简体   繁体   中英

Python Dataframe Column value update for multi condition

Hello i want to simplfy the code below. It works but i want to create a dictionary for C9, 4A, C8 and want to do the same code with a single statement.

df.loc[df["Column"] =="C9","New_Column"]="LCV"
df.loc[df["Column"] =="4A"," New_Column"]="LCV"
df.loc[df["Column"] =="C8","New Column"]="LCV"

there is 10 lines of statament like that. If the column value is C9 or 4A or C8 i want to update the new column value to LCV.

i will be grateful if you can help me.

Best Regards..

Use pd.Series.isin :

>>> df.loc[df["Column"].isin(["4A", "C8", "C9"]),"New_Column"]="LCV"

Try:

values = ["C9", "4A", "C8"]
df.loc[df["Column"].isin(values), "New_Column"]="LCV"

I use apply function, and I passed to it a lambda function that will check each row if the column value is in the items it will put the "LVC" to the value of New_Column otherwise it will put None.

items = ["C9", "4A", "C8"]
df["New_Column"] = df.apply(lambda row: "LVC" if row.Column in items else None, axis = 1) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM