[英]Pandas: Group By Elements of a Column
Looking for assistance to group by
elements of a column in a Pandas df. 寻找协助以熊猫df栏group by
元素group by
。
Original 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
Desired df: 所需的df:
Country A B C
0 US 1 0 9
1 DE 2 5 0
2 FR 3 7 1
Not sure if group by
is the best choice if I should create a dictionary. 如果我应该创建字典group by
则不确定group by
是否是最佳选择。 Thanks in advance for your help! 在此先感谢您的帮助!
You could use pivot_table
for that: 您可以pivot_table
使用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
If you want your index to be 0, 1, 2 you could use reset_index
如果您希望索引为0、1、2,则可以使用reset_index
EDIT 编辑
If your Number
actually not numbers but strings you could convert that column with astype
or with pd.to_numeric
: 如果您的Number
实际上不是数字而是字符串,则可以使用astype
或pd.to_numeric
转换该列:
df.Number = df.Number.astype(float)
or: 要么:
df.Number = pd.to_numeric(df.Number)
Note : pd.to_numeric
is available only for pandas >= 0.17.0
注意 : pd.to_numeric
仅适用于>= 0.17.0
熊猫
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.