0

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

3 Answers 3

2

Use pd.Series.isin:

>>> df.loc[df["Column"].isin(["4A", "C8", "C9"]),"New_Column"]="LCV"
Sign up to request clarification or add additional context in comments.

Comments

0

Try:

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

Comments

0

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) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.