Ad

Pandas Dataframe Two Column Condition And Replace

- 1 answer

I have a data-frame in that i want to put filter or condition for particularly for two column want change the values if values not pass the threshold change to zero, I know that I can do it with convert to separate dataframe do the filter and merge is there any other efficient way i cando, please suggest me

import pandas as pd

df = pd.DataFrame({"User": ["user1", "user2", "user2", "user3", "user2", "user1"],
                  "Amount": [10.0, 1.0, 8.0, 2, 7.5, 8.0],
                  "Amount2": [1, 5.0, 8.0, 10.5, 0, 8.0]})

output i want >2 threshold

User  Amount  Amount2

user1    10.0      0.0
user2     0.0      5.0
user2     8.0      8.0
user3     0.0     10.5
user2     7.5      0.0
user1     8.0      8.0

Thank you

Ad

Answer

You can clip value below 2 to 2 then replace 2 to 0

df[['Amount', 'Amount2']] = df[['Amount', 'Amount2']].clip(lower=2).replace(2, 0)
print(df)

    User  Amount  Amount2
0  user1    10.0      0.0
1  user2     0.0      5.0
2  user2     8.0      8.0
3  user3     0.0     10.5
4  user2     7.5      0.0
5  user1     8.0      8.0
Ad
source: stackoverflow.com
Ad