Home > Mobile >  How to assign new column to existing DataFrame in pandas
How to assign new column to existing DataFrame in pandas

Time:10-28

I'm new to pandas. I'm trying to add new columns to my existing DataFrame but It's not getting assigned don't know why can anyone explain me what I'm missing this is what i tried

import pandas as pd
df = pd.DataFrame(data = {"test":["mkt1","mkt2","mkt3"],
                         "test2":["cty1","cty2","cty3"]})
print("Before",df.columns)
df.assign(test3="Hello")
print("After",df.columns)

Output

Before Index(['test', 'test2'], dtype='object')
After Index(['test', 'test2'], dtype='object')

CodePudding user response:

Pandas assign method returns a new modified dataframe with a new column, it does not modify it in place.

import pandas as pd
df = pd.DataFrame(data = {"test":["mkt1","mkt2","mkt3"],
                         "test2":["cty1","cty2","cty3"]})
print("Before",df.columns)
df = df.assign(test3="Hello") # <--- Note the variable reassingment
print("After",df.columns)
  • Related