Python pandas apply function if a column value is not NULL

后端 未结 4 806
面向向阳花
面向向阳花 2021-02-01 03:00

I have a dataframe (in Python 2.7, pandas 0.15.0):

df=
       A    B               C
0    NaN   11             NaN
1    two  NaN  [\'foo\', \'bar\']
2  three   3         


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 03:37

    The problem is that pd.notnull(['foo', 'bar']) operates elementwise and returns array([ True, True], dtype=bool). Your if condition trys to convert that to a boolean, and that's when you get the exception.

    To fix it, you could simply wrap the isnull statement with np.all:

    df[['A','C']].apply(lambda x: my_func(x) if(np.all(pd.notnull(x[1]))) else x, axis = 1)
    

    Now you'll see that np.all(pd.notnull(['foo', 'bar'])) is indeed True.

提交回复
热议问题