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
EDIT 前两个回答突出显示了我的问题,所以请使用以下来构造 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 开始,只要命名了 Series,就可以合并 DataFrame 和 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() 简单地将 Series 转换为 DataFrame .所以(如果加入索引):
df.merge(s.to_frame(), left_index=True, right_index=True)
关于python - 如何合并 Series 和 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26265819/