I want read two columns (Latitude & longitude) from my dataframe df1 in pandas and create a new column zipcode and add zipcode at each row in the dataframe.
I think this webpage is useful: 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
You have to use apply
to create new column based on other data of dataframe.
def getPostcode(row):
try:
row['postcode']=postcodes.get_nearest(row['Latitude'], row['Longitude'])
except:
print('Error for data {0}'.format(row))
return row
Then add this line to main code after init df1
:
df1.apply(getPostcode,axis=1)
.