Maxim
Maxim

Reputation: 756

List comprehension that ignores NaN

I'm trying to build a list comprehension that has a conditional to not import nan values, but not having luck. Below is the current code along with the resulting output. What conditional will remove the nans from the list?

def generate_labels(filtered_df, columnName):
    return[
        {'label': i, 'value': i} for i in 
        filtered_df[columnName].unique() 
    ]

generate_labels(df, 'Region')


#Output  


[{'label': 'Americas', 'value': 'Americas'},
     {'label': 'EMEA', 'value': 'EMEA'},
     {'label': nan, 'value': nan},
     {'label': 'APAC ', 'value': 'APAC '}]

Upvotes: 4

Views: 4317

Answers (2)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210882

def generate_labels(filtered_df, columnName):
    return[
        {'label': i, 'value': i} for i in filtered_df[columnName].dropna().unique() 
    ]

Upvotes: 5

Yilun Zhang
Yilun Zhang

Reputation: 9018

You can add a condition in your list comprehension expression. Something like:

import math

def generate_labels(filtered_df, columnName):
    return[
        {'label': i, 'value': i} for i in 
        filtered_df[columnName].unique() 
        if not math.isnan(i)
    ]

There are a number of ways where you can check if a value is nan or not. You can also use the numpy version if that's what you prefer.

Upvotes: 3

Related Questions