Although pandas does correctly return a list (see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.tolist.html) they take the safe route and turn the values in the Series to floats and not ints. Thus when you try to get the zipcode of a float, it errors.
You can see this by running the following:
import pandas as pd import numpy as np import zipcodes list1 = [np.nan, 14975, 98121] series1 = pd.Series([np.nan,14975,98121]) def z(each): zipcode_list = [] for i in each: print(i, type(i)) try: if zipcodes.is_real(str(i)): zip_code = str(i) else: zip_code = str(1) except Exception: zip_code = str(0) zipcode_list.append(zip_code) return zipcode_list print(z(series1.tolist())) print(z(list1))
Output:
nan <class 'float'> 14975.0 <class 'float'> import pandas as pd 98121.0 <class 'float'> ['0', '0', '0'] nan <class 'float'> 14975 <class 'int'> 98121 <class 'int'> ['0', '1', '98121']
Changing the code to convert the list to ints before passing it into z will fix your problem. See:
import pandas as pd import numpy as np import zipcodes list1 = [np.nan, 14975, 98121] series1 = pd.Series([np.nan,14975,98121]) def z(each): zipcode_list = [] for i in each: try: if zipcodes.is_real(str(int(i))): zip_code = str(int(i)) else: zip_code = str(1) except Exception: zip_code = str(0) zipcode_list.append(zip_code) return zipcode_list print(z(series1.tolist())) # ['0', '1', '98121'] print(z(list1)) # ['0', '1', '98121']
is_realfor lists, so they all should evaluate tozip_code = str(0)zipcodesinside you z function