Ajay Chinni
Ajay Chinni

Reputation: 850

How to Convert the row unique values in to columns

I have this dataFrame

dd = pd.DataFrame({'a':[1,1,1,1,2,2,2,2],'feature':[10,10,20,20,10,10,20,20],'h':['h_30','h_60','h_30','h_60','h_30','h_60','h_30','h_60'],'count':[1,2,3,4,5,6,7,8]})


   a  feature     h  count
0  1       10  h_30      1
1  1       10  h_60      2
2  1       20  h_30      3
3  1       20  h_60      4
4  2       10  h_30      5
5  2       10  h_60      6
6  2       20  h_30      7
7  2       20  h_60      8

My expected output is I want to shift my h column unique values into column and use count numbers as values like this

   a  feature  h_30  h_60
0  1       10     1     2
1  1       20     3     4
2  2       10     5     6
3  2       20     7     8

I tried this but got an error saying ValueError: Length of passed values is 8, index implies 2

dd.pivot(index = ['a','feature'],columns ='h',values = 'count' )

enter image description here

Upvotes: 0

Views: 945

Answers (1)

Bruck1701
Bruck1701

Reputation: 329

df.pivot does not accept list of columns as index for versions below 1.1.0

Changed in version 1.1.0: Also accept list of index names.

Try this:

import pandas as pd

pd.pivot_table(
    dd, index=["a", "feature"], columns="h", values="count"
).reset_index().rename_axis(None, 1)

Upvotes: 1

Related Questions