bfmcneill
bfmcneill

Reputation: 127

how to assert a dataframe value is NaN

How can I assert a specific Pandas row/column value is nan ? I tried to assert a value from the iloc DataFrame value and from converting the Pandas DataFrame to Numpy array. It seems as if I can feed values in as np.nan but I can't test individual values.

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 

Upvotes: 1

Views: 1686

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

Here is a trick:

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

Let's use pd.Series method isna. We can bracket the column to force a return of a signle element pandas series.

another way is to use either math.isnan or np.isnan.

import math

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

Upvotes: 2

ccluff
ccluff

Reputation: 163

you want

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

Upvotes: 3

Related Questions