group by
在Pandas df中寻找对列元素的帮助。
原始df:
Country Feature Number
0 US A 1
1 DE A 2
2 FR A 3
3 US B 0
4 DE B 5
5 FR B 7
6 US C 9
7 DE C 0
8 FR C 1
所需的df:
Country A B C
0 US 1 0 9
1 DE 2 5 0
2 FR 3 7 1
group by
如果我应该创建字典,则不确定是否是最好的选择。在此先感谢您的帮助!
您可以pivot_table
为此使用:
In [39]: df.pivot_table(index='Country', columns='Feature')
Out[39]:
Number
Feature A B C
Country
DE 2 5 0
FR 3 7 1
US 1 0 9
如果您希望索引为0、1、2,则可以使用 reset_index
编辑
如果您Number
实际上不是数字而是字符串,则可以使用astype
或将该列转换为pd.to_numeric
:
df.Number = df.Number.astype(float)
或者:
df.Number = pd.to_numeric(df.Number)
注意:pd.to_numeric
仅适用于熊猫>= 0.17.0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句