【问题标题】:ufunc 'isnan' not supported for the input types输入类型不支持 ufunc 'isnan'
【发布时间】:2021-12-01 03:33:27
【问题描述】:

我有一个df,其中一个特定的列有几个空值。我想提取第一个非空值。

print(df.kst_erloes_stpfl.to_list())
[nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 'WH042700', 90510000, 90510000]
import numpy as np

def not_na(array):
    return ~np.isnan(array)

def first_not_na_value(array):
    return list(filter(not_na, array))[0]

first = first_not_na_value(df.kst_erloes_stpfl)
print(first)

但是,我收到此错误:

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

我还能尝试提取第一个非空值吗?

【问题讨论】:

  • 使用df.kst_erloes_stpfl.notnull()
  • 我将如何从中提取第一个值?如果我打印这个结果,我只会得到真或假@QuangHoang
  • this 回答你的问题了吗?

标签: python pandas dataframe numpy typeerror


【解决方案1】:

最简单的方法是使用pandas内置函数dropna:

import numpy as np
import pandas as pd

values = [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
          np.nan, np.nan, np.nan, np.nan, np.nan, 'WH042700', 90510000, 90510000]

df = pd.DataFrame(values)

first_non_na = df.dropna().iloc[0,0]

print(first_non_na)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2020-02-18
    • 2019-03-10
    • 1970-01-01
    • 2020-07-21
    • 2020-09-29
    • 2023-03-30
    相关资源
    最近更新 更多