如何使用 Pandas 将 Series 连接到 DataFrame 上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20512297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:26:07  来源:igfitidea点击:

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

pythonpandas

提问by David Wolever

If I have a DataFrame:

如果我有一个DataFrame

students = pd.DataFrame([
    ['Alex'],
    ['Lauren'],
])

How can I concatenate a Seriesand create a new DataFrame? For example, I'd like:

如何连接 aSeries并创建一个新的DataFrame?例如,我想:

>>> 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.

但那会发生变异students

I've tried:

我试过了:

 >>> pd.concat([students, marks])
 …
 AttributeError: 'Series' object has no attribute '_data'

回答by alko

You can convert to DataFrame and concatenate afterwards:

您可以转换为 DataFrame 并在之后进行连接:

>>> pd.concat([students, pd.DataFrame(marks)], axis=1)
        0     0
0    Alex  0.80
1  Lauren  0.75

回答by qmorgan

To retain your original dataframe, you could first copy the dataframe, and then add the column:

要保留原始数据框,您可以先复制数据框,然后添加列:

students2 = students.copy(deep=True)
students2['marks'] = marks

回答by jvns

In this case I would normally do

在这种情况下,我通常会做

students["marks"] = marks

students["marks"] = marks

But pd.concatworks as well.

pd.concat也有效。