Access index in pandas.Series.apply

前端 未结 6 1020
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:41

    You can access the whole row as argument inside the fucntion if you use DataFrame.apply() instead of Series.apply().

    def f1(row):
        if row['I'] < 0.5:
            return 0
        else:
            return 1
    
    def f2(row):
        if row['N1']==1:
            return 0
        else:
            return 1
    
    import pandas as pd
    import numpy as np
    df4 = pd.DataFrame(np.random.rand(6,1), columns=list('I'))
    df4['N1']=df4.apply(f1, axis=1)
    df4['N2']=df4.apply(f2, axis=1)
    

提交回复
热议问题