如何通过使用字典替换值来设置系列的级别值,或者只使用值列表来设置系列的级别值?
以下是DataFrame示例:
sector from_country to_country 0
0 Textiles FRA AUS 47.502096
1 Textiles FRA USA 431.890710
2 Textiles GBR AUS 83.500590
3 Textiles GBR USA 324.836158
4 Wood FRA AUS 27.515607
5 Wood FRA USA 276.501148
6 Wood GBR AUS 1.406096
7 Wood GBR USA 8.996177
现在设置索引:
df = df.set_index(['sector', 'from_country', 'to_country']).squeeze()
例如,如果我想根据以下键/值对进行更改:
In [69]: replace_dict = {'FRA':'France', 'GBR':'UK'}
In [70]: new_vals = [replace_dict[x] for x in df.index.get_level_values('from_country')]
我希望输出看起来像:
In [68]: df.index.set_level_values(new_vals, level='from_country')
Out[68]:
sector from_country to_country
Textiles France AUS 47.502096
USA 431.890710
UK AUS 83.500590
USA 324.836158
Wood France AUS 27.515607
USA 276.501148
UK AUS 1.406096
USA 8.996177
我目前这样做,但对我来说似乎很蠢:
def set_index_values(df_or_series, new_values, level):
"""
Replace the MultiIndex level `level` with `new_values`
`new_values` must be the same length as `df_or_series`
"""
levels = df_or_series.index.names
retval = df_or_series.reset_index(level)
retval[level] = new_values
retval = retval.set_index(level, append=True).reorder_levels(levels).sortlevel().squeeze()
return retval
答案 0 :(得分:5)
稍微hacky,但你可以用.index.set_levels
:
In [11]: df1.index.levels[1]
Out[11]: Index(['FRA', 'GBR'], dtype='object', name='from_country')
In [12]: df1.index.levels[1].map(replace_dict.get)
Out[12]: array(['France', 'UK'], dtype=object)
In [13]: df1.index = df1.index.set_levels(df1.index.levels[1].map(replace_dict.get), "from_country")
In [14]: df1
Out[14]:
sector from_country to_country
Textiles France AUS 47.502096
USA 431.890710
UK AUS 83.500590
USA 324.836158
Wood France AUS 27.515607
USA 276.501148
UK AUS 1.406096
USA 8.996177
Name: 0, dtype: float64
注意:是从名称中获取级别编号的方法,但我不记得了。