2017-10-06 106 views
1

Hej!国家数据:根据字典更名为熊猫

我正在对国别统计数据进行一些数据分析。我现在使用来自不同来源的数据,并且很快就会看到,有些国家会有不同的呼叫方式:世界银行称它为“英国和北爱尔兰”,世界卫生组织称之为“英国”,意思是相同的政治建构(我意识到英格兰,苏格兰和威尔士是“国家”,而不是英国)。

我创建了一本字典,我把大部分不同的名字都标准化为世界银行数据。这在列表中的作用就像一个魅力,但我需要它在一个熊猫DataFrame中,我从pd.read_csv得到。 在例如:如果我有一个很短的字典

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等?)。这可能是上述问题的延伸。

回答

2

使用replace

df['country'] = df['country'].replace(dic) 

而对于ISO 3166-1阿尔法 - 3检查answers

我认为simpliest是从here下载。

如果想从wikipedia解析代码可以使用this溶液或python 3 rewrited为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 
+0

等你刮维基百科网页和转换为'dic' – Dark

+0

:)不是那么容易; 0 – jezrael

+0

https://gis.stackexchange.com/questions/1047/full-list-of-iso-alpha-2-and-iso-alpha-3-country-codes可能有帮助 – Dark