2014-03-14 163 views
1

在下面的熊貓DataFrame熊貓數據幀格式輸出

df = pd.DataFrame({'session' : ["1","1","2","2","3","3"], 
       'path' : ["p1","p2","p1","p2","p2","p3"], 'seconds' : ["20","21","132","10","24","45"]}) 

我需要得到像下面這樣的輸出。 (Pages as columns,sessions as rows and seconds in each cell。)

session,p1,p2,p3 
1,20,21,0 
2,132,10,0 
3,0,24,45 

我到目前爲止所做的工作。

In [76]: wordlist = ['p1', 'p2', 'p3'] 
In [77]: df2 = pd.DataFrame(df.groupby('session').apply(lambda x: ','.join(x.path))) 
In [78]: df2 #I have renamed the columns 
Out[78]: 

        path 
     session  
     1  p1,p2 
     2  p1,p2 
     3  p2,p3 

In [79]: df3 = pd.DataFrame(df.groupby('session').apply(lambda x: ','.join(x.seconds.astype(str)))) 
In [80]: df3 #I have renamed the columns 
Out[80]: 
        path 
     session   
     1   20,21 
     2  132,10 
     3   24,45 

以下只是給出了布爾結果。我需要得到我的預期輸出。對此有何幫助?

In [84]: pd.DataFrame({name : df2["path"].str.contains(name) for name in wordlist}) 
Out[84]: 
      p1 p2  p3 
session      
1   True True False 
2   True True False 
3  False True True 

回答

2

使用數據透視表:

df.pivot(index='session', columns='path') 

然後替換所有楠與零:

df2 = df1.fillna(0) 

這給你以下的輸出:

 seconds   
path   p1 p2 p3 
session     
1   20 21 0 
2   132 10 0 
3    0 24 45 

然後你可能想要刪除多索引列:

df1.columns = df1.columns.droplevel(0) 

屈服所需的解決方案(沒有引號):

path  p1 p2 p3 
session    
1   20 21 0 
2  132 10 0 
3   0 24 45 

最後,你可以使用StringIO其轉換爲逗號分隔的字符串:

import StringIO 
s = StringIO.StringIO() 
df1.to_csv(s) 
print s.getvalue() 

用下面的輸出:

session,p1,p2,p3 
1,20,21,0 
2,132,10,0 
3,0,24,45 
+0

謝謝juniper- for你很好的解釋。 –