Homesand
Homesand

Reputation: 423

How to convert rows' values into columns

I have a DataFrame:

  ID      Location       Value        Count
  1              X           6           13
  1              X           5           10

I want to convert two value in rows value into column name with the corresponding count like:

  ID      Location           6            5 
  1              X          13           10

Upvotes: 1

Views: 92

Answers (1)

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Use pd.pivot_table:

df1 = df.pivot_table(values=['Count'], index=['ID', 'Location'], columns=['Value'])

Output

            Count
Value           5   6
ID Location
1  X           10  13

You can reset_index() to bring it to the OP's expected output shape -

df1.reset_index()

      ID Location Count
Value                 5   6
0      1        X    10  13

Upvotes: 1

Related Questions