4 回答
TA贡献1804条经验 获得超7个赞
您可以df.apply
与*一起使用pd.value_counts
df.apply(pd.value_counts).T
bronze gold silver
Canada 1 2 1
China 1 1 2
South Korea 2 1 1
* 我没有找到 的文档pd.value_counts
,因此将 github 链接链接到该函数。
编辑:在阅读源代码时pd.Series.value_counts
只需调用pd.value_counts
TA贡献1830条经验 获得超3个赞
w = df.melt()
variable value
0 Canada gold
1 Canada silver
2 Canada gold
3 Canada bronze
4 China bronze
5 China gold
6 China silver
7 China silver
8 South Korea silver
9 South Korea bronze
10 South Korea bronze
11 South Korea gold
进而:
pd.crosstab(w['variable'],w['value'])
期望的结果:
value bronze gold silver
variable
Canada 1 2 1
China 1 1 2
South Korea 2 1 1
TA贡献1797条经验 获得超6个赞
使用pd.get_dummies和sum
pd.get_dummies(df.T, prefix='',prefix_sep='').sum(level=0,axis=1)
Out[995]:
bronze gold silver
Canada 1 2 1
China 1 1 2
South Korea 2 1 1
TA贡献1847条经验 获得超11个赞
df = pd.DataFrame([('gold', 'bronze', 'silver'),
('silver', 'gold', 'bronze'),
('gold', 'silver', 'bronze'),
('bronze', 'silver', 'gold')],
columns=('Canada', 'China', 'South Korea')).transpose()
df.apply(pd.value_counts,axis=1)
添加回答
举报