【发布时间】:2018-07-24 05:58:40
【问题描述】:
我有两个多索引,我想在索引上合并在一起。
下面我想在Cif 和ye 上合并,并在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 的数据框的组合,但它们具有相同的索引,Cif 和 ye,如下所示:
new=pd.concat([staff_cost_sum, sub_cost_sum, consum_cost_sum, soft_cost_sum]).sum(level=['Cif','ye'])
new.reset_index(inplace=True)
在这个过程中数据类型似乎正在改变,因为新的数据帧将Cif和ye设置为对象类型,而staff_cost_sum仍然是int64数据类型。
如何在“新”数据框中保留 Cif 和 ye 列的相同数据类型?它们是什么数据类型对我来说并不重要,因为这就是我需要做的所有事情(所以没有未来的后果),但我宁愿知道如何编辑下面的代码示例来做到这一点而不是做解决方法。不过,任何想法都会很感激。
两个多索引数据集如下。
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
【问题讨论】:
-
你的预期输出是什么?
-
两个 0 列,在不同的列中,所以它会创建列 0_x 和 0_y 编辑:并且索引是 'Cif' 和 'ye'