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

标签 python list pandas null apply

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

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

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

def my_func(row):
    print row

我的申请代码如下:

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

完美运行。如果我想检查 'B' 列的 NULL 值,那么 pd.notnull() 也可以正常工作。但是,如果我选择包含列表对象的列“C”:

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

然后我收到以下错误消息:ValueError: ('具有多个元素的数组的真值是不明确的。使用 a.any() 或 a.all()', u'发生在索引 1')

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

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

df[['A','C']].apply(lambda x: my_func(x) if(str(x[1]) != 'nan') else x, axis = 1)

谢谢!

最佳答案

问题是 pd.notnull(['foo', 'bar']) 按元素操作并返回 array([ True, True], dtype=bool)。您的 if 条件尝试将其转换为 bool 值,这就是您遇到异常的时候。

要修复它,您可以简单地用 np.all 包装 isnull 语句:

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

现在你会看到 np.all(pd.notnull(['foo', 'bar'])) 确实是 True

关于如果列值不为 NULL,则 Python pandas 应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26614465/

相关文章:

python - 拟合模型时出错

javascript - channel Google App Engine Channel.open() 不起作用

c++ - 从 int[] 转换为 list<int> : Any better way

python,读取带有太多分隔符的CSV

python - 如何在 for 循环中识别多个列表项

Python 检测损坏的编码

python - pandas.concat 和 numpy.append 的大数据集内存错误

string - 列表[字符串] -> 矢量[矢量[字符]]

python - 根据子列表的长度删除列表的子列表

python - 有没有一种方法可以将函数应用于具有相同外部索引的多索引数据帧切片,而无需迭代每个切片?