Calculate Proportions
Nationally, 55% of Hispanics identify as White and 35% identify as "Some Other Race". (You can run Line 2 in the code window to confirm this.) But there is substantial state-to-state variation, which we will now investigate. As a reminder, we will express proportions as percentages throughout this course.
pandas
has been imported, the DataFrame states
is loaded with population counts by race and Hispanic origin. A list, hispanic_races
, has names of columns with Hispanics by race data, and is shown in the console.
This is a part of the course
“Analyzing US Census Data in Python”
Exercise instructions
- Use the
copy
method to create a deep copy of only thehispanic_races
columns instates
- As you iterate the races in the
hispanic_races
list, calculate the percentage of Hispanics identifying as each race as100
times the count of the currentrace
divided by the total number of Hispanics. - Print the
head
of the resulting DataFrame.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# What percentage of Hispanics identify as each race?
print(100 * states[hispanic_races].sum() / states["hispanic"].sum())
# Create a deep copy of only the Hispanic race columns
states_hr = ____.copy()
# Calculate percentages for all columns in the date frame
for race in hispanic_races:
states_hr[race] = ____ * ____ / states["hispanic"]
# View the result
print(____)