0
0
Pandasdata~10 mins

Long to wide format conversion in Pandas - Interactive Code Practice

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

Complete the code to convert the DataFrame from long to wide format using pivot.

Pandas
wide_df = long_df.pivot(index='[1]', columns='variable', values='value')
Drag options to blanks, or click blank then click option'
Aid
Bvalue
Cvariable
Dindex
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'value' as index instead of 'id'.
Using 'variable' as index which is actually the column to spread.
2fill in blank
medium

Complete the code to reset the index of the wide DataFrame to turn the index back into a column.

Pandas
wide_df = wide_df.[1]()
Drag options to blanks, or click blank then click option'
Areset_index
Bset_index
Cdrop
Dmelt
Attempts:
3 left
💡 Hint
Common Mistakes
Using set_index() which does the opposite.
Using drop() which removes columns.
3fill in blank
hard

Fix the error in the code to pivot the DataFrame when there are duplicate entries for the index and columns combination.

Pandas
wide_df = long_df.pivot_table(index='id', columns='[1]', values='value', aggfunc='mean')
Drag options to blanks, or click blank then click option'
Aaggfunc
Bvariable
Cid
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'value' as columns which is incorrect.
Using 'id' as columns which is the index.
4fill in blank
hard

Fill both blanks to create a wide DataFrame with 'date' as index and 'category' as columns, aggregating values by sum.

Pandas
wide_df = df.pivot_table(index='[1]', columns='[2]', values='sales', aggfunc='sum')
Drag options to blanks, or click blank then click option'
Adate
Bcategory
Cregion
Dproduct
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping index and columns values.
Using columns that are not categorical.
5fill in blank
hard

Fill all three blanks to create a dictionary of average scores by student and subject from a long DataFrame.

Pandas
result = df.pivot_table(index='[1]', columns='[2]', values='[3]', aggfunc='mean').to_dict('index')
Drag options to blanks, or click blank then click option'
Astudent
Bsubject
Cscore
Dgrade
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'grade' instead of 'score' for values.
Mixing up student and subject keys.