Package: country-converter
country converterThe country converter (coco) is a Python package to convert and match
country names between different classifications and between different
naming versions. Internally it uses regular expressions to match country
names. Coco can also be used to build aggregation concordance matrices
between different classification schemes.MotivationTo date, there is no single standard of how to name or specify
individual countries in a (meta) data description. While some data
sources follow ISO 3166, this standard defines a two and a three letter
code in addition to a numerical classification. To further complicate
the matter, instead of using one of the existing standards, many
databases use unstandardised country names to classify countries.The country converter (coco) automates the conversion from different
standards and version of country names. Internally, coco is based on a
table specifying the different ISO and UN standards per country together
with the official name and a regular expression which aim to match all
English versions of a specific country name. In addition, coco includes
classification based on UN-, EU-, OECD-membership, UN regions
specifications, continents and various MRIO and IAM databases (seeClassification schemesbelow).InstallationCountry_converter is registered at PyPI. From the command line:pip install country_converter --upgradeThe country converter is also available from theconda
forgeand can be installed using conda with
(if you don't have the conda_forge channel added to your conda config
add "-c conda-forge", seethe install instructions
here):conda install country_converterAlternatively, the source code is available onGitHub.The package depends onPandas; for testingpytestis required. For further information on
running the tests seeCONTRIBUTING.md.UsageBasic usageUse within PythonConvert various country names to some standard names:importcountry_converterascocosome_names=['United Rep. of Tanzania','DE','Cape Verde','788','Burma','COG','Iran (Islamic Republic of)','Korea, Republic of',"Dem. People's Rep. of Korea"]standard_names=coco.convert(names=some_names,to='name_short')print(standard_names)Which results in ['Tanzania', 'Germany', 'Cabo Verde', 'Tunisia',
'Myanmar', 'Congo Republic', 'Iran', 'South Korea', 'North Korea']. The
input format is determined automatically, based on ISO two letter, ISO
three letter, ISO numeric or regular expression matching. In case of any
ambiguity, the source format can be specified with the parameter 'src'.In case of multiple conversion, better performance can be achieved by
instantiating a single CountryConverter object for all conversions:importcountry_converterascococc=coco.CountryConverter()some_names=['United Rep. of Tanzania','Cape Verde','Burma','Iran (Islamic Republic of)','Korea, Republic of',"Dem. People's Rep. of Korea"]standard_names=cc.convert(names=some_names,to='name_short')UNmembership=cc.convert(names=some_names,to='UNmember')print(standard_names)print(UNmembership)In order to more efficiently convert Pandas Series, thepandas_convert()method can be used. The
performance gain is especially significant for large Series. For a series containing 1 million rows
a 4000x speedup can be achieved, compared toconvert().importcountry_converterascocoimportpandasaspdcc=coco.CountryConverter()some_countries=pd.Series(['Australia','Belgium','Brazil','Bulgaria','Cyprus','Czech Republic','Guatemala','Mexico','Honduras','Costa Rica','Colombia','Greece','Hungary','India','Indonesia','Ireland','Italy','Japan','Latvia','Lithuania','Luxembourg','Malta','Jamaica','Ireland','Turkey','United Kingdom','United States'],name='country')iso3_codes=cc.pandas_convert(series=some_countries,to='ISO3')Convert between classification schemes:iso3_codes=['USA','VUT','TKL','AUT','XXX']iso2_codes=coco.convert(names=iso3_codes,to='ISO2')print(iso2_codes)Which results in ['US', 'VU', 'TK', 'AT', 'not found']The not found indication can be specified (e.g. not_found = 'not
there'), if None is passed for 'not_found', the original entry gets
passed through:iso2_codes=coco.convert(names=iso3_codes,to='ISO2',not_found=None)print(iso2_codes)results in ['US', 'VU', 'TK', 'AT', 'XXX']Internally the data is stored in a Pandas DataFrame, which can be
accessed directly. For example, this can be used to filter countries for
membership organisations (per year). Note: for this, an instance of
CountryConverter is required.importcountry_converterascococc=coco.CountryConverter()some_countries=['Australia','Belgium','Brazil','Bulgaria','Cyprus','Czech Republic','Denmark','Estonia','Finland','France','Germany','Greece','Hungary','India','Indonesia','Ireland','Italy','Japan','Latvia','Lithuania','Luxembourg','Malta','Romania','Russia','Turkey','United Kingdom','United States']oecd_since_1995=cc.data[(cc.data.OECD>=1995)&cc.data.name_short.isin(some_countries)].name_shorteu_until_1980=cc.data[(cc.data.EU<=1980)&cc.data.name_short.isin(some_countries)].name_shortprint(oecd_since_1995)print(eu_until_1980)All classifications can be directly accessed by:cc.EU28cc.OECDcc.EU27as('ISO3')and the classification schemes available:cc.valid_classThere is also a methdod for only getting country classifications (thus
omitting any grouping of countries):cc.valid_country_classificationsIf you rather need a dictionary describing the classification/membership
use:importcountry_converterascococc=coco.CountryConverter()cc.get_correspondence_dict('EXIO3','ISO3')to also include countries not assigned within a specific classification
use:cc.get_correspondence_dict('EU27','ISO2',replace_nan='NonEU')The regular expressions can also be used to match any list of countries
to any other. For example:match_these=['norway','united_states','china','taiwan']master_list=['USA','The Swedish Kingdom','Norway is a Kingdom too','Peoples Republic of China','Republic of China']matching_dict=coco.match(match_these,master_list)Country converter by default provides a warning to the pythonlogginglogger if no match is found. The
following example demonstrates how to configure thecocologging behaviour.importloggingimportcountry_converterascocologging.basicConfig(level=logging.INFO)coco.convert("asdf")# WARNING:country_converter.country_converter:asdf not found in regex# Out: 'not found'coco_logger=coco.logging.getLogger()coco_logger.setLevel(logging.CRITICAL)coco.convert("asdf")# Out: 'not found'See the IPython Notebook
(country_converter_examples.ipynb)
for more information.Command line usageThe country converter package also provides a command line interface
called coco.Minimal example:coco Cyprus DE Denmark Estonia 4 'United Kingdom' AUTConverts the given names to ISO3 codes based on matching the input to
ISO2, ISO3, ISOnumeric or regular expression matching. The list of names
must be separated by spaces, country names consisting of multiple words
must be put in quotes ('').The input classification can be specified with '--src' or '-s' (or will
be determined automatically), the target classification with '--to' or
'-t'.The default output is a space separated list, this can be changed by
passing a separator by '--output_sep' or '-o' (e.g -o '|').Thus, to convert from ISO3 to UN number codes and receive the output as
comma separated list use:coco AUT DEU VAT AUS -s ISO3 -t UNcode -o ', 'The command line tool also allows to specify the output for none found
entries, including passing them through to the output by passing None:coco CAN Peru US Mexico Venezuela UK Arendelle --not_found=Noneand to specify an additional data file which will overwrite existing
country matchingcoco Congo --additional_data path/to/datafile.csvSeehttps://github.com/IndEcol/country_converter/tree/master/tests/custom_data_example.txtfor an example of an additional datafile.The flags --UNmember_only (-u) and --include_obsolete (-i) restrict the
search to UN member states only or extend it to also include currently
obsolete countries. For example, theNetherlands
Antilleswere
dissolved in 2010.Thus:coco "Netherlands Antilles"results in "not found". The search, however, can be extended to recently
dissolved countries by:coco "Netherlands Antilles" -iwhich results in 'ANT'.In addition to the countries, the coco command line tool also accepts
various country classifications (EXIO1, EXIO2, EXIO3, WIOD, Eora,
MESSAGE, OECD, EU27, EU28, UN, obsolete, Cecilia2050, BRIC, APEC, BASIC,
CIS, G7, G20). One of these can be passed bycoco G20which lists all countries in that classification.For the classifications covering almost all countries (MRIO and IAM
classifications)coco EXIO3lists the unique classification names. When passing a --to parameter, a
simplified correspondence of the chosen classification is printed:coco EXIO3 --to ISO3For further information call the help bycoco -hUse in MatlabNewer (tested in 2016a) versions of Matlab allow to directly call Python
functions and libraries. This requires a Python version >= 3.4
installed in the system path (e.g. through Anaconda).To test, try this in Matlab:py.print(py.sys.version)If this works, you can also use coco after installing it through pip (at
the windows commandline - see the installing instruction above):pipinstallcountry_converter--upgradeAnd in matlab:coco=py.country_converter.CountryConverter()countries={'The Swedish Kingdom','Norway is a Kingdom too','Peoples Republic of China','Republic of China'};ISO2_pythontype=coco.convert(countries,pyargs('to','ISO2'));ISO2_cellarray=cellfun(@char,cell(ISO2_pythontype),'UniformOutput',false);Alternatively, as a long oneliner:short_names=cellfun(@char,cell(py.country_converter.convert({56,276},pyargs('src','UNcode','to','name_short'))),'UniformOutput',false);All properties of coco as explained above are also available in Matlab:coco=py.country_converter.CountryConverter();coco.EU27EU27ISO3=coco.EU27as('ISO3');These functions return a Pandas DataFrame. The underlying values can be
access with .values (e.g.EU27ISO3.valuesI leave it to professional Matlab users to figure out how to further
process them.See also IPython Notebook
(country_converter_examples.ipynb)
for more information - all functions available in Python (for example
passing additional data files, specifying the output in case of missing
data) work also in Matlab by passing arguments through the pyargs
function.Building concordances for country aggregationCoco provides a function for building concordance vectors, matrices and
dictionaries between different classifications. This can be used in
python as well as in matlab. For further information see
(country_converter_aggregation_helper.ipynb)Classification schemesCurrently the following classification schemes are available (see also
Data sources below for further information):ISO2 (ISO 3166-1 alpha-2) - including UK/EL for Britain/Greece (but always convert to GB/GR)ISO3 (ISO 3166-1 alpha-3)ISO - numeric (ISO 3166-1 numeric)UN numeric code (M.49 - follows to a large extend ISO-numeric)A standard or short nameThe "official" nameContinent: 6 continent classification with Africa, Antarctica, Asia, Europe, America, OceaniaContinent_7 classification- 7 continent classification spliting North/South AmericaUN regionEXIOBASE 1classification (2 and 3 letters)EXIOBASE 2classification (2 and 3 letters)EXIOBASE 3classification (2 and 3 letters)WIODclassificationEoraOECDmembership (per year)MESSAGE11-region classificationIMAGEREMINDUNmembership (per year)EUmembership (including EU12, EU15, EU25, EU27, EU27_2007, EU28)EEAmembershipSchengenregionCecilia2050 classificationAPECBRICBASICCIS(as by 2019, excl. Turkmenistan)G7G20(listing all EU member
states as individual members)FAOcode(numeric)GBDcode(numeric - Global Burden of
Disease country codes)IEA(World Energy Balances 2021)DACcode(numeric - OECD Development Assistance Committee)ccTLD- country code top-level domainsGWcode- Gledisch & Ward numerical codes as published inhttps://www.andybeger.com/states/articles/statelists.htmlCC41 - common classification for MRIOs (list of countries found in all public MRIOs)IOC- International Olympic Committee (IOC) country codesCoco contains official recognised codes as well as non-standard codes
for disputed or dissolved countries. To restrict the set to only the
official recognized UN members or include obsolete countries, passimportcountry_converterascococc=coco.CountryConverter()cc_UN=coco.CountryConverter(only_UNmember=True)cc_all=coco.CountryConverter(include_obsolete=True)cc.convert(['PSE','XKX','EAZ','FRA'],to='name_short')cc_UN.convert(['PSE','XKX','EAZ','FRA'],to='name_short')cc_all.convert(['PSE','XKX','EAZ','FRA'],to='name_short')cc results in ['Palestine', 'Kosovo', 'not found', 'France'], whereas
cc_UN converts to ['not found', 'not found', 'not found', 'France']
and cc_all converts to ['Palestine', 'Kosovo', 'Zanzibar', 'France']
Note that the underlying dataframe is available at the attribute .data
(e.g. cc_all.data).Data sources and further readingMost of the underlying data can be found in Wikipedia, the page describingISO
3166-1is a good starting point. The
page on theISO2 codesincludes a section "Imperfect Implementations" explaining the GB/UK and EL/GR
issue.
UN regions/codes are given on the United Nation
Statistical Division
(unstats)
webpage. The differences between the ISO numeric and UN (M.49) codes arealso explained at wikipedia.EXIOBASE,WIODandEoraclassification were extracted from the
respective databases. ForEora, the names
are based on the 'Country names' csv file provided on the webpage, but
updated for different names used in the Eora26 database. The MESSAGE
classification follows the 11-region aggregation given in theMESSAGEmodel regions description. TheIMAGEclassification is based on the "region classification
map",
forREMINDwe received a country mapping from the model developers.The membership ofOECDandUNcan be found at the membership
organisations' webpages, information about obsolete country codes on theStatoidswebpage.The situation for theEUgot complicated due to the Brexit process. For the naming, coco follows
theEurostat
glossary,
thus EU27 refers to the EU without UK, whereas EU27_2007 refers to the
EU without Croatia (the status after the 2007 enlargement). The shortcut
EU always links to the most recent classification. TheEEAagreements for the UK ended by 2021-01-01 (which also affects Guernsey, Isle of Man, Jersey and Gibraltar).
Switzerland is not part of the EEA but member of the single market.The Global Burden of Disease country codes were extracted form theGBD
code book available
here.Communication, issues, bugs and enhancementsPlease use the issue tracker for documenting bugs, proposing
enhancements and all other communication related to coco.You can follow me onmastodon - @kst@qoto.organdtwitterto get
the latest news about all my open-source and research projects (and
occasionally some random retweets/toots).ContributingWant to contribute? Great! Please checkCONTRIBUTING.mdif you want to help to improve coco
and for some pointer for how to add classifications.Related softwareThe packagepycountryprovides
access to the official ISO databases for historic countries, country
subdivisions, languages and currencies. In case you need to convert
non-English country names,countrynamesincludes an
extensive database of country names in different languages and functions
to convert them to the different ISO 3166 standards.Python-iso3166focuses
on conversion between the two-letter, three-letter and three-digit codes
defined in the ISO 3166 standard.If you are using R, you should have a look atcountrycode.Citing the country converterVersion 0.5 of the country converter was published in theJournal of
Open Source Software. To cite the country
converter in publication please use:Stadler, K. (2017). The country converter coco - a Python package for
converting country names between different classification schemes. The
Journal of Open Source Software. doi:10.21105/joss.00332For the full bibtex key seeCITATIONAcknowledgementsThis package was inspired by (and the regular expression are mostly
based on) the R-packagecountrycodebyVincent Arel-Bundockand his (defunct) port
to Python (pycountrycode). Many thanks toRobert
Giesekefor the review of the source code
and paper for the publication in theJournal of Open Source
Software.