0

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
noah
  • 2,616
  • 13
  • 27
bmaster69
  • 121
  • 9

1 Answers1

1

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
noah
  • 2,616
  • 13
  • 27
  • It's is worth noting that there is a WHY question that should be asked here. My answer will do what you asked, but it is an odd thing to have to do in general. – noah Jan 25 '21 at 18:23
  • thanks, i have to isolate some of the issue with the code. So was hoping to use something like this to pass different value rather then crashing. Apologies coding is not my main skill set. and Thank you for your time and effort. – bmaster69 Jan 25 '21 at 18:31