在Pandas中合并两个多索引

时间:2018-02-13 19:14:16

标签: python pandas merge

我有两个多索引,我想在索引上合并在一起。 下面我要在Cifye上合并,并在al_staff数据框中同时包含0列。

al_staff=pd.merge(new.reset_index(), staff_cost_sum.reset_index(), on=['Cif', 'ye'], how='inner').set_index(['Cif','ye'])

我重置了索引并指定了要合并的列,并定义了新索引中应该包含哪些列。什么都没有归还。

“新”数据框架是与staff_sum类似的多个数据框架的组合,但它们具有相同的索引,Cifye,如下所示:

new=pd.concat([staff_cost_sum, sub_cost_sum, consum_cost_sum, soft_cost_sum]).sum(level=['Cif','ye'])
new.reset_index(inplace=True)

由于新数据框架Cifye设置为对象类型而staff_cost_sum仍为int64数据,因此似乎正在更改数据类型类型。

如何在“新”数据框中保留Cifye列的相同数据类型?对我来说无关紧要的是什么数据类型,因为这是我需要做的所有事情(因此没有未来的后果),但我宁愿知道如何编辑下面的代码示例来做这个而不是做解决方案。但是,任何想法都会欣赏。

下面是两个多索引数据集。

Cif     ye  0
277     13  519297.676200
        14  770372.973000
        15  63046.854000
312     13  21292.546058
322     14  60154.098500
361     13  78735.072000

Cif     ye  0
277     13  444597.411500
        14  484438.682500
312     13  21292.546058
322     14  60154.098500
361     13  78735.072000
        16  35333.400000




new.reset_index().info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2101 entries, 0 to 2100
Data columns (total 3 columns):
Cif    2101 non-null object
ye     2101 non-null object
0      2101 non-null float64
dtypes: float64(1), object(2)
memory usage: 49.3+ KB


staff_cost_sum.reset_index().info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1899 entries, 0 to 1898
Data columns (total 3 columns):
Cif    1899 non-null int64
ye     1899 non-null int64
0      1899 non-null float64
dtypes: float64(1), int64(2)
memory usage: 44.6 KB

预期输出:

                  0_x            0_y
Cif ye                              
277 13  444597.411500  519297.676200
    14  484438.682500  770372.973000
312 13   21292.546058   21292.546058
322 14   60154.098500   60154.098500
361 13   78735.072000   78735.072000

1 个答案:

答案 0 :(得分:0)

IIUC。使用join加入多索引行:

df1.join(df2, rsuffix='_x', lsuffix='_y', how='inner')

输出:

                  0_y            0_x
Cif ye                              
277 13  519297.676200  444597.411500
    14  770372.973000  484438.682500
312 13   21292.546058   21292.546058
322 14   60154.098500   60154.098500
361 13   78735.072000   78735.072000

或者

df2.merge(df1, right_index=True, left_index=True, how='inner')

输出:

                  0_x            0_y
Cif ye                              
277 13  444597.411500  519297.676200
    14  484438.682500  770372.973000
312 13   21292.546058   21292.546058
322 14   60154.098500   60154.098500
361 13   78735.072000   78735.072000