country count
Argentina 3
Argentina 4
Argentina NaN
Wales 1
Wales 3
Wales NaN
Nan values, I want to make a minimum of the values that share the same countries as the NaN value.
Output Should Be:
Argentina 3
Argentina 4
Argentina 3
Wales 1
Wales 3
Wales 1
I tried bfill method but didn't manage this. Thank You For Help
CodePudding user response:
One way is using map
, groupby
and fillna
map
allows you to match by an index, when you create a groupby object it defaults to creating an index, (as_index=True
) so it's pretty simple to map it back to your main dataframe.
df['count'] = df['count'].fillna(
df['country'].map(df.groupby('country')['count'].min()))
print(df)
country count
0 Argentina 3.0
1 Argentina 4.0
2 Argentina 3.0
3 Wales 1.0
4 Wales 3.0
5 Wales 1.0
a simplier method is to use .transform
which applies groupby operations without modifying the index
df['count'] = df['count'].fillna(
df.groupby('country')['count'].transform('min'))
country count
0 Argentina 3.0
1 Argentina 4.0
2 Argentina 3.0
3 Wales 1.0
4 Wales 3.0
5 Wales 1.0