2014-02-07 135 views
2

比方說,我有這樣的數據幀:重塑數據幀

df = pd.DataFrame({'n':[0 ,1 ,0 ,0 ,1 ,1 ,0 ,1],'l':[12 ,16 ,92, 77 ,32 ,47, 22, 14], 'cols':['col1','col1','col1','col1','col2','col2','col2','col2']}) 

,這就是我想要得到:

col1 col2 
l n l n 
12 0 32 1 
16 1 47 1 
92 0 22 0 
77 0 14 1 

我一直在​​和玩弄stack/unstack方法,但沒有成功...

回答

1
import pandas as pd 

df = pd.DataFrame(
    {'n':[0 ,1 ,0 ,0 ,1 ,1 ,0 ,1],'l':[12 ,16 ,92, 77 ,32 ,47, 22, 14], 
    'cols':['col1','col1','col1','col1','col2','col2','col2','col2']}) 

df['index'] = df.groupby(['cols']).cumcount() 
result = df.pivot(index='index', columns='cols') 
print(result) 
#   l   n  
# cols col1 col2 col1 col2 
# index       
# 0  12 32  0  1 
# 1  16 47  1  1 
# 2  92 22  0  0 
# 3  77 14  0  1 

如果你關心的ORD在多指標列標籤的呃,你可以使用 棧和出棧,以精確地再現結果你貼:

result = result.stack(level=0).unstack(level=1) 
print(result) 

# cols col1  col2 
#   l n  l n 
# index     
# 0  12 0 32 1 
# 1  16 1 47 1 
# 2  92 0 22 0 
# 3  77 0 14 1 

當尋找一個解決方案往往是向後覺得有用。

從所需的DataFrame開始,並問自己可能會產生所需的DataFrame的哪個操作會導致 。在這種情況下,想到的操作 是pd.pivot。接下來的問題是, something,所需要的數據幀,使

desired = something.pivot(index='index', columns='cols') 

通過觀察在行動pivotother examples,顯然比something不得不等於

cols l n index 
0 col1 12 0  0 
1 col1 16 1  1 
2 col1 92 0  2 
3 col1 77 0  3 
4 col2 32 1  0 
5 col2 47 1  1 
6 col2 22 0  2 
7 col2 14 1  3 

然後你看是否你可以找到一種方法來將df分成something,再 向後按摩something分成df ...從這個角度來看,在 這種情況下,缺失的鏈接變得明顯:something有一個index列 即df缺乏。

+0

感謝偉大的解釋! – HappyPy

0

您可以使用DataFrame.groupbyDataFrame.reset_indexDataFrame.T組合(轉)

import pandas as pd 

df = pd.DataFrame({'n':[0 ,1 ,0 ,0 ,1 ,1 ,0, 1],'l':[12 ,16 ,92, 77 ,32 ,47, 22, 14], 'cols':['col1','col1','col1','col1','col2','col2','col2','col2']}) 
print df.groupby('cols').apply(lambda x: x.reset_index(drop=True).drop('cols',axis=1).T).T 

輸出:

cols col1  col2 
     l n  l n 
0  12 0 32 1 
1  16 1 47 1 
2  92 0 22 0 
3  77 0 14 1 

或者你可以使用concat

print pd.concat([g.drop('cols',axis=1).reset_index(drop=True) for _,g in df.groupby('cols')],axis=1,keys=df['cols'].unique()) 

輸出:

col1  col2 
     l n  l n 
0 12 0 32 1 
1 16 1 47 1 
2 92 0 22 0 
3 77 0 14 1 

希望它能幫助,:)