合并具有重叠列的数据帧

2024-03-28 21:53:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

    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

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

^{pr2}$

Tags: columnsstoredataframedfdatagreenbluered
2条回答

您可以使用update

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

您想使用combine_first

visits_df.combine_first(stores_df)

enter image description here

相关问题 更多 >