pandas 使用列名将系列连接到数据框上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39047915/
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-08 15:44:43  来源:igfitidea点击:

concat series onto dataframe with column name

pandasdataframerenameseries

提问by vaer-k

I want to add a Series (s) to a Pandas DataFrame (df) as a new column. The series has more values than there are rows in the dataframe, so I am using the concatmethod along axis 1.

我想将 Series ( s)添加到 Pandas DataFrame ( df) 作为新列。该系列的值多于数据框中的行数,因此我concat沿轴 1使用该方法。

df = pd.concat((df, s), axis=1)

df = pd.concat((df, s), axis=1)

This works, but the new column of the dataframe representing the series is given an arbitrary numerical column name, and I would like this column to have a specific name instead.

这是有效的,但表示该系列的数据框的新列被赋予了一个任意数字列名,我希望该列有一个特定的名称。

Is there a way to add a series to a dataframe, when the series is longer than the rows of the dataframe, and with a specified column name in the resulting dataframe?

当系列比数据帧的行长并且在结果数据帧中具有指定的列名时,有没有办法将系列添加到数据帧?

回答by jezrael

You can try Series.rename:

你可以试试Series.rename

df = pd.concat((df, s.rename('col')), axis=1)

回答by vaer-k

Of course, after many minutes of trying this, I figured out the answer on my own immediately after posting the question. The answer is simply to specify the name when creating the series:

当然,经过几分钟的尝试后,我在发布问题后立即自己找出了答案。答案只是在创建系列时指定名称:

example_scores = pd.Series([1,2,3,4], index=['t1', 't2', 't3', 't4'], name='example_scores')

example_scores = pd.Series([1,2,3,4], index=['t1', 't2', 't3', 't4'], name='example_scores')

Using the name attribute when creating the series is all I needed.

我只需要在创建系列时使用 name 属性。

回答by piRSquared

Try:

尝试:

df = pd.concat((df, s.rename('CoolColumnName')), axis=1)