pandas - 如何在熊猫中进行此操作
问题描述
我有一个包含国家列的数据框。不幸的是,国家名称字符都是大写的,我需要它们是 ISO3166_1_Alpha_3
例如美国将是美国英国将是英国等等。
幸运的是,我在互联网上找到了这个数据框,其中包含 2 个重要列,第一个是国家名称,第二个是 ISO3166_1_Alpha_3 你可以在这个网站上找到这个数据框 https://datahub.io/JohnSnowLabs/iso-3166-country -codes-itu-dialing-codes-iso-4217-currency-codes
所以我写了这段代码
data_geo = pd.read_excel("tab0.xlsx")#this is the data frame that contains all the capitalized country name
country_iso = pd.read_csv(r"https://datahub.io/JohnSnowLabs/iso-3166-country-codes-itu-dialing-codes-iso-4217-currency-codes/r/iso-3166-country-codes-itu-dialing-codes-iso-4217-currency-codes-csv.csv",
usecols=['Official_Name_English', 'ISO3166_1_Alpha_3'])
s = pd.Series(data_geo.countery_name_e).str.lower().str.title()#this line make all the names characters small except the first character
y = pd.Series([])
现在我想在一个循环
s = Official_Name_English
我想追加
country_iso[Official_Name_English].ISO3166_1_Alpha_3
到Y
系列。如果国家/地区名称不在此列表中,则附加NaN
这是 s 中的 20 行
['Diffrent Countries', 'Germany', 'Other Countries', 'Syria',
'Jordan', 'Yemen', 'Sudan', 'Somalia', 'Australia',
'Other Countries', 'Syria', 'Lebanon', 'Jordan', 'Yemen', 'Qatar',
'Sudan', 'Ethiopia', 'Djibouti', 'Somalia', 'Botswana Land']
你知道我怎么做这个吗?
解决方案
你可以试试map
:
data_geo = pd.read_excel("tab0.xlsx")
country_iso = pd.read_csv(r"https://datahub.io/JohnSnowLabs/iso-3166-country-codes-itu-dialing-codes-iso-4217-currency-codes/r/iso-3166-country-codes-itu-dialing-codes-iso-4217-currency-codes-csv.csv",
usecols=['Official_Name_English', 'ISO3166_1_Alpha_3'])
s = pd.Series(data_geo.countery_name_e).str.lower().str.title()
mapper = (country_iso.drop_duplicates('Official_Name_English')
.dropna(subset=['Official_Name_English'])
.set_index('Official_Name_English')['ISO3166_1_Alpha_3'])
y = data_geo['countery_name_e'].map(mapper)
推荐阅读
- ansible - Ansible 模板和 jinja {%block%}
- datetime - ColdFusion UTC TIME LTE 检查与 NonUTC 时间
- excel - 循环链接并下载 PDF
- python - 为什么我的刮刀没有返回美丽汤?
- c# - 什么可能导致 COM 组件被注册(在 Visual Studio 参考 COM 部分中显示)但在 Office ActiveX 组件中不可见?
- c - 从汇编代码用 C 语言设计一个函数
- kubernetes - 与具有相同子路径的 pod 中的两个容器共享 Kubernetes 中的 s3fs 卷
- vue.js - 在 ag-grid 中获取数据
- javascript - 如何解决使用 p5 创建板的问题
- rust - 安装 rust 后如何从我的 PATH 中删除生锈货物