Use .replace() to convert postal codes to cities in pandas columns
I
have a list of zip codes and I’m trying to convert it to a city using the uszipcode module. My Data Frame:
index Color Postal_Code
0 blue 10006.0
1 green 11415.0
2 red 10037.0
I wrote this code and updated the columns using .replace().
def zco():
for x in zcode['Postal_Code']:
x = int(x) #convert to int because value is float
city = search.by_zipcode(x)['City'] #Module extracts the city name
if city == str(city): #The module doesn't recognize some zipcodes, thus generating None.This will skip None values.
str(x).replace(str(x), city) #replace int value with city
else: continue
zcode['Postal_Code'] = zcode['Postal_Code'].apply(zco())
But I get an error :
‘NoneType’ object is not callable
Why is that? Is there a better way to replace and update postal codes in columns?
Solution
The main problem is that instead of passing the correct callable to df.apply
, you call the zco()
> that returns None
, and then pass that to the app.
In addition, zco
must be a callable that can accept a single parameter, rather than traversing the entire column at once. df.apply
has solved this problem.
You can convert postal codes faster with df.astype
outside of zco
:
zcode['Postal_Code'].fillna(0).astype(int).astype(str).apply(zco)
Your ZCO
definition can then be shortened to:
def zco(x):
city = search.by_zipcode(x)['City']
return city if city else x # if city is None for certain zipcodes, take advantage of the truthiness of None
Note that the definition of zco
has changed significantly, accepting one parameter and operating on only one item at a time, rather than on the entire row.
Alternatively, you can use df.transform(callable, axis=1)
:
zcode['Postal_Code'].fillna(0).astype(int).astype(str).transform(zco)