0

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')
5
  • assign does not occur inplace. Commented Oct 27, 2021 at 15:29
  • df = df.assign(test3="Hello")? Commented Oct 27, 2021 at 15:30
  • @It_is_Chris df = df.assign(test3="Hello") check I've added in between two print functions where should place it can you provide a solution for it Commented Oct 27, 2021 at 15:33
  • 1
    sorry what is the question? You just need to replace df.assign(test3="Hello") to df = df.assign(test3="Hello") Commented Oct 27, 2021 at 15:36
  • Hello @sophocles It's solved my problem thanks ❤️️ Commented Oct 27, 2021 at 15:39

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Hello @BSP I've got solution by sophocles but thanks for your answer ❤️️
@ I see he commented just before me. Anyway, the important idea behind your question is that pandas dataframes methods do not modify them in place but return a new modified copy. That is what I wanted to explain.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.