Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension that ignores NaN

Tags:

python

pandas

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 '}]
like image 804
Maksim Avatar asked Oct 28 '25 01:10

Maksim


1 Answers

def generate_labels(filtered_df, columnName):
    return[
        {'label': i, 'value': i} for i in filtered_df[columnName].dropna().unique() 
    ]
like image 184
MaxU - stop WAR against UA Avatar answered Oct 30 '25 16:10

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!