Search code examples
pythonpandasdataframeconditional-statements

Modify data in rows and columns with conditions in pandas


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?


Solution

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

    Hope it Helps...