如何检查数据帧列中的所有非 nan 值是否 > 0?

问题描述 投票:0回答:1

我有一个数据框列可能有 NaN,这是可以接受的,但非正值是不可接受的。

我尝试过做

assert (df[col] > 0).all()

但这断言是否存在 nan 列。

我也尝试过

assert (df[col] > 0 | df[col] == np.nan).all()

但这给出了错误

E                   TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

检查此内容的适当方法是什么?

python pandas dataframe nan
1个回答
0
投票

确实需要检查 NaN 性。 但

==
平等行不通; 你需要一个像 np.isnan(x) 这样的函数。

这就是您想要的:

assert (df[col].dropna() > 0).all()

我们过滤掉 首先是 NaN,然后验证剩余的数字都是正数。

© www.soinside.com 2019 - 2024. All rights reserved.