国家数据:根据 pandas 中的字典重命名国家
Country Data: Renaming countries according to dict in pandas
嘿!
我正在从事国家统计的一些数据分析。我现在使用来自不同来源的数据,很快就会看到,有时国家/地区的称呼不同:虽然世界银行称之为 "United Kingdom and Northern Ireland",但 WHO 可能简称为 "United Kingdom",意思是相同的政治构造(我知道英格兰、苏格兰和威尔士是 "countries" 而不是真正的英国)。
我创建了一个字典,其中我将大部分不同的名称标准化为世界银行数据。这在列表中就像一个魅力,但我需要它在我从 pd.read_csv
获得的 pandas DataFrame 中。
例如:如果我有一本很短的字典
dict = {'US': 'USA'}
如何在我的数据框中转换它(将 df.country
中的列设置为 dict.key
值)?
在示例中显示:
ID country val
1 US some values
至:
ID country val
1 USA some values
对于我的列表转换,我使用了以下结构,其中 listB
是输入和输出列表:
for key in dict:
listB = [w.replace(key, dict[key]) for w in listB]
有什么建议可以最轻松地做到这一点吗?任何帮助都会很棒!
P.S:另外,有没有人知道如何生成 ISO 3166-1 alpha-3 代码(例如德国 = GER、瑞典 = SWE 等等?)。这可能是上述问题的延伸。
使用replace
:
df['country'] = df['country'].replace(dic)
并且对于 ISO 3166-1 alpha-3 检查 answers。
我认为最简单的是从 here 下载它。
如果想要从 wikipedia
解析代码是可能的,请使用 this 解决方案或在 python 3
中为 DataFrame
重写:
from bs4 import BeautifulSoup
import requests
url = "http://en.wikipedia.org/wiki/ISO_3166-1"
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
t = soup.findAll('table', {'class' : 'wikitable sortable'})[1]
L = []
cs = [th.findAll(text=True)[0] for th in t.findAll('th')]
for row in t.findAll("tr")[1:]:
tds = row.findAll('td')
raw_cols = [td.findAll(text=True) for td in tds]
cols = []
# country field contains differing numbers of elements, due to the flag --
# only take the name
cols.append(raw_cols[0][-1:][0])
# for all other columns, use the first result text
cols.extend([col[0] for col in raw_cols[1:]])
L.append(cols)
df = pd.DataFrame(L, columns=cs)
print (df.head())
English short name (upper/lower case) Alpha-2 code Alpha-3 code \
0 Afghanistan AF AFG
1 Åland Islands AX ALA
2 Albania AL ALB
3 Algeria DZ DZA
4 American Samoa AS ASM
Numeric code Link to Independent
0 004 ISO 3166-2:AF Yes
1 248 ISO 3166-2:AX No
2 008 ISO 3166-2:AL Yes
3 012 ISO 3166-2:DZ Yes
4 016 ISO 3166-2:AS No
您可以使用函数 clean_country()
from the library DataPrep 将国家/地区名称列转换为 ISO 3166-1 alpha-3 代码。使用 pip install dataprep
.
安装 DataPrep
from dataprep.clean import clean_country
df = pd.DataFrame({"country": ["Germany", "Sweden", "US"]})
df2 = clean_country(df, "country", output_format="alpha-3")
df2
country country_clean
0 Germany DEU
1 Sweden SWE
2 US USA
嘿!
我正在从事国家统计的一些数据分析。我现在使用来自不同来源的数据,很快就会看到,有时国家/地区的称呼不同:虽然世界银行称之为 "United Kingdom and Northern Ireland",但 WHO 可能简称为 "United Kingdom",意思是相同的政治构造(我知道英格兰、苏格兰和威尔士是 "countries" 而不是真正的英国)。
我创建了一个字典,其中我将大部分不同的名称标准化为世界银行数据。这在列表中就像一个魅力,但我需要它在我从 pd.read_csv
获得的 pandas DataFrame 中。
例如:如果我有一本很短的字典
dict = {'US': 'USA'}
如何在我的数据框中转换它(将 df.country
中的列设置为 dict.key
值)?
在示例中显示:
ID country val
1 US some values
至:
ID country val
1 USA some values
对于我的列表转换,我使用了以下结构,其中 listB
是输入和输出列表:
for key in dict:
listB = [w.replace(key, dict[key]) for w in listB]
有什么建议可以最轻松地做到这一点吗?任何帮助都会很棒!
P.S:另外,有没有人知道如何生成 ISO 3166-1 alpha-3 代码(例如德国 = GER、瑞典 = SWE 等等?)。这可能是上述问题的延伸。
使用replace
:
df['country'] = df['country'].replace(dic)
并且对于 ISO 3166-1 alpha-3 检查 answers。
我认为最简单的是从 here 下载它。
如果想要从 wikipedia
解析代码是可能的,请使用 this 解决方案或在 python 3
中为 DataFrame
重写:
from bs4 import BeautifulSoup
import requests
url = "http://en.wikipedia.org/wiki/ISO_3166-1"
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
t = soup.findAll('table', {'class' : 'wikitable sortable'})[1]
L = []
cs = [th.findAll(text=True)[0] for th in t.findAll('th')]
for row in t.findAll("tr")[1:]:
tds = row.findAll('td')
raw_cols = [td.findAll(text=True) for td in tds]
cols = []
# country field contains differing numbers of elements, due to the flag --
# only take the name
cols.append(raw_cols[0][-1:][0])
# for all other columns, use the first result text
cols.extend([col[0] for col in raw_cols[1:]])
L.append(cols)
df = pd.DataFrame(L, columns=cs)
print (df.head())
English short name (upper/lower case) Alpha-2 code Alpha-3 code \
0 Afghanistan AF AFG
1 Åland Islands AX ALA
2 Albania AL ALB
3 Algeria DZ DZA
4 American Samoa AS ASM
Numeric code Link to Independent
0 004 ISO 3166-2:AF Yes
1 248 ISO 3166-2:AX No
2 008 ISO 3166-2:AL Yes
3 012 ISO 3166-2:DZ Yes
4 016 ISO 3166-2:AS No
您可以使用函数 clean_country()
from the library DataPrep 将国家/地区名称列转换为 ISO 3166-1 alpha-3 代码。使用 pip install dataprep
.
from dataprep.clean import clean_country
df = pd.DataFrame({"country": ["Germany", "Sweden", "US"]})
df2 = clean_country(df, "country", output_format="alpha-3")
df2
country country_clean
0 Germany DEU
1 Sweden SWE
2 US USA