Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Column to Pandas DataFrame Not in Place

Tags:

pandas

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
like image 997
Alex Rothberg Avatar asked Nov 06 '13 02:11

Alex Rothberg


People also ask

How do I add a column to a DataFrame in Python?

loc: loc is an integer which is the location of column where we want to insert new column. This will shift the existing column at that position to the right. column: column is a string which is name of column to be inserted. value: value is simply the value to be inserted.


1 Answers

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
like image 71
Zero Avatar answered Sep 27 '22 21:09

Zero