python - 在 Pandas 中加入具有不同级别数的 MultiIndex

标签 python pandas dataframe join multi-index

如何在具有不同级别的 MultiIndex 上加入 2 个 Pandas DataFrames?

import pandas as pd
t1 = pd.DataFrame(data={'a1':[0,0,1,1,2,2],
                        'a2':[0,1,0,1,0,1],
                        'x':[1.,2.,3.,4.,5.,6.]})
t1.set_index(['a1','a2'], inplace=True)
t1.sort_index(inplace=True)
t2 = pd.DataFrame(data={'b1':[0,1,2],
                        'y':[20.,40.,60.]})
t2.set_index(['b1'], inplace=True)
t2.sort_index(inplace=True)

>>> t1
         x
a1 a2     
0  0   1.0
   1   2.0
1  0   3.0
   1   4.0
2  0   5.0
   1   6.0
>>> t2
       y
b1      
0   20.0
1   40.0
2   60.0

加入 'a1' => 'b1' 的预期结果:

         x    y
a1 a2
0  0   1.0 20.0
   1   2.0 20.0
1  0   3.0 40.0
   1   4.0 40.0
2  0   5.0 60.0
   1   6.0 60.0

另一个例子:加入 ['a1','a2'] => ['b1','b2']:

import pandas as pd, numpy as np
t1 = pd.DataFrame(data={'a1':[0,0,0,0,1,1,1,1,2,2,2,2],
                        'a2':[3,3,4,4,3,3,4,4,3,3,4,4],
                        'a3':[7,8,7,8,7,8,7,8,7,8,7,8],
                        'x':[1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12.]})
t1.set_index(['a1','a2','a3'], inplace=True)
t1.sort_index(inplace=True)
t2 = pd.DataFrame(data={'b1':[0,0,1,1,2,2],
                        'b2':[3,4,3,4,3,4],
                        'y':[10.,20.,30.,40.,50.,60.]})
t2.set_index(['b1','b2'], inplace=True)
t2.sort_index(inplace=True)

>>> t1
             x
a1 a2 a3   
0  3  7    1.0
      8    2.0
   4  7    3.0
      8    4.0
1  3  7    5.0
      8    6.0
   4  7    7.0
      8    8.0
2  3  7    9.0
      8   10.0
   4  7   11.0
      8   12.0
>>> t2
          y
b1 b2
0  3   10.0
   4   20.0
1  3   30.0
   4   40.0
2  3   50.0
   4   60.0

加入 ['a1','a2'] => ['b1','b2'] 的预期结果:

             x     y
a1 a2 a3         
0  3  7    1.0  10.0
      8    2.0  10.0
   4  7    3.0  20.0
      8    4.0  20.0
1  3  7    5.0  30.0
      8    6.0  30.0
   4  7    7.0  40.0
      8    8.0  40.0
2  3  7    9.0  50.0
      8   10.0  50.0
   4  7   11.0  60.0
      8   12.0  60.0

该解决方案应该在多个索引级别上工作。

感谢您的帮助!

最佳答案

您可以使用 pd.Index.get_level_values 并映射来自 t2 的系列:

t1['y'] = t1.index.get_level_values(0).map(t2['y'].get)

print(t1)

         x     y
a1 a2           
0  0   1.0  20.0
   1   2.0  20.0
1  0   3.0  40.0
   1   4.0  40.0
2  0   5.0  60.0
   1   6.0  60.0

关于python - 在 Pandas 中加入具有不同级别数的 MultiIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50477220/

相关文章:

python - 从带时间戳的流量计数器创建摘要统计信息

python - 在新数据框列的行之间填充

python - 循环遍历具有多个条件的分组数据框

python - 将标识符行添加到数据框,然后写入 excel 文件

python - 具有动态添加属性的 Django 模型对象

python - 在后台运行计时器 x 秒 [Alexa 技能]

python - 如何使用 Pandas 将不一致的时间戳舍入到五分钟间隔并填补空白?

python - 如何计算 Pandas 一行中所有元素的加权和?

python - python中子命名空间的节俭使用

python - 获取索引值的有效方法