输入类型不支持ufunc“isnan”

2024-10-03 17:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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''

我还可以尝试提取第一个非空值吗


Tags: thetodfnpnotnanarraylist
1条回答
网友
1楼 · 发布于 2024-10-03 17:19:05

最简单的方法是使用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)

相关问题 更多 >