Pandas: Grouping by one value + new column about this group
I have this dataframe:
Player Country
0 Peter USA
1 Louis France
2 Andrew France
3 Peter Spain
4 Michael Spain
5 Alfred USA
6 Peter France
7 Michael USA
8 Andrew USA
9 Michael Spain
I need to create a new dataframe grouping the column Player by the names and, besides, I have to create a new column where the result depends on the column Country. I need this column (called Availability) to say 'Yes' if in the countries appears a country different to Spain or USA. So the result in the new dataframe would be:
Player Availability
0 Peter Yes
1 Louis Yes
2 Andrew Yes
3 Michael No
4 Alfred No
Any suggestion about how to do it? Thanks in advance.
Solution 1:
Use:
new_df = (~df['Country'].str.contains('USA|Spain', regex=True))\
.groupby(df['Player'], sort=False).any().reset_index(name='Availability')\
.assign(Availability=lambda df: df['Availability'].map({True : 'Yes',
False: 'No'}))
Player Availability
0 Peter Yes
1 Louis Yes
2 Andrew Yes
3 Michael No
4 Alfred No