Reputation: 31
I have a data frame like this
df
Col A Col B Col C
25 1 2
NaN 3 1
27 2 3
29 3 1
I want to fill Nan values in col A based on Col C and Col B.
My output df should be like this
25 1 2
29 3 1
27 2 3
29 3 1
I have tried this code df.groupby(['Col B','Col C']).ffill()
but didnt worked.Any suggestion will be helpful
Upvotes: 2
Views: 43
Reputation: 323316
You can try
df.fillna(df.groupby(['ColB','ColC']).transform('first'),inplace=True)
df
Out[386]:
ColA ColB ColC
0 25.0 1 2
1 29.0 3 1
2 27.0 2 3
3 29.0 3 1
Upvotes: 0
Reputation: 1614
Here you go:
df['Col A'] = df["Col A"].fillna(df.groupby(['Col B','Col C'])["Col A"].transform(lambda x: x.mean()))
print(df)
Prints:
Col A Col B Col C
0 25.0 1 2
1 29.0 3 1
2 27.0 2 3
3 29.0 3 1
Upvotes: 1