2014-02-17 328 views
7

的一部分,我有以下數據框:移調一個大熊貓據幀

>>> df 
Out[15]: 
     group type amount number 
0 group_A buy  100  123 
1 group_A view  0  111 
2 group_B view  0  222 
3 group_A view  0  222 

我想透視數據,這樣我結束了:

   type group_A group_B 
0 amount buy  100   0 
1 number buy  0  123 
2 number view  333  222 

如何做到這一點?

回答

3

使用:

df=pd.DataFrame([['group_A','buy',100,123],['group_A','view',0,111],['group_B','view',0,222],['group_A','view',0,222]],columns=['group','type','amount','number']) 

首先總和指數和定向:

df = df[~((df['group_A']==0) | (df['group_B']==0))] 

Fillna的:

>>> df.fillna(0) 
group level_0 type group_A group_B 
0  amount buy  100  0 
2  number buy  123  0 
3  number view  333  222 
這都是零

>>> df = df.groupby(['type','group']).sum().transpose().stack(0).reset_index() 
>>> df 
group level_0 type group_A group_B 
0  amount buy  100  NaN 
1  amount view  0  0 
2  number buy  123  NaN 
3  number view  333  222 

刪除行

這裏有幾處有點猜測,但它應該給你一個開始。

+0

謝謝。我試圖使用多索引,但這是非常簡單的。 – greenafrican