我想做的基本上是为所有 7 个大陆添加一列,并且我希望根据国家/地区所在的位置来分配大陆。添加列是简单的部分,我所要做的就是制作一个字典并将其转换为所述 Pandas DataFrame 的列,困难的部分是将所述大陆分配给 DataFrame,我尝试在网上搜索,但到目前为止我还没找到解决办法。
到目前为止,我尝试搜索其他解决方案,但是我找不到任何通过映射相关的解决方案。它们似乎太乏味了,无法输入,因为我必须输入每个国家才能使大陆地图工作。例子: 如何用大陆替换数据框列国家/地区名称?
顺便说一句,这是我用于 DataFrame 的文件: https://www.kaggle.com/datasets/deeplyft/world-population-growth-annual
任何帮助都将不胜感激,以使其不再那么乏味。
用途:
df1 = pd.read_html('https://statisticstimes.com/geography/countries-by-continents.php')[2]
print (df1.head())
No Country or Area ISO-alpha3 Code M49 Code Region 1 Region 2 \
0 1 Afghanistan AFG 4 Southern Asia NaN
1 2 Åland Islands ALA 248 Northern Europe NaN
2 3 Albania ALB 8 Southern Europe NaN
3 4 Algeria DZA 12 Northern Africa NaN
4 5 American Samoa ASM 16 Polynesia NaN
Continent
0 Asia
1 Europe
2 Europe
3 Africa
4 Oceania
d = df1.set_index('Country or Area')['Continent'].to_dict()
# print (d)
然后是地图:
df['continent'] = df['country'].map(d)