0

I am trying to fill the dataframe with certain condition but I can not find the appropriate solution. I have a bit larger dataframe bet let's say that my pandas dataframe looks like this:

0 1 2 3 4 5
0.32 0.40 0.60 1.20 3.40 0.00
0.17 0.12 0.00 1.30 2.42 0.00
0.31 0.90 0.80 1.24 4.35 0.00
0.39 0.00 0.90 1.50 1.40 0.00

And I want to update the values, so that if 0.00 appears once in a row (row 2 and 4) that until the end all the values are 0.00. Something like this:

0 1 2 3 4 5
0.32 0.40 0.60 1.20 3.40 0.00
0.17 0.12 0.00 0.00 0.00 0.00
0.31 0.90 0.80 1.24 4.35 0.00
0.39 0.00 0.00 0.00 0.00 0.00

I have tried with

for t in range (1,T-1):
    data= np.where(df[t-1]==0,0,df[t])

and several others ways but I couldn't get what I want.

Thanks!

Boom
  • 31
  • 5
  • Please check [How to make pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). – MagnusO_O Oct 16 '22 at 16:42

1 Answers1

2

Try as follows:

  • Select from df with df.eq(0). This will get us all zeros and the rest as NaN values.
  • Now, add df.ffill along axis=1. This will continue all the zeros through to the end of each row.
  • Finally, change the dtype to bool by chaining df.astype, thus turning all zeros into False, and all NaN values into True.
  • We feed the result to df.where. For all True values, we'll pick from the df itself, for all False values, we'll insert 0.
df = df.where(df[df.eq(0)].ffill(axis=1).astype(bool), 0)

print(df)

      0     1    2     3     4    5
0  0.32  0.40  0.6  1.20  3.40  0.0
1  0.17  0.12  0.0  0.00  0.00  0.0
2  0.31  0.90  0.8  1.24  4.35  0.0
3  0.39  0.00  0.0  0.00  0.00  0.0
ouroboros1
  • 9,113
  • 3
  • 7
  • 26