Complete the code to reshape the DataFrame from wide to long format using pandas melt.
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)
The id_vars parameter specifies the column(s) to keep fixed. Here, 'Name' is the identifier column, so it should be passed to id_vars.
Complete the code to specify the variable name for the melted columns.
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)
The var_name parameter sets the name of the new column that holds the original column headers. Here, it should be 'Year' because the columns represent years.
Fix the error in the code to melt the DataFrame correctly.
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)
The value_name parameter should be the name of the column that will hold the values from the melted columns. Here, it should be 'Sales' to represent the sales numbers.
Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.
words = ['apple', 'bat', 'car', 'door'] lengths = { [1] : [2] for word in words if len(word) > 3 } print(lengths)
The dictionary comprehension keys should be the word itself, and the values should be the length of the word using len(word).
Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths only if length is greater than 3.
words = ['apple', 'bat', 'car', 'door'] lengths = { [1] : [2] for word in words if [3] } print(lengths)
The keys are uppercase words using word.upper(), the values are their lengths using len(word), and the condition filters words longer than 3 characters.