3 回答

TA貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
嘗試pandas 交叉表:
pd.crosstab(df.Name, df.Weight)
Weight? Above Average? ?Average Below Average
Name? ? ? ? ? ??
John? ? ? ? ? ?0? ? ? ? ? ?2? ? ? ? 0
Paul? ? ? ? ? ?0? ? ? ? ? ?0? ? ? ? 1
Darren? ? ? ? ?2? ? ? ? ? ?0? ? ? ? 0

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用 groupby 和 unstack:
df = pd.DataFrame({'Name':['John','Paul','Darren','John','Darren'],
'Weight':['Average','Below Average','Above Average','Average','Above Average']})
df = df.groupby(['Name', 'Weight'])['Weight'].count().unstack(1).fillna(0).astype(int).reset_index()
df = df.rename_axis('', axis=1).set_index('Name')
df
Out[1]:
Above Average Average Below Average
Name
Darren 2 0 0
John 0 2 0
Paul 0 0 1

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
在這里用來get dummies實(shí)現(xiàn)你所需要的
pd.get_dummies(df.set_index('Name'), dummy_na=False,prefix=[None]).groupby('Name').sum()
Above Average Average Below Average
Name
Darren 2 0 0
John 0 2 0
Paul 0 0 1
添加回答
舉報(bào)