Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save JonathanLoscalzo/5896420a90d15e59a346398e771f2a28 to your computer and use it in GitHub Desktop.

Select an option

Save JonathanLoscalzo/5896420a90d15e59a346398e771f2a28 to your computer and use it in GitHub Desktop.
pandas between, groupby, isin, nunique example cold_war

Counting USA vs. USSR Cold War Olympic Sports The Olympic competitions between 1952 and 1988 took place during the height of the Cold War between the United States of America (USA) & the Union of Soviet Socialist Republics (USSR). Your goal in this exercise is to aggregate the number of distinct sports in which the USA and the USSR won medals during the Cold War years.

The construction is mostly the same as in the preceding exercise. There is an additional filtering stage beforehand in which you reduce the original DataFrame medals by extracting data from the Cold War period that applies only to the US or to the USSR. The relevant country codes in the DataFrame, which has been pre-loaded as medals, are 'USA' & 'URS'.

# Extract all rows for which the 'Edition' is between 1952 & 1988: during_cold_war
during_cold_war = medals.Edition.between(1952, 1988, inclusive=True)
# Extract rows for which 'NOC' is either 'USA' or 'URS': is_usa_urs
is_usa_urs = medals.NOC.isin(['USA', 'URS'])
# Use during_cold_war and is_usa_urs to create the DataFrame: cold_war_medals
cold_war_medals = medals.loc[is_usa_urs & during_cold_war]
# Group cold_war_medals by 'NOC'
country_grouped = cold_war_medals.groupby('NOC')
# Create Nsports
Nsports = country_grouped.Sport.nunique()
# Print Nsports
print(Nsports)
# NOC
# URS 21
# USA 20
# Name: Sport, dtype: int64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment