问题 wind Pandas map 方法(用于从另一个数据框中添加数据框中的列)

Problem wind Pandas map method (for adding columns in dataframe from another dataframe)

我有一个带有 'Country' 列和一些其他数据的数据框,我想从另一个数据框中为每个国家/地区添加经度和纬度。我使用“地图”方法在第二个数据框中找到每个国家并添加到第一个数据框中。

df_filteres['longitude'] = df_filteres['Country'].map(lambda item : df_countries[df_countries['country'] == item].iloc[0, 2])

如果我将 'item' 替换为示例国家/地区名称 (ex.Germany),它会起作用,但如果使用 'item',它会 returns 此错误:

IndexError: 单个位置索引器越界

哪一部分不正确?

有一个更好的方法可以不使用地图来解决这个问题。通读 join / merge / concatenate documentation 以更好地理解您正在执行的操作风格,并找到合适的示例作为工作基础。

一般来说,对于这个问题,您会在键 country 上进行左合并,但只能对属于另一个数据帧的列 longitude 进行合并。

df_subset = df_countries[['country', 'longitude']]
df_filteres = df_filteres.merge(df_subset, on='country', how='left')

你可以试试:

df_filteres['longitude'] = df_filteres['Country'].map(df_countries.set_index('country').iloc[:, 1])