For loops through pandas dataframes for state and country

Viewed 28

I am trying to get the state location from zip codes when they are in the US. The code below is what I am using importing a csv with zip codes and country. I am getting repeating state for the first zip code in the dataframe. I tried .append on the state, country but am still just getting the return of the first row. How could I get it to run through each zip code to return that value?

import csv
import pandas as pd
from geopy.geocoders import Nominatim

# Import CSV for ZipCodes
filename='/filepath/test.csv'
df=pd.read_csv(filename, dtype=object)
df.head()

#calling Nominatim tool 
geolocator = Nominatim(user_agent="user")

state=[]
country=[]
for item in df["Zip"]:

    geolocator = Nominatim(user_agent="user")
    location = geolocator.geocode("Zip", addressdetails=True)
    state.append(getLoc.raw['address']['state'])
    country.append(getLoc.raw['address']['country'])
df['state']=state
df['country']=country

print(df.head())

These are the results I am getting:

Zip state country
0 65807, US Michigan United States
1 V92x4vr, IE Michigan United States
2 V92x4vr, IE Michigan United States
3 91010, US Michigan United States
1 Answers
df['state']=state
df['country']=country

overwrite the whole column.

You can use .apply() instead. Put your code in a function and you can do something like that:

def zip_to_state_country(zip_code):
    # your logic here
    return zip_code[0], zip_code[1]  # returns just for example

df["state"], df["country"] = zip(*df["Zip"].apply(zip_to_state_country))
Related