aAnnAa
aAnnAa

Reputation: 145

How can I check if a value is nan or a list?

I'm currently working with pandas DataFrames. While iterating over it I want to check if a value is numpy.nan or a list.

for i, row in df.iterrows():
value = row["Name"]
if pd.isnull(value):
    dosomething()

This works just fine, except if

type(value) == list

Then I thought of maybe putting any() around:

for i, row in df.iterrows():
value = row["Name"]
if any(pd.isnull(value)):
    dosomething()

But now I get a exception everytime a NaN is in value because it's obviously not iterable.

Is there a better solution then checking the type of value?

Upvotes: 1

Views: 6196

Answers (1)

jezrael
jezrael

Reputation: 862396

Use or:

for i, row in df.iterrows():
    value = row["Name"]
    if pd.isnull(value) or (type(value) == list):
        dosomething()

Another way for check is isinstance:

for i, row in df.iterrows():
    value = row["Name"]
    if pd.isnull(value) or isinstance(value, list):
        dosomething()

Upvotes: 4

Related Questions