检查 Pandas 中的单个单元格值是否为 NaN

Check if single cell value is NaN in Pandas

我只想检查 Pandas 系列中的单个单元格是否为空,即检查值是否为 NaN

所有其他答案都是针对序列和数组的,而不是针对单值的。

我试过pandas.notnullpandas.isnullnumpy.isnan。有单一值的解决方案吗?

试试这个:

import pandas as pd
import numpy as np
from pandas import *

>>> L = [4, nan ,6]
>>> df = Series(L)

>>> df
0     4
1   NaN
2     6

>>> if(pd.isnull(df[1])):
        print "Found"

Found

>>> if(np.isnan(df[1])):
        print "Found"

Found

步骤 1.)

df[df.isnull().any(1)]

----> 如果有 nan 值,将为您提供包含行和列的数据框。

步骤 2.)

这将为您提供数据框中准确值为 nan 的位置。 那么你可以做

if(**df.iloc[loc_row,loc_colum]==np.nan**):
    print"your code here"

您可以使用 "isnull" 和 "at" 来检查数据帧中的特定值。

例如:

import pandas as pd
import numpy as np

df = pd.DataFrame([[np.nan, 2], [1, 3], [4, 6]], columns=['A', 'B'])

产量:

    A   B
0   NaN 2
1   1.0 3
2   4.0 6

检查值:

pd.isnull(df.at[0,'A'])

-> 正确

pd.isnull(df.at[0,'B'])

-> 假

我自己刚遇到这个问题并找到了解决方案,虽然不完美,但有效。如上所述,这 3 个答案中的 none 正在解决 OP 的问题。这是我的问题的一个例子,我觉得是一样的。

# fill null values of one column with that of another
f = lambda row: row['A'] if (row['B'].isnull()) else row['B']
df['B'] = df.apply(f, axis=1)

>>> AttributeError: 'str' object has no attribute 'isnull'

因为值 within 数据框的单元格只是原始数据类型,您不能使用任何 pandas 内置方法。所以这就是我所做的。

f = lambda row: row['A'] if (str(row['B'])=='nan') else row['B']

这实际上是我唯一可以开始工作的东西!