Python reference¶
countrycode¶
countrycode.countrycode.countrycode(sourcevar, origin, destination, custom_dict=None, *, warn=True, nomatch=_DEFAULT_NOMATCH, custom_match=None, origin_regex=None)
¶
Convert country codes or names from one format to another.
Converts long country names into coding schemes, translates between schemes, standardizes country names, and identifies continents or regions. The built-in conversion dictionary supports ISO, Correlates of War, Gleditsch-Ward, World Bank, Unicode flag, and many other fields.
Multiple destinations are tried from left to right. Each destination fills values not covered by an earlier one. Country-name origins use regular expressions; other built-in origins use case-insensitive exact matching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sourcevar
|
Any
|
Country codes or names to convert. Accepts a scalar, list, tuple, Pandas Series, Polars Series, or another iterable. |
required |
origin
|
str
|
Name of the source coding scheme, such as |
required |
destination
|
str | Sequence[str]
|
Destination coding scheme, or a sequence of schemes to
try in order, such as |
required |
custom_dict
|
Any
|
Optional replacement dictionary. Accepts a mapping of
column names to equal-length sequences, a Pandas or Polars
DataFrame, or a path to a |
None
|
warn
|
bool
|
Emit warnings listing unmatched or ambiguous input values. |
True
|
nomatch
|
Any
|
Replacement for unmatched values. By default they become
|
_DEFAULT_NOMATCH
|
custom_match
|
Mapping[Any, Any] | None
|
Mapping of input values to destination values. These overrides supersede normal or ambiguous matches. |
None
|
origin_regex
|
bool | None
|
Whether the origin column contains regular expressions. The default selects regex matching for built-in country-name origins and exact matching otherwise. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Converted values. A scalar input returns a scalar; lists and tuples |
Any
|
retain their container kind; Pandas and Polars Series retain their |
Any
|
respective type and metadata where applicable. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If a code field is invalid, a numeric origin receives
non-numeric input, the custom dictionary is malformed, or
|
FileNotFoundError
|
If a custom dictionary path does not exist. |
NotImplementedError
|
If a custom dictionary type or file format is unsupported. |
Examples:
Convert ISO codes to Correlates of War numeric codes:
Convert an English country name to ISO:
Try a historical code first, then fall back to ISO:
Note
Country-year data require special care because some political units,
including Vietnam and Serbia, change codes over time. For panel data,
prefer :func:countrycode.datasets.load_codelist_panel and merge on
the appropriate year instead of relying on the cross-sectional
dictionary.
Source code in python/countrycode/countrycode.py
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | |
countryname¶
countrycode.helpers.countryname(sourcevar, destination='country.name.en', *, nomatch=_DEFAULT_NOMATCH, warn=True)
¶
Convert country names in many languages to another name or code.
The function makes two passes over the data. First it detects country-name
variations in many languages extracted from the Unicode Common Locale Data
Repository. It then applies the English country-name patterns used by
:func:countrycode to unresolved values.
Because the two-pass approach is permissive, some names can be ambiguous,
such as Saint Martin versus Saint Martin (French part). Use
countrycode(x, "country.name", "country.name") when stricter English
name matching is preferable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sourcevar
|
Any
|
Country names to convert. Non-ASCII names are supported.
Accepts the same scalar and container types as :func: |
required |
destination
|
str
|
Destination country-name or coding field. Defaults to the
standardized English name, |
'country.name.en'
|
nomatch
|
Any
|
Replacement for unmatched values. By default they become
|
_DEFAULT_NOMATCH
|
warn
|
bool
|
Emit warnings listing values that could not be matched. |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
Converted names or codes, preserving the scalar or container type of |
Any
|
|
Examples:
>>> countryname(["Barbadas", "Sverige", "UK"])
['Barbados', 'Sweden', 'United Kingdom']
>>> countryname(["Barbadas", "Sverige"], destination="iso3c")
['BRB', 'SWE']
Source code in python/countrycode/helpers.py
guess_field¶
countrycode.helpers.guess_field(codes, min_similarity=80)
¶
Guess which coding scheme or name field contains a collection of values.
Compares the unique supplied values with every field in the built-in
countrycode dictionary and ranks fields by their match percentage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
codes
|
Any
|
Country codes or country names. Scalars and iterable inputs
accepted by :func: |
required |
min_similarity
|
float
|
Minimum percentage of unique, non-missing values that must occur in a field for that field to be returned. |
80
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
A list of dictionaries sorted by decreasing match percentage. Each |
list[dict[str, Any]]
|
dictionary contains |
list[dict[str, Any]]
|
|
list[dict[str, Any]]
|
non-missing values are supplied or no field meets the threshold. |
Examples:
Source code in python/countrycode/helpers.py
get_dictionary¶
countrycode.helpers.get_dictionary(dictionary=None)
¶
List or download a maintained custom conversion dictionary.
Downloaded dictionaries can be passed directly to the custom_dict
argument of :func:countrycode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dictionary
|
str | None
|
Name of the dictionary to retrieve. If omitted, return the names of all available dictionaries. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[Any]] | tuple[str, ...]
|
A tuple of available names when |
dict[str, list[Any]] | tuple[str, ...]
|
a mapping of column names to values suitable for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
URLError
|
If the remote dictionary cannot be downloaded. |
Examples:
List available dictionaries:
Download and use a dictionary:
>>> states = get_dictionary("us_states")
>>> countrycode(
... "MO", "state.abb", "state.name", custom_dict=states
... )
'Missouri'
Source code in python/countrycode/helpers.py
Supplementary datasets¶
countrycode.datasets.load_dataset(name, as_type='dict')
¶
Load a supplementary dataset distributed with countrycode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Dataset name. Valid values are |
required |
as_type
|
Literal['dict', 'pandas', 'polars']
|
Output representation: |
'dict'
|
Returns:
| Type | Description |
|---|---|
Any
|
A mapping of column names to lists, a Pandas DataFrame, or a Polars |
Any
|
DataFrame, depending on |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If the requested optional DataFrame library is not installed. |
Examples:
Source code in python/countrycode/datasets.py
countrycode.datasets.load_codelist_panel(as_type='dict')
¶
Load the reconciled country-year conversion dictionary.
The panel contains country-year observations with multiple coding schemes. It is preferable to the cross-sectional dictionary when political units or codes change over time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_type
|
Literal['dict', 'pandas', 'polars']
|
Output representation: |
'dict'
|
Returns:
| Type | Description |
|---|---|
Any
|
The country-year panel in the requested representation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If the requested optional DataFrame library is absent. |
Examples:
Source code in python/countrycode/datasets.py
countrycode.datasets.load_countryname_dict(as_type='dict')
¶
Load alternative country names used by :func:countryname.
The dataset pairs standardized English country names with alternative names drawn from many languages and sources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_type
|
Literal['dict', 'pandas', 'polars']
|
Output representation: |
'dict'
|
Returns:
| Type | Description |
|---|---|
Any
|
The alternative-name dictionary in the requested representation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If the requested optional DataFrame library is absent. |
Examples:
Source code in python/countrycode/datasets.py
countrycode.datasets.load_cldr_examples(as_type='dict')
¶
Load examples of available Unicode CLDR destination fields.
The dataset associates CLDR field codes with example country names and is
useful for choosing among the hundreds of cldr.* destinations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_type
|
Literal['dict', 'pandas', 'polars']
|
Output representation: |
'dict'
|
Returns:
| Type | Description |
|---|---|
Any
|
The CLDR examples in the requested representation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If the requested optional DataFrame library is absent. |
Examples: