0
0
Data Analysis Pythondata~10 mins

Melt for wide-to-long reshaping in Data Analysis Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to reshape the DataFrame from wide to long format using pandas melt.

Data Analysis Python
import pandas as pd

df = pd.DataFrame({
    'Name': ['Alice', 'Bob'],
    'Math': [90, 80],
    'Science': [85, 88]
})

long_df = pd.melt(df, id_vars=[1], var_name='Subject', value_name='Score')
print(long_df)
Drag options to blanks, or click blank then click option'
A'Name'
B'Math'
C'Science'
D'Score'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a subject column like 'Math' or 'Science' as id_vars instead of 'Name'.
Passing the value column name to id_vars.
2fill in blank
medium

Complete the code to specify the variable name for the melted columns.

Data Analysis Python
import pandas as pd

df = pd.DataFrame({
    'City': ['NY', 'LA'],
    '2019': [100, 200],
    '2020': [110, 210]
})

long_df = pd.melt(df, id_vars='City', var_name=[1], value_name='Population')
print(long_df)
Drag options to blanks, or click blank then click option'
A'Year'
B'Population'
C'City'
D'Value'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the value column name as var_name.
Using the id_vars column name as var_name.
3fill in blank
hard

Fix the error in the code to melt the DataFrame correctly.

Data Analysis Python
import pandas as pd

df = pd.DataFrame({
    'Product': ['A', 'B'],
    'Q1': [10, 20],
    'Q2': [15, 25]
})

long_df = pd.melt(df, id_vars='Product', var_name='Quarter', value_name=[1])
print(long_df)
Drag options to blanks, or click blank then click option'
A'Quarter'
B'Sales'
C'Product'
D'Q1'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the var_name or id_vars as value_name.
Using a column name that does not represent the values.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.

Data Analysis Python
words = ['apple', 'bat', 'car', 'door']
lengths = { [1] : [2] for word in words if len(word) > 3 }
print(lengths)
Drag options to blanks, or click blank then click option'
Aword
Blen(word)
Cword.upper()
Dlen
Attempts:
3 left
💡 Hint
Common Mistakes
Using the length as key and word as value.
Using word.upper() instead of word as key.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths only if length is greater than 3.

Data Analysis Python
words = ['apple', 'bat', 'car', 'door']
lengths = { [1] : [2] for word in words if [3] }
print(lengths)
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
Clen(word) > 3
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Not converting words to uppercase for keys.
Using the wrong condition in the if clause.