如何在一个pandas MultiIndex切片中操作字符串

时间:2016-10-19 21:31:52

标签: python pandas

我有MultiIndex这样:

                                 metric
sensor  variable   side  
foo        Speed   Left      Left speed
                  Right     Right speed
bar        Speed   Left      Left_Speed
                  Right     Right_Speed
baz        Speed   Left           speed
foo      Support   Left    Left support
                  Right   Right support
bar      Support   Left    Left_support
                  Right   Right_support
baz      Support   Left         support

我正在尝试将字符串映射应用于此数据帧的切片:

df.loc['baz',:,'Left'].metric.map(lambda s: "Left_" + s)

如何将此地图仅应用于baz-Left行,并返回结果DataFrame

                                 metric
sensor  variable   side  
foo        Speed   Left      Left speed
                  Right     Right speed
bar        Speed   Left      Left_Speed
                  Right     Right_Speed
baz        Speed   Left      Left_speed
foo      Support   Left    Left support
                  Right   Right support
bar      Support   Left    Left_support
                  Right   Right_support
baz      Support   Left    Left_support

1 个答案:

答案 0 :(得分:1)

我找到了以下方法,但我认为/希望必须有更优雅的方法来实现这一目标:

In [101]: index_saved = df.index

让我们排序索引以摆脱KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (3), lexsort depth (0)'错误:

In [102]: df = df.sort_index()

In [103]: df
Out[103]:
                              metric
sensor variable side
bar    Speed    Left      Left_Speed
                Right    Right_Speed
       Support  Left    Left_support
                Right  Right_support
baz    Speed    Left           speed
       Support  Left         support
foo    Speed    Left      Left speed
                Right    Right speed
       Support  Left    Left support
                Right  Right support

In [119]: df.loc[pd.IndexSlice['baz', :, 'Left'], 'metric'] = \
     ...:     'AAA__' + df.loc[pd.IndexSlice['baz', :, 'Left'], 'metric']

In [120]: df
Out[120]:
                              metric
sensor variable side
bar    Speed    Left      Left_Speed
                Right    Right_Speed
       Support  Left    Left_support
                Right  Right_support
baz    Speed    Left      AAA__speed
       Support  Left    AAA__support
foo    Speed    Left      Left speed
                Right    Right speed
       Support  Left    Left support
                Right  Right support

设置旧(已保存)索引:

In [121]: df = df.reindex(index_saved)

In [122]: df
Out[122]:
                              metric
sensor variable side
foo    Speed    Left      Left speed
                Right    Right speed
bar    Speed    Left      Left_Speed
                Right    Right_Speed
baz    Speed    Left      AAA__speed
foo    Support  Left    Left support
                Right  Right support
bar    Support  Left    Left_support
                Right  Right_support
baz    Support  Left    AAA__support