Access index in pandas.Series.apply

前端 未结 6 1026
Happy的楠姐
Happy的楠姐 2020-11-30 02:21

Lets say I have a MultiIndex Series s:

>>> s
     values
a b
1 2  0.1 
3 6  0.3
4 4  0.7

and I want to apply a functi

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 02:55

    You may find it faster to use where rather than apply here:

    In [11]: s = pd.Series([1., 2., 3.], index=['a' ,'b', 'c'])
    
    In [12]: s.where(s.index != 'a', 5)
    Out[12]: 
    a    5
    b    2
    c    3
    dtype: float64
    

    Also you can use numpy-style logic/functions to any of the parts:

    In [13]: (2 * s + 1).where((s.index == 'b') | (s.index == 'c'), -s)
    Out[13]: 
    a   -1
    b    5
    c    7
    dtype: float64
    
    In [14]: (2 * s + 1).where(s.index != 'a', -s)
    Out[14]: 
    a   -1
    b    5
    c    7
    dtype: float64
    

    I recommend testing for speed (as efficiency against apply will depend on the function). Although, I find that applys are more readable...

提交回复
热议问题