Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

This can be achieved using the pivot() function in pandas.

Here is an example:

Suppose you have a DataFrame df with the following data:

| | name | category | value | | - | -------- | -------- | ----- | | 0 | John | A | 10 | | 1 | John | B | 20 | | 2 | Mary | A | 5 | | 3 | Mary | B | 15 |

To transform the category column into column headers, you can use the following code:

pivoted = df.pivot(index='name', columns='category', values='value')

This will create a new DataFrame pivoted with the following data:

| category | A | B | | -------- | -- | -- | | name | | | | John | 10 | 20 | | Mary | 5 | 15 |

Now, the category column has become the column headers, with the name column as the index.

Note that if there are multiple values for the same combination of index and column labels, the pivot() function will aggregate them using a mean by default. You can specify a different aggregation function using the aggfunc parameter.