Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Challenge: Economic Indicator Correlation Heatmap | Advanced Economic Analysis and Visualization
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Python for Economists

bookChallenge: Economic Indicator Correlation Heatmap

In economic analysis, understanding the relationships between different indicators is crucial for drawing meaningful insights about countries' economic health and trends. Correlation analysis helps you measure the strength and direction of linear relationships between variables such as GDP, inflation, unemployment, and interest rates. A correlation matrix conveniently summarizes these relationships, and visualizing it as a heatmap provides an intuitive overview of the connections among multiple indicators.

To tackle this challenge, you will use a hardcoded pandas DataFrame containing economic data for several countries. Your goal is to write a function that computes the correlation matrix, visualizes it as a heatmap using seaborn, and identifies the strongest positive and negative correlations among the indicators.

1234567891011121314151617181920212223242526272829303132333435363738394041
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Hardcoded economic data for multiple countries data = { "Country": ["USA", "Germany", "Japan", "Canada", "UK"], "GDP": [21.4, 4.2, 5.1, 1.8, 2.7], # Trillions USD "Inflation": [1.8, 1.4, 0.5, 2.0, 1.7], # Percent "Unemployment": [3.7, 3.1, 2.4, 5.7, 4.0], # Percent "Interest Rate": [1.75, 0.0, -0.1, 1.75, 0.75] # Percent } df = pd.DataFrame(data) df.set_index("Country", inplace=True) def correlation_heatmap_and_extremes(df): # Compute the correlation matrix corr_matrix = df.corr() # Visualize the correlation matrix as a heatmap plt.figure(figsize=(8, 6)) sns.heatmap(corr_matrix, annot=True, cmap="coolwarm", center=0) plt.title("Correlation Heatmap of Economic Indicators") plt.show() # Find the strongest positive and negative correlations corr_pairs = corr_matrix.unstack() # Remove self-correlations corr_pairs = corr_pairs[corr_pairs.index.get_level_values(0) != corr_pairs.index.get_level_values(1)] # Drop duplicate pairs corr_pairs = corr_pairs.groupby([frozenset(pair) for pair in corr_pairs.index]).first() strongest_positive = corr_pairs.idxmax() strongest_negative = corr_pairs.idxmin() print(f"Strongest positive correlation: {tuple(strongest_positive)} = {corr_pairs.max():.2f}") print(f"Strongest negative correlation: {tuple(strongest_negative)} = {corr_pairs.min():.2f}") # Run the function correlation_heatmap_and_extremes(df)
copy

This approach lets you quickly spot which economic indicators move together and which tend to move in opposite directions. Positive correlations indicate that two variables tend to increase or decrease together, while negative correlations suggest that as one increases, the other decreases. Identifying the strongest relationships can guide further economic investigation or policy analysis.

Tarea

Swipe to start coding

Write a function named correlation_heatmap_and_extremes that:

  • Accepts a pandas DataFrame containing columns for GDP, Inflation, Unemployment, and Interest Rate.
  • Computes the correlation matrix for these columns.
  • Uses seaborn to display a heatmap of the correlation matrix with annotations.
  • Prints out the pair of indicators with the strongest positive correlation and the pair with the strongest negative correlation, including their correlation values.

Test your function on the DataFrame below:

CountryGDPInflationUnemploymentInterest Rate
USA21.41.83.71.75
Germany4.21.43.10.0
Japan5.10.52.4-0.1
Canada1.82.05.71.75
UK2.71.74.00.75
  • The heatmap should be displayed using seaborn.
  • The printed output should clearly state the indicator pairs and their correlation values.

Solución

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 3
single

single

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Suggested prompts:

Can you explain how the correlation values are interpreted in this context?

What do the strongest positive and negative correlations mean for these countries?

Can you help me modify the function to include more economic indicators?

close

bookChallenge: Economic Indicator Correlation Heatmap

Desliza para mostrar el menú

In economic analysis, understanding the relationships between different indicators is crucial for drawing meaningful insights about countries' economic health and trends. Correlation analysis helps you measure the strength and direction of linear relationships between variables such as GDP, inflation, unemployment, and interest rates. A correlation matrix conveniently summarizes these relationships, and visualizing it as a heatmap provides an intuitive overview of the connections among multiple indicators.

To tackle this challenge, you will use a hardcoded pandas DataFrame containing economic data for several countries. Your goal is to write a function that computes the correlation matrix, visualizes it as a heatmap using seaborn, and identifies the strongest positive and negative correlations among the indicators.

1234567891011121314151617181920212223242526272829303132333435363738394041
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Hardcoded economic data for multiple countries data = { "Country": ["USA", "Germany", "Japan", "Canada", "UK"], "GDP": [21.4, 4.2, 5.1, 1.8, 2.7], # Trillions USD "Inflation": [1.8, 1.4, 0.5, 2.0, 1.7], # Percent "Unemployment": [3.7, 3.1, 2.4, 5.7, 4.0], # Percent "Interest Rate": [1.75, 0.0, -0.1, 1.75, 0.75] # Percent } df = pd.DataFrame(data) df.set_index("Country", inplace=True) def correlation_heatmap_and_extremes(df): # Compute the correlation matrix corr_matrix = df.corr() # Visualize the correlation matrix as a heatmap plt.figure(figsize=(8, 6)) sns.heatmap(corr_matrix, annot=True, cmap="coolwarm", center=0) plt.title("Correlation Heatmap of Economic Indicators") plt.show() # Find the strongest positive and negative correlations corr_pairs = corr_matrix.unstack() # Remove self-correlations corr_pairs = corr_pairs[corr_pairs.index.get_level_values(0) != corr_pairs.index.get_level_values(1)] # Drop duplicate pairs corr_pairs = corr_pairs.groupby([frozenset(pair) for pair in corr_pairs.index]).first() strongest_positive = corr_pairs.idxmax() strongest_negative = corr_pairs.idxmin() print(f"Strongest positive correlation: {tuple(strongest_positive)} = {corr_pairs.max():.2f}") print(f"Strongest negative correlation: {tuple(strongest_negative)} = {corr_pairs.min():.2f}") # Run the function correlation_heatmap_and_extremes(df)
copy

This approach lets you quickly spot which economic indicators move together and which tend to move in opposite directions. Positive correlations indicate that two variables tend to increase or decrease together, while negative correlations suggest that as one increases, the other decreases. Identifying the strongest relationships can guide further economic investigation or policy analysis.

Tarea

Swipe to start coding

Write a function named correlation_heatmap_and_extremes that:

  • Accepts a pandas DataFrame containing columns for GDP, Inflation, Unemployment, and Interest Rate.
  • Computes the correlation matrix for these columns.
  • Uses seaborn to display a heatmap of the correlation matrix with annotations.
  • Prints out the pair of indicators with the strongest positive correlation and the pair with the strongest negative correlation, including their correlation values.

Test your function on the DataFrame below:

CountryGDPInflationUnemploymentInterest Rate
USA21.41.83.71.75
Germany4.21.43.10.0
Japan5.10.52.4-0.1
Canada1.82.05.71.75
UK2.71.74.00.75
  • The heatmap should be displayed using seaborn.
  • The printed output should clearly state the indicator pairs and their correlation values.

Solución

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 3
single

single

some-alt