Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Reshaping and transposing in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Reshaping Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of reshaping a NumPy array
What is the output of this code snippet that reshapes a NumPy array?
Data Analysis Python
import numpy as np
arr = np.arange(6)
reshaped = arr.reshape(2, 3)
print(reshaped)
A
[[0 1 2 3]
 [4 5 6 7]]
B
[[0 1]
 [2 3]
 [4 5]]
C
[[0 1 2]
 [3 4 5]]
D[0 1 2 3 4 5]
Attempts:
2 left
💡 Hint
Remember reshape changes the shape but keeps all elements in order.
❓ data_output
intermediate
2:00remaining
Result of pandas DataFrame transpose
Given this DataFrame, what is the result of transposing it?
Data Analysis Python
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
result = df.T
print(result)
A
   0  1
A  1  2
B  3  4
B
   A  B
0  1  3
1  2  4
C
   1  2
A  0  1
B  3  4
D
   0  1
A  3  4
B  1  2
Attempts:
2 left
💡 Hint
Transpose swaps rows and columns.
🔧 Debug
advanced
2:00remaining
Identify the error in reshaping a pandas DataFrame
What error does this code raise and why? import pandas as pd df = pd.DataFrame({'X': [1, 2, 3], 'Y': [4, 5, 6]}) df_reshaped = df.values.reshape(2, 4)
Data Analysis Python
import pandas as pd
df = pd.DataFrame({'X': [1, 2, 3], 'Y': [4, 5, 6]})
df_reshaped = df.values.reshape(2, 4)
ANo error, reshaping works fine
BTypeError: 'DataFrame' object is not callable
CAttributeError: 'DataFrame' object has no attribute 'values'
DValueError: cannot reshape array of size 6 into shape (2,4)
Attempts:
2 left
💡 Hint
Check if the total number of elements matches the new shape.
❓ visualization
advanced
2:30remaining
Visualize the effect of pivoting a DataFrame
What does the pivot operation produce from this DataFrame? import pandas as pd df = pd.DataFrame({ 'Date': ['2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02'], 'City': ['NY', 'LA', 'NY', 'LA'], 'Temperature': [30, 60, 28, 65] }) pivoted = df.pivot(index='Date', columns='City', values='Temperature') print(pivoted)
Data Analysis Python
import pandas as pd
df = pd.DataFrame({
  'Date': ['2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02'],
  'City': ['NY', 'LA', 'NY', 'LA'],
  'Temperature': [30, 60, 28, 65]
})
pivoted = df.pivot(index='Date', columns='City', values='Temperature')
print(pivoted)
A
Date        LA  NY
City               
2023-01-01  30  60
2023-01-02  28  65
B
City        LA  NY
Date               
2023-01-01  60  30
2023-01-02  65  28
C
City        NY  LA
Date               
2023-01-01  30  60
2023-01-02  28  65
D
Date        NY  LA
City               
2023-01-01  60  30
2023-01-02  65  28
Attempts:
2 left
💡 Hint
Pivot uses the index and columns parameters to rearrange data.
🚀 Application
expert
3:00remaining
Transform and summarize data with melt and groupby
Given this DataFrame, which option correctly melts it and then groups by 'variable' to find the mean value? import pandas as pd df = pd.DataFrame({ 'ID': [1, 2], 'Math': [90, 80], 'Science': [85, 95] }) melted = pd.melt(df, id_vars=['ID'], value_vars=['Math', 'Science']) result = melted.groupby('variable')['value'].mean() print(result)
Data Analysis Python
import pandas as pd
df = pd.DataFrame({
  'ID': [1, 2],
  'Math': [90, 80],
  'Science': [85, 95]
})
melted = pd.melt(df, id_vars=['ID'], value_vars=['Math', 'Science'])
result = melted.groupby('variable')['value'].mean()
print(result)
A
Math       85.0
Science    90.0
Name: value, dtype: float64
B
ID
1    87.5
2    87.5
Name: value, dtype: float64
C
Math       90
Science    95
Name: value, dtype: int64
D
variable
Math       85
Science    90
Name: value, dtype: int64
Attempts:
2 left
💡 Hint
Melt converts columns to rows, then groupby calculates mean per variable.

Practice

(1/5)
1. What does the transpose() function do to a DataFrame in pandas?
easy
A. It swaps the rows and columns of the DataFrame.
B. It sorts the DataFrame by index.
C. It removes duplicate rows from the DataFrame.
D. It fills missing values with zeros.

Solution

  1. Step 1: Understand transpose operation

    The transpose() function flips the DataFrame so rows become columns and columns become rows.
  2. Step 2: Compare with other options

    Sorting, removing duplicates, or filling missing values are different operations not related to transposing.
  3. Final Answer:

    It swaps the rows and columns of the DataFrame. -> Option A
  4. Quick Check:

    transpose() = swap rows and columns [OK]
Hint: Remember transpose flips rows and columns [OK]
Common Mistakes:
  • Confusing transpose with sorting
  • Thinking transpose removes duplicates
  • Assuming transpose fills missing values
2. Which of the following is the correct syntax to reshape a DataFrame df from wide to long format using pandas?
easy
A. df.melt(id_vars=['id'], var_name='variable', value_name='value')
B. df.stack(level=0)
C. df.transpose()
D. df.pivot(index='id', columns='variable', values='value')

Solution

  1. Step 1: Identify function for wide to long

    The melt() function converts wide format to long format by unpivoting columns.
  2. Step 2: Check syntax correctness

    df.melt(id_vars=['id'], var_name='variable', value_name='value') is the correct syntax to keep 'id' fixed and melt other columns.
  3. Final Answer:

    df.melt(id_vars=['id'], var_name='variable', value_name='value') -> Option A
  4. Quick Check:

    melt() = wide to long reshape [OK]
Hint: Use melt() to go from wide to long format [OK]
Common Mistakes:
  • Using pivot() instead of melt() for wide to long
  • Confusing transpose() with reshaping
  • Using stack() without understanding its effect
3. Given the DataFrame df below:
import pandas as pd
df = pd.DataFrame({
  'A': [1, 2],
  'B': [3, 4]
})

What is the output of df.T?
medium
A. An error because T is not a valid attribute.
B. A DataFrame sorted by column 'A'.
C. A DataFrame with rows and columns swapped, showing columns as rows.
D. A DataFrame with duplicated rows removed.

Solution

  1. Step 1: Understand df.T usage

    T is a shortcut for transpose() in pandas, swapping rows and columns.
  2. Step 2: Visualize the transposed DataFrame

    Original df has columns 'A' and 'B' with 2 rows. After transpose, columns become rows and rows become columns.
  3. Final Answer:

    A DataFrame with rows and columns swapped, showing columns as rows. -> Option C
  4. Quick Check:

    df.T = transpose DataFrame [OK]
Hint: Use df.T to quickly transpose DataFrame [OK]
Common Mistakes:
  • Thinking df.T sorts data
  • Believing df.T removes duplicates
  • Assuming df.T causes error
4. What is wrong with this code snippet that tries to reshape a DataFrame df using pivot()?
df.pivot(index='id', columns='variable')
medium
A. Pivot cannot be used on DataFrames with numeric columns.
B. Missing the values parameter required for pivot.
C. The index parameter should be a list, not a string.
D. The columns parameter should be omitted.

Solution

  1. Step 1: Check pivot() required parameters

    The pivot() function needs index, columns, and values to reshape data properly.
  2. Step 2: Identify missing argument

    The code misses the values argument, which tells pivot what data to fill in the new table.
  3. Final Answer:

    Missing the values parameter required for pivot. -> Option B
  4. Quick Check:

    pivot() needs values parameter [OK]
Hint: Always include values= when using pivot() [OK]
Common Mistakes:
  • Forgetting values parameter in pivot()
  • Using string instead of list for index incorrectly
  • Thinking pivot() can't handle numeric columns
5. You have a DataFrame df with columns ['id', 'year', 'sales_Q1', 'sales_Q2']. You want to reshape it to a long format with columns ['id', 'year', 'quarter', 'sales']. Which code correctly achieves this?
hard
A. df.stack(level=['quarter', 'sales'])
B. df.pivot(index=['id', 'year'], columns='quarter', values='sales')
C. df.transpose()
D. df.melt(id_vars=['id', 'year'], var_name='quarter', value_name='sales')

Solution

  1. Step 1: Identify wide to long reshape method

    To convert columns like 'sales_Q1', 'sales_Q2' into rows, use melt().
  2. Step 2: Use melt() with correct parameters

    Keep 'id' and 'year' fixed with id_vars, set var_name='quarter' and value_name='sales' to rename columns.
  3. Step 3: Check other options

    pivot() is for long to wide, transpose() swaps rows and columns, stack() is for multi-index reshaping but not here.
  4. Final Answer:

    df.melt(id_vars=['id', 'year'], var_name='quarter', value_name='sales') -> Option D
  5. Quick Check:

    melt() with id_vars = long format reshape [OK]
Hint: Use melt() with id_vars to reshape wide to long [OK]
Common Mistakes:
  • Using pivot() instead of melt() for wide to long
  • Trying transpose() for reshaping columns
  • Misusing stack() without multi-index
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard