pandas - 如何使用多索引合并表

pandas - how to merge tables with multiindexes

我有两个具有相似多索引结构的 table:datecountry__name。索引不相同:某些国家/地区可能会从一个或另一个国家/地区中消失 table.

table 有不同的列。为了说明,这里是:

我想将它们合并到一个 table 中,它保留了多索引,但具有来自两个 table 的所有列。

但是当我这样做的时候

pandas.concat([grouped_channel_df, grouped_tds_df], axis=1)

我得到一个 table 满 NaN:

我错过了什么?

如果您想合并 table,您需要使用 .merge 而不是 .concat。检查两个概念之间的区别here

对于您的用例,尝试这样的事情:

merged = pandas.merge(grouped_channel_df, grouped_tds_df, how='outer', on=('date','country_name'), suffixes=('_channel','_tds'))

阅读上面的文档以阅读其他选项