안녕하세요.
국가별 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가 전부 붕괴된 느낌인데, 어떻게 수정해야 활용할 수 있을지, 제가 어느 부분을 잘 못 알고 있는지 지적해주시면 감사하겠습니다.
- 참고 Get continent code from country code / using "country_alpha2_to_continent_code()" from pycountry_convert https://stackoverflow.com/questions/55910004/get-continent-name-from-country-using-pycountry