Okyay Sönmez
Okyay Sönmez

Reputation: 15

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..

Upvotes: 0

Views: 42

Answers (3)

Azzedine
Azzedine

Reputation: 505

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) 

Upvotes: 0

frab
frab

Reputation: 1173

Try:

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

Upvotes: 0

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

Use pd.Series.isin:

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

Upvotes: 2

Related Questions