1

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
Ashish
  • 63
  • 5

2 Answers2

0

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).

Serenity
  • 35,289
  • 20
  • 120
  • 115
0

You can try:

df1['postcode'] = df1.apply(
    lambda x: postcodes.get_nearest(x['Latitude'], x['Longitude']),
    axis=1
)

You can imagine that the apply function loops every row or column of the dataframe executing a function (in this case, the lambda function).
It will loop rows when the axis option is 1, and will loop columns when axis options is 0 (default).
This lambda function receives a row as x, then it sends the 'Latitude' and 'Longitude' values to .get_nearest.

Depending on the size of your dataframe, it may take a while though.
I've tested the postcodes here and it didn't worked, but if this lib is working for you, this code should do fine.

edinho
  • 406
  • 2
  • 6