熊猫:按列元素分组

莱文

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如果我应该创建字典,则不确定是否是最好的选择。在此先感谢您的帮助!

安东·普罗托波夫(Anton Protopopov)

您可以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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章