Pandas create dataframe column by assigning a value to matching records

Viewed 24

I have a Pandas dataframe and I want to assign a value to a nonexisting column by setting the value to records that match a criteria. This is my attempt:

criteria = ["XX", "XY", "XYY"]
dataframe.loc[dataframe["criteria_column"].isin(criteria)]["new_column"] = 1000

dataframe["new_column"]

The problem is that this code is raising the following error:

KeyError: 'new_column'

I tried the code with a dataframe whose all records match the criteria, and got the same error.

1 Answers

try with

df.loc[df['criteria_column'].isin(criteria),"new_colum"]= 1000
Related