Reputation: 154454
If I have a DataFrame
:
students = pd.DataFrame([
['Alex'],
['Lauren'],
])
How can I concatenate a Series
and create a new DataFrame
? For example, I'd like:
>>> marks = pd.Series([.8, .75])
>>> students.concat(marks).values
[['Alex', .8],
['Lauren', .75]]
I know that I could use:
students['marks'] = marks
But that would mutate students
.
I've tried:
>>> pd.concat([students, marks])
…
AttributeError: 'Series' object has no attribute '_data'
Upvotes: 21
Views: 28400
Reputation: 281
In this case I would normally do
students["marks"] = marks
But pd.concat
works as well.
Upvotes: 0
Reputation: 48307
You can convert to DataFrame and concatenate afterwards:
>>> pd.concat([students, pd.DataFrame(marks)], axis=1)
0 0
0 Alex 0.80
1 Lauren 0.75
Upvotes: 29
Reputation: 4894
To retain your original dataframe, you could first copy the dataframe, and then add the column:
students2 = students.copy(deep=True)
students2['marks'] = marks
Upvotes: 1