Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Replace all 0's in first row with next non-zero value in column?

Tags:

python

pandas

I have a csv like the following:

enter image description here

I want to replace any 0 in the first row with the next non-0 value in that column - eg. in the above the first row in the 'momentum_ao' should change to 0.1439166667, the first first row of the 'others_dlr' column should be 0.9153612171 etc (the second row and lower will be unchanged). How should this be done in pandas? This csv has dozens of columns, so I'd want a solution that doesn't involve manually typing in and iterating through columns one-by-one.

like image 537
ZhouW Avatar asked Nov 15 '25 16:11

ZhouW


1 Answers

This should get the job done. Just fill the zeroes with np.nan values, backfill, and take the first row and reassign it to the original dataframe.

df.iloc[0, :] = df.replace(0, np.nan).bfill().iloc[0, :]
like image 165
Alexander Avatar answered Nov 18 '25 05:11

Alexander



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!