我有一個如下所示的pandas資料框:
mydict ={
'person': ['Jenny', 'Jenny', 'David', 'David', 'Max', 'Max'],
'fruit': ['Apple', 'Orange', 'Apple', 'Orange', 'Apple', 'Orange'],
'eaten': [25, 75, 15, 5, 10, 10]
}
df = pd.DataFrame(mydict)
person fruit eaten
Jenny Apple 25
Jenny Orange 75
David Apple 15
David Orange 5
Max Apple 10
Max Orange 10
我想轉換成:
person apple_percentage orange_percentage
Jenny 0.25 0.75
David 0.75 0.25
Max 0.50 0.50
我猜我將不得不以groupby某種方式使用它來做到這一點,但無法找到一種干凈的 Pythonic 方式來做到這一點?
uj5u.com熱心網友回復:
使用DataFrame.pivot與除以sumS:
df = df.pivot('person','fruit','eaten').add_suffix('_percentage')
df = df.div(df.sum(axis=1), axis=0)
print (df)
fruit Apple_percentage Orange_percentage
person
David 0.75 0.25
Jenny 0.25 0.75
Max 0.50 0.50
uj5u.com熱心網友回復:
另一種選擇是熊貓的交叉表:
pd.crosstab(index = df.person,
columns = df.fruit,
values = df.eaten,
aggfunc = 'mean',
normalize='index')
fruit Apple Orange
person
David 0.75 0.25
Jenny 0.25 0.75
Max 0.50 0.50
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360275.html
標籤:Python 熊猫 数据框 pandas-groupby
上一篇:在用另一列中的值替換資料框中的NaN值時應用for回圈
下一篇:每小時行數
