python - 合并具有重叠列的数据框

标签 python pandas dataframe

我有以下数据框:

    stores = [['AA', 12, 'Red'], ['BB', 13, 'Red'], ['BB', 14, 'Red'], ['BB', 15, 'Red']]
    visits = [['BB', 13, 'Green'], ['BB', 14, 'Blue']]

    stores_df = pd.DataFrame(data=stores, columns=['retailer', 'store', 'color'])
    stores_df.set_index(['retailer', 'store'], inplace=True)

    visits_df = pd.DataFrame(data=visits, columns=['retailer', 'store', 'color'])
    visits_df.set_index(['retailer', 'store'], inplace=True)

                color
retailer store       
BB       13     Green
         14      Blue

               color
retailer store      
AA       12      Red
BB       13      Red
         14      Red
         15      Red

我如何合并它们以获得以下结果:

               color
retailer store      
AA       12      Red
BB       13      Green
         14      Blue
         15      Red

最佳答案

您可以使用更新:

In [41]: stores_df.update(visits_df)

In [42]: stores_df
Out[42]:
                color
retailer store
AA       12       Red
BB       13     Green
         14      Blue
         15       Red

关于python - 合并具有重叠列的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38369638/

相关文章:

python - 你能从 boto 得到 AWS 账户名吗?

python - 如何使 numba @jit 使用所有 cpu 内核(并行化 numba @jit)

python - 无法将 RGBA 模式写为 BMP pytesser

python pandas 如果 A 列中有 1,则使用同一行中 B 列的值

python - Pandas DataFrame 到 Django API

python - 创建新文件的函数

python - 将数据框与字典值列表进行比较

python - 将行条目与列名称连接起来

python - 清理 1677 年之前日期的不同日期格式时的 Pandas OutOfBoundsDatetime

python - Pandas:如何合并不同的数据框?