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
concat series onto dataframe with column name
提问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 concat
method 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
回答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)