Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: 'float' object has no attribute 'isna'"

Tags:

python

pandas

I have the below series:

my_series = pd.Series([np.nan, np.nan, ['A', 'B']])

I have to loop through my_series and evaluate whether the value is NaN or not and then do something (actions defined as 'do A' and 'do B' for the sake of simplicity).

1st try:

for element in my_series:
    if element.isna():
        print('do A')
    else:
        print('do B')

When running it, I've got the error: "'float' object has no attribute 'isna'"

2nd try from the question: Error: float object has no attribute notnull

for element in my_series:
    np.where(element.isnull(), 'do A', 'do B')

When running it, I've got the error: "AttributeError: 'float' object has no attribute 'isnull'"

I haven't found any other similar question here at StackOverflow, I don't know what else to try.

like image 916
asa Avatar asked Nov 30 '19 16:11

asa


Video Answer


2 Answers

Change your code to:

for element in my_series:
    if type(element) == float and pd.isna(element):
        print('do A')
    else:
        print('do B')

Edit following the comment by Peter

I on purpose didn't change the original concept of processing the source Series in a loop. It looks like both print instructions are rather "placeholders", to be replaced with one piece of code for NaN values and another for other values.

like image 83
Valdi_Bo Avatar answered Sep 24 '22 06:09

Valdi_Bo


No need for explicit for loops. Based on your second attempt:

# Setup
my_series = pd.Series([np.nan, np.nan, ['A', 'B']])

# Solution
np.where(my_series.isnull(), 'do A', 'do B')                                              

# Output
array(['do A', 'do A', 'do B'], dtype='<U4')
like image 44
Peter Leimbigler Avatar answered Sep 26 '22 06:09

Peter Leimbigler