Max
Max

Reputation: 471

How to fill nan based on first value?

imagine you have the following df:

d = {'description#1': ['happy', 'coding', np.nan], 'description#2': [np.nan, np.nan, np.nan], 'description#3': [np.nan, np.nan, np.nan]}
dffinalselection= pd.DataFrame(data=d)
dffinalselection


description#1   description#2   description#3
0   happy            NaN          NaN
1   coding            NaN         NaN
2   NaN               NaN         NaN

I want to fill the df with the first description#1 column value if NaN:

filldesc = dffinalselection.filter(like='description')
filldesc = filldesc.fillna(dffinalselection['description#1'], axis=1)
filldesc

However, getting the following error:

NotImplementedError: Currently only can fill with dict/Series column by column

How to workaround?

desired output:

description#1   description#2   description#3
0   happy            happy        happy
1   coding            coding      coding
2   NaN               NaN         NaN

Please help!

Upvotes: 0

Views: 163

Answers (2)

Ynjxsjmh
Ynjxsjmh

Reputation: 30050

You can use apply() on rows with axis=1 then use Series.fillna() to fill nan values.

import pandas as pd
import numpy as np

d = {'description#1': ['happy', 'coding', np.nan], 'description#2': [np.nan, 'tokeep', np.nan], 'description#3': [np.nan, np.nan, np.nan]}

dffinalselection = pd.DataFrame(data=d)

df_ = dffinalselection.apply(lambda row: row.fillna(row[0]), axis=1)
print(df_)

  description#1 description#2 description#3
0         happy         happy         happy
1        coding        tokeep        coding
2           NaN           NaN           NaN

Upvotes: 2

Use ffill method with axis=1:

dffinalselection.ffill(axis=1)

Upvotes: 1

Related Questions