简体   繁体   中英

Pandas: Group By Elements of a Column

Looking for assistance to group by elements of a column in a Pandas df.

Original 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:

    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. Thanks in advance for your help!

You could use pivot_table for that:

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

EDIT

If your Number actually not numbers but strings you could convert that column with astype or with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM