我正在处理一个多索引panda数据帧。我的目标是将两个索引列合并为一个,而不脱离方法链。
示例:
A具有以下熊猫数据帧:
In[1]: df
Out[1]:
value
year type color
2018 A red -0.236022
blue -1.030577
B red 1.197374
blue -0.496247
2019 A red -0.066938
blue 0.087585
B red -1.702598
blue 0.085282
现在,我想在此数据帧上执行一系列方法。在这些方法中间的某个位置,我想将两个索引列合并为一个。例如,我执行一个查询(type==a(,然后组合两个索引列(年份和颜色(,然后乘以(4(。所有这些都没有从链中脱离:
df2 = df
.query('type=="A"')
.reset_index('type', drop=True)
.combine_indexes(["year", "type"]) # <- this is what I'm missing
.multiply(4)
所需输出为:
In[3]: df2
Out[3]:
value
year-color
2018-red -0.944089
2018-blue -4.122310
2019-red -0.267752
2019-blue 0.350339
我在这个例子中构造了"combine_indexes"方法。有人知道是否有类似的东西吗?我知道如何组合两个索引列,但前提是我要从链中分离出来。我需要一些与链接兼容的东西。
感谢
如果不断链,我会把set_index
移到最后:
(df.query('type=="A"')
.reset_index('type',drop=True)
.mul(4)
.assign(year_color=lambda x: [f'{a}-{b}' for a,b in x.index])
.set_index('year_color')
)
输出(原始值为np.arange(8)
(
value
year_color
2018-red 0
2018-blue 4
2019-red 16
2019-blue 20
关于如何加入索引级别的问题,让我们尝试Index.map
:
tmp = df.query('type == "A"').droplevel('type')
# The money line:
tmp.index = tmp.index.map('{0[0]}-{0[1]}'.format)
tmp.index.name = 'year-color'
tmp
value
year-color
2018-red -0.236022
2018-blue -1.030577
2019-red -0.066938
2019-blue 0.087585