Python Pandas:获取列不为null的DataFrame的行 [英] Python Pandas: get rows of a DataFrame where a column is not null

查看:2187
本文介绍了Python Pandas:获取列不为null的DataFrame的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在过滤我的DataFrame,删除其中特定列的单元格值为无"的那些行.

I'm filtering my DataFrame dropping those rows in which the cell value of a specific column is None.

df = df[df['my_col'].isnull() == False]

工作正常,但是PyCharm告诉我:

Works fine, but PyCharm tells me:

PEP8:与False的比较应为如果cond为False:"或如果非cond:"

PEP8: comparison to False should be 'if cond is False:' or 'if not cond:'

但是我不知道如何将其应用于我的用例?使用"not ..."或"is False"无效.我当前的解决方案是:

But I wonder how I should apply this to my use-case? Using 'not ...' or ' is False' did not work. My current solution is:

df = df[df['my_col'].notnull()]

推荐答案

因此python具有短路逻辑运算符notandor.这些在python中具有非常特定的含义,不能被覆盖(not必须返回bool,而a and/or b始终返回ab或抛出错误.

So python has the short-circuiting logic operators not, and, or. These have a very specific meaning in python and cannot be overridden (not must return a bool and a and/or b always returns either a or b or throws an error.

但是,python还具有可重载的布尔运算符~(不是),&(和),|(或)和^(xor).

However, python also has over-loadable boolean operators ~ (not), & (and), | (or) and ^ (xor).

您可能会认识到它们是int逐位运算符,但是Numpy(因此是熊猫)使用它们来执行数组/系列布尔运算.

You may recognise these as the int bitwise operators, but Numpy (and therefore pandas) use these to do array / series boolean operations.

例如

b = np.array([True, False, True]) & np.array([True, False, False])
# b --> [True False False]
b = ~b 
# b --> [False True True]

因此,您想要的是

df = df[~df['my_col'].isnull()]

我同意PEP8,不同意== False.

I agree with PEP8, don't do == False.

这篇关于Python Pandas:获取列不为null的DataFrame的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆