<小时/>If you came here looking for information on how to merge a
DataFrame
andSeries
on the index, please look at this answer.The OP's original intention was to ask how to assign series elements as columns to another DataFrame. If you are interested in knowing the answer to this, look at the accepted answer by EdChum.
我能想到的最好的是
df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]}) # see EDIT below
s = pd.Series({'s1':5, 's2':6})
for name in s.index:
df[name] = s[name]
a b s1 s2
0 1 3 5 6
1 2 4 5 6
有人可以建议更好的语法/更快的方法吗?
我的尝试:
df.merge(s)
AttributeError: 'Series' object has no attribute 'columns'
和
df.join(s)
ValueError: Other Series must have a name
编辑发布的前两个答案突出显示了我的问题的一个问题,因此请使用以下内容构建df
:
df = pd.DataFrame({'a':[np.nan, 2, 3], 'b':[4, 5, 6]}, index=[3, 5, 6])
最终结果
a b s1 s2
3 NaN 4 5 6
5 2 5 5 6
6 3 6 5 6
最佳答案
更新
从 v0.24.0 开始,您可以 merge在 DataFrame 和 Series 上,只要 Series 被命名。
df.merge(s.rename('new'), left_index=True, right_index=True)
# If series is already named,
# df.merge(s, left_index=True, right_index=True)
<小时/>
现在,您可以使用 to_frame() 将系列简单地转换为 DataFrame 。所以(如果加入索引):
df.merge(s.to_frame(), left_index=True, right_index=True)
关于python - 如何合并Series和DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55542535/