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

编辑发布的前两个答案突出显示了我的问题的一个问题,因此请使用以下内容构建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/

相关文章:

python - 在 pandas read_sql 中可选择 SQLalchemy 的方法

java - Jenkins 命令显示目录中的所有文件?

Python v3 日志记录

python - 对两列进行分组并计算第三列中的唯一值

python - 如何根据多个条件将值插入数据框?逻辑问题

python - Pandas ,读入文件时列之间没有分隔符

python - 当模板具有内联 JS 时缩小 Flask 应用程序?

python - 如何根据具有特定标识符的选定值(在该组行内)减去一组行

python - 读取 excel 文件时将转换器应用于所有列,Python 3.6

json - 如何在名称/值对中将 R 数据帧转换为 Json?