如果您在寻找关于如何在索引上合并
DataFrame
和Series
的信息,请查看这个答案。原始提问者的初衷是想知道如何将系列元素分配为另一个DataFrame的列。如果您有兴趣了解答案,请查看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
df
和s
的定义,这个答案返回的是一个空数据框,而不是问题所要求的结果。我们不想按索引匹配;我们想要将s
值广播到df
的所有行。 - CPBL