Reputation: 391
I am trying to fill some empty row cell of a column with the corresponding previous row cell. However i am not getting the right solution:
df = pd.DataFrame({'A':[1, 2, 3, 4, 5], 'B':[6, 7, '', '', 10]})
df.replace('', np.nan)
df.fillna(method='ffill')
The result is still empty. i would like to fill empty cell of column B with 3 and 4 from column A
Upvotes: 3
Views: 100
Reputation: 34086
Use df.ffill
with axis=1
:
In [2466]: df = df.replace('', np.nan).ffill(axis=1)
In [2451]: df
Out[2451]:
A B
0 1 6.0
1 2 7.0
2 3 3.0
3 4 4.0
OR:
Use Series.combine_first
:
In [2441]: df = df.replace('', np.nan)
In [2450]: df['B'] = df['B'].combine_first(df['A'])
OR use Series.fillna
:
In [2441]: df = df.replace('', np.nan)
In [2457]: df['B'] = df['B'].fillna(df['A'])
Upvotes: 3