Pandas - 使用PostCoder在每行中查找纬度和经度,然后在新列中返回Postcode

问题描述 投票:1回答:2

我想从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
python pandas dataframe postal-code
2个回答
0
投票

您必须使用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)


0
投票

你可以试试:

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对你有效,那么这段代码应该没问题。

© www.soinside.com 2019 - 2024. All rights reserved.