Access index in pandas.Series.apply

前端 未结 6 1027
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:53

    I don't believe apply has access to the index; it treats each row as a numpy object, not a Series, as you can see:

    In [27]: s.apply(lambda x: type(x))
    Out[27]: 
    a  b
    1  2    
    3  6    
    4  4    
    

    To get around this limitation, promote the indexes to columns, apply your function, and recreate a Series with the original index.

    Series(s.reset_index().apply(f, axis=1).values, index=s.index)
    

    Other approaches might use s.get_level_values, which often gets a little ugly in my opinion, or s.iterrows(), which is likely to be slower -- perhaps depending on exactly what f does.

提交回复
热议问题