当他们在美国时,我正试图从邮政编码中获取州位置。下面的代码是我用来导入带有邮政编码和国家/地区的csv的代码。我得到了数据帧中第一个邮政编码的重复状态。我试过了。附加在州,国家,但仍然只是得到第一排的回报。我怎样才能让它在每个邮政编码中运行以返回该值?
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())
以下是我得到的结果:
邮编 | 州 | 国家|
---|---|---|
0 | 65807,美国 | 密歇根州 | 美国
1 | V92x4vr,IE | 密歇根州 | 美国
2 | V92x4vr,IE | 密歇根州 | 美国
3 | 91010,美国 | 密歇根州 | 美国
df['state']=state
df['country']=country
覆盖整列。
您可以改用.apply((。把你的代码放在一个函数中,你可以做这样的事情:
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))