【问题标题】:how to assert a dataframe value is NaN如何断言数据帧值为 NaN
【发布时间】:2020-09-08 20:01:24
【问题描述】:

如何断言特定的 Pandas 行/列值为 nan ?我试图从 iloc DataFrame 值中断言一个值,并将 Pandas DataFrame 转换为 Numpy 数组。似乎我可以将值作为 np.nan 输入,但我无法测试单个值。

import pandas as pd
import numpy as np

df= pd.DataFrame([
    dict(id=1, color='red'),
    dict(id=2, color='blue'),
    dict(id=3, color=np.nan),
])

assert df.iloc[0, 1] == 'red'  # True
assert df.iloc[1, 1] == 'blue' # True

# Assertion fails
assert df.iloc[2, 1] == np.nan 

# Assertion fails
assert df.to_numpy()[2][1] == np.nan 

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    你想要的

    assert np.isnan(df.iloc[2, 1])
    

    【讨论】:

      【解决方案2】:

      这里有一个技巧:

      assert df.iloc[2, [1]].isna().any()
      

      让我们使用 pd.Series 方法 isna。我们可以将列括起来以强制返回一个单一的元素熊猫系列。

      另一种方法是使用 math.isnan 或 np.isnan。

      import math
      
      assert math.isnan(df.iloc[2, 1])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-26
        • 2015-09-08
        • 1970-01-01
        • 2022-01-12
        • 2017-12-24
        • 1970-01-01
        • 1970-01-01
        • 2018-04-06
        相关资源
        最近更新 更多