Access index in pandas.Series.apply

前端 未结 6 1021
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:50

    Make it a frame, return scalars if you want (so the result is a series)

    Setup

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

    Printing function

    In [13]: def f(x):
        print type(x), x
        return x
       ....: 
    
    In [14]: pd.DataFrame(s).apply(f)
     a    1
    b    2
    c    3
    Name: 0, dtype: float64
     a    1
    b    2
    c    3
    Name: 0, dtype: float64
    Out[14]: 
       0
    a  1
    b  2
    c  3
    

    Since you can return anything here, just return the scalars (access the index via the name attribute)

    In [15]: pd.DataFrame(s).apply(lambda x: 5 if x.name == 'a' else x[0] ,1)
    Out[15]: 
    a    5
    b    2
    c    3
    dtype: float64
    

提交回复
热议问题