Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I concatenate a Series onto a DataFrame with Pandas?

Tags:

python

pandas

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'
like image 738
David Wolever Avatar asked Dec 11 '13 06:12

David Wolever


People also ask

How do I concatenate a series to a DataFrame Pandas?

append() to Combine Two Series. You can use pandas. DataFrame(Series. append(Series,ignore_index=True)) to create a DataFrame by appending series to another series.

How do I merge a series list into a DataFrame?

To combine multiple Series into a single DataFrame, use the concat(~) method or the DataFrame(~) constructor.

Can you append a series to a DataFrame?

Pandas DataFrame. append() will append rows (add rows) of other DataFrame, Series, Dictionary or list of these to another DataFrame.


1 Answers

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
like image 110
alko Avatar answered Oct 10 '22 06:10

alko