bmaster69
bmaster69

Reputation: 131

How to see if column name exists in a dataframe, and if not create the column with a default value?

I want to add a Column_4 when Column_4 does not exists in the dataframe. How do I search for it, and if no match create the new column?

Column_1   Column_2  Clolumn_3 

1             4         7
2             5         8
3             6         9 

Since Column_4 is not available, add Column_4 with value of 10

Column_1   Column_2  Clolumn_3  Column_4

1             4         7          10
2             5         8          10  
3             6         9          10

Upvotes: 0

Views: 5242

Answers (1)

noah
noah

Reputation: 2786

Check if the column name is in the columns list. If not make it 10:

if("Col_4" in df.columns):
    print("Col_4 exists")
else:
    df["Col_4"] = 10

Upvotes: 1

Related Questions