0

I have a pandas dataframe like this one:

name   category  count 
Tom      A         5
Tom      B         3
Tom      C         2
Eva      A        15
Eva      B        13
Eva      C        12

I want to transform it to this:

Name    Category_A     Category_B      Category_C
Tom         5             3                2
Eva        15            13               12

How can I do that?

mac13k
  • 2,423
  • 23
  • 34

2 Answers2

0

This should work:

import pandas as pd

result=pd.pivot_table(df, index='name', columns='category', values='count')
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
0

Try this:

df = df.pivot(columns=['category'], index='name')
df.columns = df.columns.get_level_values(1)
df.columns = ['category_'+i for i in df.columns]
df.reset_index(inplace=True)
print(df)

  name  category_A  category_B  category_C
0  Eva          15          13          12
1  Tom           5           3           2
NYC Coder
  • 7,424
  • 2
  • 11
  • 24