Skip to content
Intermediate Python
Intermediate Python
Run the hidden code cell below to import the data used in this course.
# Import the course packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Import the two datasets
gapminder = pd.read_csv("datasets/gapminder.csv")
brics = pd.read_csv("datasets/brics.csv")
DataFrameas
df
variable
Take Notes
Add notes about the concepts you've learned and code cells with code you want to keep.
Numpy is a python module for mathematical calculation and operation. All the values in numpy array are in numbers. Panda is another python module with database capability making tables and showing information in different tabular format. Matplotlib is python module to display data in various ways. read_csv is a pandas method to read csv file.
# Add your code snippets here
Add your notes here
Explore Datasets
Use the DataFrames imported in the first cell to explore the data and practice your skills!
- Create a loop that iterates through the
brics
DataFrame and prints "The population of {country} is {population} million!". - Create a histogram of the life expectancies for countries in Africa in the
gapminder
DataFrame. Make sure your plot has a title, axis labels, and has an appropriate number of bins. - Simulate 10 rolls of two six-sided dice. If the two dice add up to 7 or 11, print "A win!". If the two dice add up to 2, 3, or 12, print "A loss!". If the two dice add up to any other number, print "Roll again!".
for index, row in brics.iterrows():
country = row['country']
population = row['population']
print(f"The population of {country} is {population} million!")
import pandas as pd
import matplotlib.pyplot as plt
# Assuming you have a dataframe named 'df' with columns: population, country, and continent
df = gapminder
# Step 1: Filter rows for Africa continent
africa_df = df[df['cont'] == 'Africa']
# Step 2: Extract population column for Africa
population_africa = africa_df['population']
# Step 3: Plot the histogram
plt.hist(population_africa, bins=10) # You can adjust the number of bins as needed
# Add labels and title
plt.xlabel('Population')
plt.ylabel('Frequency')
plt.title('Population of Countries in Africa')
# Display the histogram
plt.show()
gapminder.info()
import random
# Simulate 10 rolls
for _ in range(10):
# Roll two six-sided dice
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
# Calculate the sum
dice_sum = dice1 + dice2
# Check the sum and print the outcome
if dice_sum == 7 or dice_sum == 11:
print("A win!")
elif dice_sum == 2 or dice_sum == 3 or dice_sum == 12:
print("A loss!")
else:
print("Roll again!")