Pandas 使用多索引的一列进行连接

Pandas concat using one column of a multindex

我正在尝试加入新数据,该数据在多索引的一列的每个值中都有一个值。一个基本的例子是:

data = io.StringIO('''Fruit,Color,Count,Price
Apple,Red,3,.29
Apple,Green,9,[=11=].99
Pear,Red,25,.59
Pear,Green,26,.79
Lime,Green,99,[=11=].39
''')
df_unindexed = pandas.read_csv(data)
df = df_unindexed.set_index(['Fruit', 'Color'])
df

join = io.StringIO('''Fruit,Count2
Apple,3
Pear,25
Lime,99
''')
join = pandas.read_csv(join)
join = join.set_index(['Fruit'])
join

我想仅使用索引的水果列来连接新数据,给出:

             Count  Price  Count2
Fruit Color                      
Apple Red        3  .29       3
      Green      9  [=12=].99       3
Pear  Red       25  .59      25
      Green     26  .79      25
Lime  Green     99  [=12=].39      99

使用get_level_values with map,上一版.get应该省略:

df['count2'] = df.index.get_level_values('Fruit').map(join['Count2'].get)
print (df)
             Count  Price  count2
Fruit Color                      
Apple Red        3  .29       3
      Green      9  [=10=].99       3
Pear  Red       25  .59      25
      Green     26  .79      25
Lime  Green     99  [=10=].39      99

如果 join 中的多个列可能,请使用 reset_index, join and set_index:

df = df.reset_index(level=1).join(join).set_index('Color', append=True)

on='Fruit'

您可以使用 on 参数指定要用作 join 条件的索引级别或列。

df.join(join, on='Fruit')

             Count  Price  Count2
Fruit Color                      
Apple Red        3  .29       3
      Green      9  [=10=].99       3
Pear  Red       25  .59      25
      Green     26  .79      25
Lime  Green     99  [=10=].39      99

使用reset_index+set_index+assign

df.reset_index(level=1).assign(count2=join.Count2).set_index('Color',append=True)
Out[1068]: 
             Count  Price  count2
Fruit Color                      
Apple Red        3  .29       3
      Green      9  [=10=].99       3
Pear  Red       25  .59      25
      Green     26  .79      25
Lime  Green     99  [=10=].39      99