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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With