In Pandas, which method is used to pivot data from long to wide format, creating a new DataFrame?

melt()
reshape()
pivot()
groupby()

The correct answer is: A. melt()

The melt() method is used to pivot data from long to wide format, creating a new DataFrame. It takes a DataFrame as input and returns a new DataFrame with the columns of the original DataFrame as rows and the values of the original DataFrame as columns.

The reshape() method is used to reshape a DataFrame by changing the number of rows or columns. It takes a DataFrame as input and returns a new DataFrame with the same data but a different number of rows or columns.

The pivot() method is used to pivot a DataFrame by aggregating data across columns. It takes a DataFrame as input and returns a new DataFrame with the same data but with aggregated values across columns.

The groupby() method is used to group data by a column or columns. It takes a DataFrame as input and returns a new DataFrame with one row for each group and the values of the original DataFrame for each group.

Here is an example of how to use the melt() method to pivot data from long to wide format:

“`
import pandas as pd

df = pd.DataFrame({‘A’: [1, 2, 3], ‘B’: [4, 5, 6], ‘C’: [7, 8, 9]})

melted_df = df.melt(‘A’, var_name=’B’, value_name=’C’)

print(melted_df)

A B C
0 1 4
1 2 5
2 3 6
“`

As you can see, the melted_df DataFrame has one row for each unique value in the A column and one column for each value in the B column. The values in the C column are now stored in the columns of the melted_df DataFrame.

Exit mobile version