相关疑难解决方法(0)

如果列值不为NULL,Python pandas将应用函数

我有一个数据帧(在Python 2.7中,pandas 0.15.0):

df=
       A    B               C
0    NaN   11             NaN
1    two  NaN  ['foo', 'bar']
2  three   33             NaN
Run Code Online (Sandbox Code Playgroud)

我想对特定列中不包含NULL值的行应用简单函数.我的功能尽可能简单:

def my_func(row):
    print row
Run Code Online (Sandbox Code Playgroud)

我的申请代码如下:

df[['A','B']].apply(lambda x: my_func(x) if(pd.notnull(x[0])) else x, axis = 1)
Run Code Online (Sandbox Code Playgroud)

它完美地运作.如果我想检查列'B'是否为NULL值,那么它也pd.notnull()可以完美地工作.但是,如果我选择包含列表对象的列'C':

df[['A','C']].apply(lambda x: my_func(x) if(pd.notnull(x[1])) else x, axis = 1)
Run Code Online (Sandbox Code Playgroud)

然后我收到以下错误消息: ValueError: ('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()', u'occurred at index 1')

有人知道为什么pd.notnull()只适用于整数和字符串列而不适用于'列列'?

有没有更好的方法来检查列'C'中的NULL值而不是这个:

df[['A','C']].apply(lambda x: my_func(x) if(str(x[1]) != 'nan') …
Run Code Online (Sandbox Code Playgroud)

python null list apply pandas

22
推荐指数
3
解决办法
5万
查看次数

标签 统计

apply ×1

list ×1

null ×1

pandas ×1

python ×1