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
謝謝juniper- for你很好的解釋。 –