【问题标题】:Potential bug in np.isnan() for mixed types on pandas Dataframepandas Dataframe 上混合类型的 np.isnan() 中的潜在错误
【发布时间】:2020-04-25 12:34:45
【问题描述】:

我遇到了 np.isnan() 的错误。可能是它打算以这种方式工作,问题是熊猫如何处理它。如果我制作一个混合类型的数据框,例如

raw_data = {'Binary 1': [True, True, False, False, True], 
    'Binary 2': [False, False, True, True, False], 
    'age': [42, 52, 36, 24, 73], 
    'preTestScore': [4, 24, 31, 2, 3],
    'postTestScore': [25, 94, 57, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['Binary 1', 'Binary 2', 'age', 'preTestScore', 'postTestScore'])

df.dtypes


Binary 1          bool
Binary 2          bool
age              int64
preTestScore     int64
postTestScore    int64

我不能打电话

np.isnan(df)

TypeError: 输入类型不支持 ufunc 'isnan',并且根据强制转换规则 ''safe'' 无法安全地将输入强制转换为任何支持的类型

这两个

np.isnan(df[['Binary 1', 'Binary 2']])

还有这个

np.isnan(df[['age', 'preTestScore', 'postTestScore']])

工作。我认为这是因为它们属于同一类型,因为这不是

np.isnan(df[['Binary 1', 'age']])

【问题讨论】:

  • 我不认为这是一个错误,而是 numpy 不想将多种类型的数据强制转换为同一个数据类型,就像你说的那样。
  • 轻松解决 --> 使用 print(pd.isnull(df[['Binary 1', 'age']])) 而不是 numpy

标签: python pandas numpy


【解决方案1】:

np.isnan 是一个 numpy 函数,因此它适用于 numpy 数组以及从输入派生的值:

In [418]: df[['Binary 1', 'Binary 2']].values                                   
Out[418]: 
array([[ True, False],
       [ True, False],
       [False,  True],
       [False,  True],
       [ True, False]])

这是一个二维布尔 dtype 数组。但是整个数据框有混合数据类型,所以它产生一个对象数据类型:

In [419]: df.values                                                             
Out[419]: 
array([[True, False, 42, 4, 25],
       [True, False, 52, 24, 94],
       [False, True, 36, 31, 57],
       [False, True, 24, 2, 62],
       [True, False, 73, 3, 70]], dtype=object)

将该数组转换为int(或浮点数),运行正常:np.isnan(df.values.astype(int))

但正如 cmets 中所指出的,pandas 有自己的 nan 测试器,我相信它更强大(并且宽容)。 np.isnan 真正用于浮点数组,因为np.nan 是浮点数。

【讨论】:

    猜你喜欢
    • 2013-01-23
    • 2020-08-06
    • 2021-01-07
    • 1970-01-01
    • 2015-02-06
    • 2020-08-11
    • 2018-10-06
    • 2018-05-12
    • 2021-07-28
    相关资源
    最近更新 更多