【问题标题】:Create Multi-Index from Index and Column从索引和列创建多索引
【发布时间】:2016-01-10 08:06:48
【问题描述】:

我有一个 multiIndex 数据帧,我正在与另一个 multiIndex 数据帧合并,它合并成功,但现在它只有一个索引?

climate_df2.index.names
Out[79]: FrozenList(['key', 'Y'])

fileformat_df.index.names
Out[80]: FrozenList(['key', 'Y'])

climate_df3 = pd.merge(climate_df2.reset_index(), fileformat_df.reset_index(),
                   on = ["key","Y"], how = "inner").set_index("key","Y")

climate_df3.index.names
Out[81]: FrozenList(['key'])

climate_df3.columns
Out[82]: Index(['Y', 'DatasetName', 'Organization', 'URL', 'FileFormat'], dtype='object')

但现在以前的索引“Y”是合并数据框中的一列。所以我要么想让合并的 DF 首先返回两个索引,要么只是将“Y”列添加到合并的数据框中。

【问题讨论】:

    标签: python pandas indexing merge multi-index


    【解决方案1】:

    刚刚想出了如何“修复”它:

    climate_df3.set_index(["Y"], append = True)
    

    我仍然不确定为什么“Y”最终会出现在列中,但这会将其放回 MultiIndex。

    【讨论】:

      猜你喜欢
      • 2018-12-14
      • 2023-03-23
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      相关资源
      最近更新 更多