How to convert column values to columns in Pandas

In this article you learn how to convert column values to columns in Pandas Python library. You can use the pivot method in pandas to convert column values to columns. Here is an example:

Suppose you have a DataFrame df with the following columns: ‘date’, ‘category’, and ‘value’. The ‘category’ column has different categories like ‘A’, ‘B’, ‘C’, etc. and you want to convert the categories into columns.

import pandas as pd

df = pd.DataFrame({
'date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04'],
'category': ['A', 'B', 'C', 'A'],
'value': [10, 20, 30, 40]
})

To convert the ‘category’ column to columns, you can use the pivot method:

df_pivot = df.pivot(index='date', columns='category', values='value')

This will create a new DataFrame df_pivot where the ‘category’ values are now columns.

Note that the NaN values represent missing values for that category on that date. If you want to replace these NaN values with 0, you can use the fillna method:

df_pivot = df_pivot.fillna(0)

I printed the ouptut out to get this:

how to convert column values to columns

Leave a Reply