简体   繁体   中英

How to assign new column to existing DataFrame in pandas

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')

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM