What if you could turn a messy table into a neat timeline with just one command?
Why Wide to long format conversion in Pandas? - Purpose & Use Cases
Imagine you have a spreadsheet with sales data for each month in separate columns, like January, February, March, and so on. You want to analyze trends over time, but the data is spread wide across many columns.
Manually copying and rearranging each month's data into a single column is slow and boring. It's easy to make mistakes, like mixing up months or missing some data. This wastes time and causes frustration.
Wide to long format conversion automatically reshapes your data so that each row represents one observation per time period. This makes it easy to analyze trends, create charts, and apply statistical methods without manual errors.
january = df['Jan'] february = df['Feb'] # Repeat for each month # Then stack manually
df_long = df.melt(id_vars=['Store'], var_name='Month', value_name='Sales')
This lets you quickly transform messy wide tables into clean, tidy data ready for powerful analysis and visualization.
A store manager wants to compare monthly sales trends across different locations. Using wide to long conversion, they reshape the data to easily plot sales over time for each store.
Manual reshaping is slow and error-prone.
Wide to long conversion automates data restructuring.
It prepares data for easy analysis and visualization.
Practice
What does the pd.melt() function do in pandas?
Solution
Step 1: Understand the purpose of pd.melt()
Thepd.melt()function is designed to transform a DataFrame from wide format to long format by stacking multiple columns into fewer columns, making data easier to analyze.Step 2: Compare with other options
Sorting, filtering, and merging are different operations and not the purpose ofpd.melt().Final Answer:
It converts data from wide format to long format by stacking columns into rows. -> Option AQuick Check:
pd.melt() stacks columns into rows [OK]
- Confusing melt with sort or filter functions
- Thinking melt merges DataFrames
- Assuming melt changes row order only
Which of the following is the correct syntax to convert a DataFrame df from wide to long format keeping the column 'id' as identifier?
pd.melt(df, ?)
Solution
Step 1: Identify the parameter to keep identifier columns
Inpd.melt(), theid_varsparameter specifies columns to keep as identifiers and not unpivot.Step 2: Check other parameters
value_varsselects columns to unpivot,indexandcolumnsare not valid parameters forpd.melt().Final Answer:
id_vars='id' -> Option AQuick Check:
Use id_vars to keep identifier columns [OK]
- Using value_vars instead of id_vars to keep columns
- Trying to use index or columns parameters
- Not specifying id_vars and losing identifier columns
Given the DataFrame df:
id Jan Feb Mar 0 1 10 20 30 1 2 15 25 35
What is the output of:
pd.melt(df, id_vars='id', var_name='Month', value_name='Sales')
Solution
Step 1: Understand pd.melt() with id_vars and renaming
Theid_vars='id'keeps the 'id' column fixed. The other columns 'Jan', 'Feb', 'Mar' are unpivoted into two columns named 'Month' and 'Sales' as specified byvar_nameandvalue_name.Step 2: Calculate the resulting rows and columns
Each original row with 3 month columns becomes 3 rows, so total 2*3=6 rows. Columns are 'id', 'Month', 'Sales'.Final Answer:
A DataFrame with columns: id, Month, Sales and 6 rows stacking Jan, Feb, Mar values. -> Option BQuick Check:
melt stacks columns into rows with new names [OK]
- Expecting original wide format unchanged
- Dropping id column by mistake
- Thinking var_name/value_name cause errors
Consider this code snippet:
df = pd.DataFrame({
'id': [1, 2],
'A': [10, 20],
'B': [30, 40]
})
pd.melt(df, id_vars='id', value_vars=['A', 'B', 'X'], var_name='Variable')It raises an error. What is the likely cause?
Solution
Step 1: Verify columns in DataFrame
The DataFrame has columns 'id', 'A', 'B'. Thevalue_vars=['A', 'B', 'X']includes 'X' which does not exist, causing an error.Step 2: Check other options
id_vars='id'accepts string for single column.var_nameis valid. No duplicate columns.Final Answer:
Thevalue_varslist contains columns not in the DataFrame. -> Option CQuick Check:
value_vars must all exist in df.columns [OK]
- Specifying non-existent columns in value_vars
- Thinking id_vars must always be a list
- Confusing var_name as invalid parameter
You have a DataFrame df with columns ['Country', 'Year_2019', 'Year_2020', 'Year_2021'] representing sales data. You want to convert it to long format with columns ['Country', 'Year', 'Sales'] where the 'Year' column contains the year numbers (e.g., '2019') without the 'Year_' prefix. Which code snippet correctly performs this transformation?
Solution
Step 1: Use pd.melt() with id_vars and value_vars
We keep 'Country' fixed usingid_varsand specify the year columns invalue_varsto unpivot them.Step 2: Rename columns and clean year names
Usingvar_name='Year'andvalue_name='Sales'renames columns. Then, we remove the 'Year_' prefix from year values usingstr.replace()for clarity.Step 3: Compare options
pd.melt(df, id_vars='Country', var_name='Year', value_name='Sales') misses specifyingvalue_vars, so all columns except 'Country' are melted, which may be okay but less explicit. pd.melt(df, id_vars=['Country'], value_vars=['Year_2019', 'Year_2020', 'Year_2021'], var_name='Year', value_name='Sales') does not clean year names. pd.melt(df, id_vars='Country').rename(columns={'variable':'Year', 'value':'Sales'}) does not specifyvalue_varsand renames columns after melting but also misses cleaning year names.Final Answer:
pd.melt(df, id_vars='Country', value_vars=['Year_2019', 'Year_2020', 'Year_2021'], var_name='Year', value_name='Sales').assign(Year=lambda x: x['Year'].str.replace('Year_', '')) -> Option DQuick Check:
Specify value_vars and clean year names after melt [OK]
- Not specifying value_vars and melting unwanted columns
- Forgetting to clean year names after melt
- Renaming columns after melt without cleaning values
Ready to prove it?
Pass the test and this pattern moves unknown
