Alex Rothberg
Alex Rothberg

Reputation: 10993

Add Column to Pandas DataFrame Not in Place

How do I add a Series as a new column to a Pandas DataFrame and get back a new DataFrame (i.e NOT in place).

This works, but is in place:

A["name"] = s

Upvotes: 18

Views: 5189

Answers (3)

Zero
Zero

Reputation: 76927

From 0.16.0 onwards, you can use assign -- returns a new object (a copy) with all the original columns in addition to the new ones.

In [483]: A.assign(name=s)
Out[483]:
          0         1  name
0  0.876880  0.915174     0
1  0.644664  0.305387     1
2  0.930093  0.562453     2
3  0.807626  0.498871     3

Details

In [484]: A
Out[484]:
          0         1
0  0.876880  0.915174
1  0.644664  0.305387
2  0.930093  0.562453
3  0.807626  0.498871

In [485]: s
Out[485]:
0    0
1    1
2    2
3    3
dtype: int64

Upvotes: 21

TomAugspurger
TomAugspurger

Reputation: 28946

If A is your DataFrame and s is the series.

df2 = A.copy()
df2['name'] = s

Upvotes: 0

waitingkuo
waitingkuo

Reputation: 93824

Not sure whether there's any more elegant way, but this works to me:

df = pd.concat( [A, pd.DataFrame(s)], axis=1 )

Upvotes: 6

Related Questions