python - 沿着具有非唯一索引的列连接两个数据框

标签 python pandas dataframe join merge

我有两个数据框,我想将它们按列连接起来。索引不是唯一的:

df1 = pd.DataFrame({'A': ['0', '1', '2', '2'],'B': ['B0', 'B1', 'B2', 'B3'],'C': ['C0', 'C1', 'C2', 'C3']}):
    A   B   C
0  0  B0  C0
1  1  B1  C1
2  2  B2  C2
3  2  B3  C3

df2 = pd.DataFrame({'A': ['0', '2', '3'],'E': ['E0', 'E1', 'E2']},index=[0, 2, 3])
    A   E
0  0  E0
1  2  E1
2  3  E2

A 应该是我的索引。我想要的是:

    A   B   C   E
0  0  B0  C0    E0
1  1  B1  C1    NAN
2  2  B2  C2    E1
3  2  B3  C3    E1

这个 pd.concat([df1, df2], 1) 给我错误:

Reindexing only valid with uniquely valued Index objects

最佳答案

也许您正在寻找左外 merge .

df1.merge(df2, how='left')
   A   B   C    E
0  0  B0  C0   E0
1  1  B1  C1  NaN
2  2  B2  C2   E1
3  2  B3  C3   E1

关于python - 沿着具有非唯一索引的列连接两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46820068/

相关文章:

python - 麻雀 : TypeError: an integer is required (got type str)

python - 条件在过滤数据帧行时单独起作用,但不能一起起作用[ValueError : The truth value of a Series is ambiguous]

python - 为 Pandas 数据框中B列中的绝对数字分配A列中的相同值

python - 如何使用 value_counts() 返回的值进行进一步计算?

python-3.x - 如何从另一个数据框中获取一个数据框中的公共(public)列的值?

python - 如何内置对 python 调用的跟踪功能?

python - Sqlalchemy 多次插入失败,列名中有百分比符号 (%)

python - __await__ 是否需要成为生成器?

r - 获取需要匹配 R 中其他列的条件的平均值

python - 使用内置 Python 模块填写 Web 表单数据