Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

df.loc change more than one column based on condition

What I want to try is change more than one column based on condition.

Example("Data just for the explanation") =>

import pandas as pd


data = {'s' : ["placementTop","placementProductPage","safgasf", "aslgkmalksg", "ıowjsakguıwa", "placementTop","placementProductPage", "placementTop","placementProductPage",], "State": ["enabled","paused","sagasg", "sagaskg", "sagkşlaksg", "sagaskg", "sagkşlaksg", "sagaskg", "sagkşlaksg"], "x": [10,20,25,30,5,30,5,30,5], "y" : [12,20,25,30,5,20,25,30,5]}

df = pd.DataFrame(data)


filter = df.loc[(df["s"] == "placementTop") & (df["State"] == "enabled"), "x"] = 2


print(df)
                      s       State   x   y
0          placementTop     enabled   2  12
1  placementProductPage      paused  20  20
2               safgasf      sagasg  25  25
3           aslgkmalksg     sagaskg  30  30
4          ıowjsakguıwa  sagkşlaksg   5   5
5          placementTop     sagaskg  30  20
6  placementProductPage  sagkşlaksg   5  25
7          placementTop     sagaskg  30  30
8  placementProductPage  sagkşlaksg   5   5

This is working for me but I want to change y column too at the same time.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This will update the x and y columns for the rows that meet the condition s == "placementTop" and State == "enabled"

df.loc[(df["s"] == "placementTop") & (df["State"] == "enabled"), ["x", "y"]] = 2

Output:

                      s       State  x   y
0          placementTop     enabled  2  2
1  placementProductPage      paused 20  20
2               safgasf      sagasg 25  25
3           aslgkmalksg     sagaskg 30  30
4          ıowjsakguıwa  sagkşlaksg  5   5
5          placementTop     sagaskg 30  20
6  placementProductPage  sagkşlaksg  5  25
7          placementTop     sagaskg 30  30
8  placementProductPage  sagkşlaksg  5   5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading