python - 如何合并 Series 和 DataFrame

标签 python pandas dataframe

If you came here looking for information on how to merge a DataFrame and Series 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/

相关文章:

python - 从多个 Excel 文件创建 Pandas 数据框

Python 正则表达式 : Internal reoccurring spaces only

python - 将 python 图扩展到全屏

python - 正则表达式 - 在字符串中查找最后找到的符号的位置

python - 在 Pandas 中使用 For 循环的数据框

python - 在 python pandas 中指定多重索引的顺序

python - 如何在spark中设置驱动程序的python版本?

python - 通过对具有数字和字符串变量的 Dataframe 进行分组来转置

python - pandas - 如果存在部分字符串匹配,则将值放入新列中

python - pandas dataframe将函数应用于具有nans的列