Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill some empty cell of a column with the previous row cell of the previous column in pandas?

Tags:

python

pandas

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

like image 654
Yogesh Govindan Avatar asked Dec 12 '25 12:12

Yogesh Govindan


1 Answers

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'])
like image 79
Mayank Porwal Avatar answered Dec 15 '25 05:12

Mayank Porwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!