Python pandas apply function if a column value is not NULL

后端 未结 4 693
面向向阳花
面向向阳花 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

    Also another way is to just use row.notnull().all() (without numpy), here is an example:

    df.apply(lambda row: func1(row) if row.notnull().all() else func2(row), axis=1)
    

    Here is a complete example on your df:

    >>> d = {'A': [None, 2, 3, 4], 'B': [11, None, 33, 4], 'C': [None, ['a','b'], None, 4]}
    >>> df = pd.DataFrame(d)
    >>> df
         A     B       C
    0  NaN  11.0    None
    1  2.0   NaN  [a, b]
    2  3.0  33.0    None
    3  4.0   4.0       4
    >>> def func1(r):
    ...     return 'No'
    ...
    >>> def func2(r):
    ...     return 'Yes'
    ...
    >>> df.apply(lambda row: func1(row) if row.notnull().all() else func2(row), axis=1)
    0    Yes
    1    Yes
    2    Yes
    3     No
    

    And a friendlier screenshot :-)

提交回复
热议问题