파이썬기초 국가별 ISO2코드를 대륙명으로 변환하기

조회수 1030회

안녕하세요.

국가별 iso2 코드를 대륙명으로 변환하기 위해서 5시간동안 노력하다가 막혀서 질문을 올립니다.

먼저 기존에 구글링을 통해 얻은 코드를 저에게 맞춰 아래와 같이 수정하여 성공하였습니다.

# Get 'ISO2' code, which is sustituting 'Country' column, for merging w/ other df
!pip install pycountry
import pycountry

def get_country_code(name):
    for co in list(pycountry.countries):
        if name in co.name:
            return co.alpha_2
    return None

iso2_list = []
for name in country_list: # Using existing list
  iso2_list.append(get_country_code(name))
print(iso2_list)

# Make a new column filled with 'ISO2' list
df_country['ISO2'] = iso2_list
df_country.head()

그런데 이를 활용하여 pycountry_converter라는 패키지와 함께 위의 iso2_list를 이용해 대륙 정보를 얻으려는 과정에서 def과 for loop 구문을 함께 활용하기엔 이해도가 낮아서 그런지 성공하지 못 하고 있습니다.

사용하려는 코드는 아래와 같습니다.

import pycountry_convert as pc
country_alpha2_to_continent_code()

또한 제가 시도했던 코드는 아래와 같습니다.

# 1. Making continent code column by pycountry package
# Renew definition of the list with filling empties
iso2_list = df_country['ISO2'].to_list()
## I think this way isn't working for "list" type
def get_continent_code(code):
    for co in iso2_list:
        if code in co.alpha_2:
            return pc.country_alpha2_to_continent_code(code)

continent_list = []
for code in iso2_list:
    continent_list.append(get_continent_code(code))
print(continent_list)
#pc.country_alpha2_to_continent_code(iso2_list[i])

for loop과 def, if 구문 세 가지를 혼용해서 쓰는 방법에서 제가 얄팍하게 알고 있는 syntax가 전부 붕괴된 느낌인데, 어떻게 수정해야 활용할 수 있을지, 제가 어느 부분을 잘 못 알고 있는지 지적해주시면 감사하겠습니다.

2 답변

  • 코딩하다 헷갈릴 때 가끔은 한국어로 코딩해 보면 도움이 됩니다.

    def 나라이름을코드로(알고싶은나라이름) :
        if 알고싶은나라이름 is not None:
            for 나라이름, 코드 in name_code_dict:
                if 나라이름 === 알고싶은나라이름 :
                    return 코드
        return None
    
    def 나라이름을대륙으로(알고싶은나라이름) :
        알고싶은코드 = 나라이름을코드로(알고싶은나라이름)
        if 알고싶은코드 is not None :
            for 코드, 대륙 in code_continent_dict:
                if 코드 === 알고싶은코드 :
                    return 대륙
        return None
    

    무슨 일이 일어나고 있는지 보이시죠?
    이 정도면 도움이 됐을 것으로 믿고 이만 줄이겠습니다.

    + 혹시라도 "그러면 code_continent_dict는 어디서 구해요?" 하고 궁금하실까봐 적자면... 그걸 제공하는 게 바로 pycountry 같은 라이브러리들일 겁니다.

  • pandas dataframe 에 컬럼을 하나씩 추가하면서 변환하는 방법입니다.

    
    >>> import pandas as pd
    >>> import pycountry_convert as pc
    
    >>> country_names = [ "Japan", "China", "Germany" ]
    >>> for n in country_names:
        print(n, pc.country_name_to_country_alpha2(n))
    
    
    Japan JP
    China CN
    Germany DE
    >>> pc.country_alpha2_to_country_name("KR")
    'Korea, Republic of'
    >>> pc.country_alpha2_to_country_name("KP")
    "Korea, Democratic People's Republic of"
    
    >>> country_names = [ "Korea, Republic of", "Japan", "Germany" ]
    >>> country_alpha2 = [ pc.country_name_to_country_alpha2(name) for name in country_names ]
    >>> country_alpha2
    ['KR', 'JP', 'DE']
    >>> 
    >>> 
    >>> df_countries = pd.DataFrame( { "name": country_names } )
    >>> df_countries
                     name
    0  Korea, Republic of
    1               Japan
    2             Germany
    >>> df_countries["alpha2"] = df_countries["name"].apply(pc.country_name_to_country_alpha2)
    >>> df_countries
                     name alpha2
    0  Korea, Republic of     KR
    1               Japan     JP
    2             Germany     DE
    >>> df_countries["continent_code"] = df_countries["alpha2"].apply(pc.country_alpha2_to_continent_code)
    >>> df_countries
                     name alpha2 continent_code
    0  Korea, Republic of     KR             AS
    1               Japan     JP             AS
    2             Germany     DE             EU
    
    >>> df_countries["continent"] = df_countries["continent_code"].apply(pc.convert_continent_code_to_continent_name)
    >>> df_countries
                     name alpha2 continent_code continent
    0  Korea, Republic of     KR             AS      Asia
    1               Japan     JP             AS      Asia
    2             Germany     DE             EU    Europe
    >>> 
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)