Combine rows base on name and tag their group base on appearance from original pandas dataframe

Viewed 38

How can I transform this dataframe...

name        | group
James       | 1
Mike        | 2
Tod         | 1
Rico        | 2
Billie      | 3
Mike        | 3
Tod         | 2

To this:

name        | in_group_1 | in_group_2 | in_group_3
James       | True       | False      | True
Mike        | False      | True       | True
Tod         | True       | True       | False
Rico        | False      | True       | False
Billie      | False      | False      | True

In the first dataframe, it is a combination of all people with each group. In the second dataframe, we combine rows with the same name and tag their group as True base on their groups on the first dataframe. We will also drop the group column after.

1 Answers

You could use pd.crosstab and chain astype(bool) to convert 1 and 0 to True/False:

>>> pd.crosstab(df.name, df.group).astype(bool).add_prefix('in_group_').reset_index()

group    name  in_group_1  in_group_2  in_group_3
0      Billie       False       False        True
1       James        True       False       False
2        Mike       False        True        True
3        Rico       False        True       False
4         Tod        True        True       False

Note that:

>>> pd.crosstab(df.name, df.group).add_prefix('in_group_').reset_index()

group    name  in_group_1  in_group_2  in_group_3
0      Billie           0           0           1
1       James           1           0           0
2        Mike           0           1           1
3        Rico           0           1           0
4         Tod           1           1           0
Related