我想从pandas中的数据帧df1中读取两列(纬度和经度)并创建一个新的列邮政编码,并在数据框的每一行添加zipcode。
我认为这个网页很有用:https://postcodes.readthedocs.io/en/latest/
df1 = df[['Col1',' Col2', 'Col3','Col4', 'Col5', 'Latitude', 'Longitude']]
for row in df1[7]:
# Try to,
try:
# get lat long and find the post code
postcodes.get_nearest(lat, lng)
# But if you get an error
except:
# error
# Create a new columns post code in df1
df1['postcode'] = zipcode
您必须使用apply
根据数据框的其他数据创建新列。
def getPostcode(row):
try:
row['postcode']=postcodes.get_nearest(row['Latitude'], row['Longitude'])
except:
print('Error for data {0}'.format(row))
return row
然后在init df1
之后将此行添加到主代码中:
df1.apply(getPostcode,axis=1)
。
你可以试试:
df1['postcode'] = df1.apply(
lambda x: postcodes.get_nearest(x['Latitude'], x['Longitude']),
axis=1
)
您可以想象apply函数循环执行函数的数据帧的每一行或每一列(在本例中为lambda函数)。 它将在axis选项为1时循环行,并在轴选项为0时循环列(默认值)。 这个lambda函数接收一行为x,然后它将'Latitude'和'Longitude'值发送给.get_nearest。
根据数据框的大小,可能需要一段时间。 我已经在这里测试过邮政编码但它没有用,但是如果这个lib对你有效,那么这段代码应该没问题。