【问题标题】:isnull(df.any) is returning False despite NaN in the DataFrame尽管 DataFrame 中有 NaN,isnull(df.any) 仍返回 False
【发布时间】:2018-12-28 10:59:20
【问题描述】:

我正在尝试通过以下方式获取 Dataframe 是否包含 Null 或 NaN 值:

import numpy as np
import pandas as pd

# load the time series of known points
y = [np.array([])]

y = [np.array([10, 11, 11, 11, 2, 4, 3, 7, 8, 9]),  
     np.array([1, 1, 1, 2, 2, 2, 2, 3, 2, 1]), 
     np.array([1, 1, 2, 2, 2, 2, 3, 2, 1])]
y = pd.DataFrame(y)



for i in range(len(y)):
    if (pd.isnull(y.any) == True):
        print ("Error: t2 array index " + str(i) + " ahave NaN or null!")
print("All good bro")
print (pd.isnull(y)
print (pd.isnull(y.any))

当我打印 y 时,您可以清楚地看到最后一个元素是 NaN。这是因为第三个 numpy 数组比其他数组短。 Pandas 会自动用 NaN 填充缺失值以保持数据框形状。

但是,如果我尝试打印 pd.isnull(y.any) 我会得到 False。 我尝试了y.all,但也得到了错误。 我也尝试了y[1].any,结果相同。

我在这里错过了什么?

【问题讨论】:

  • y.any 是一个函数,你必须调用它,即使那样也不能满足你的要求。

标签: python pandas


【解决方案1】:

你可以使用:

y.isnull().values.any()

代码:

import numpy as np
import pandas as pd

# load the time series of known points
y = [np.array([])]

y = [np.array([10, 11, 11, 11, 2, 4, 3, 7, 8, 9]),  
     np.array([1, 1, 1, 2, 2, 2, 2, 3, 2, 1]), 
     np.array([1, 1, 2, 2, 2, 2, 3, 2, 1])]
y = pd.DataFrame(y)

print(y.isnull().values.any())

输出:

True

【讨论】:

  • 是的,抱歉必须等待 10 分钟才能接受。
猜你喜欢
  • 1970-01-01
  • 2023-01-21
  • 1970-01-01
  • 2017-07-29
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2019-10-03
相关资源
最近更新 更多