How to update a subset of a MultiIndexed pandas DataFrame

前端 未结 2 1847
情歌与酒
情歌与酒 2020-12-05 20:54

I\'m using a MultiIndexed pandas DataFrame and would like to multiply a subset of the DataFrame by a certain number.

It\'s the same as this but with a MultiIndex.

2条回答
  •  萌比男神i
    2020-12-05 21:25

    Note: In soon to be released 0.13 a drop_level argument has been added to xs (thanks to this question!):

    In [42]: df.xs('sat', level='day', drop_level=False)
    Out[42]:
                         sales
    year flavour    day
    2008 strawberry sat     10
    

    Another option is to use select (which extracts a sub-DataFrame (copy) of the same data, i.e. it has the same index and so can be updated correctly):

    In [11]: d.select(lambda x: x[2] == 'sat') * 2
    Out[11]:
                         sales
    year flavour    day
    2008 strawberry sat     20
         banana     sat     44
    2009 strawberry sat     22
         banana     sat     46
    
    In [12]: d.update(d.select(lambda x: x[2] == 'sat') * 2)
    

    Another option is to use an apply:

    In [21]: d.apply(lambda x: x*2 if x.name[2] == 'sat' else x, axis=1)
    

    Another option is to use get_level_values (this is probably the most efficient way of these):

    In [22]: d[d.index.get_level_values('day') == 'sat'] *= 2
    

    Another option is promote the 'day' level to a column and then use an apply.

提交回复
热议问题