Home > Net >  Modify data in rows and columns with conditions in pandas
Modify data in rows and columns with conditions in pandas

Time:09-20

I want to modify a specific data points in the pandas data frame under a condition. For example in the following table, I want to divide the data by 2 in column A where only row values of column B is greater than 1.

Column A Column B
1 1
2 1
3 1
4 2
5 2
6 2
7 1
8 1

Expected output :

Column A Column B
1 1
2 1
3 1
2 2
2.5 2
3 2
7 1
8 1

How can I modify the data frame with pandas?

CodePudding user response:

df.loc[df["Column B"] > 1,"Column A"] = df["Column A"]/2

Hope it Helps...

CodePudding user response:

you can try 'where' which takes the opposite condition and replaces it with the values.

import pandas as pd

data=pd.DataFrame(data={'A':[1,2,3,4,5,6,7,8],'B':[1,1,1,2,2,2,1,1]})
data.A=data.A.where(data.B<=1,data.A/2)

CodePudding user response:

try this:

df["A"]=df.apply(lambda x:x["A"]/2 if x["B"]>1 else x["A"],axis=1)
  • Related