0

I have a pandas dataframe that has values like this:

**id**   **type**    **attr**     **value**
1         type1       key1          val1
1         type1       key2          val2
2         type1       key1          val3
2         type1       key2          val4

And I want the output as

**id**   **type**    **key1**     **key2**
1          type1       val1         val2
2.         type1       val3         val4

I am trying to filter rows with same ids here like pick rows with same id and then create new columns as shown above.

I tried the following but getting DataError: No numeric types to aggregate

pd.pivot_table(df, values='value', index=['id', 'type'], columns='attr').reset_index()

UPDATE:

Solved the data error by the following modification:

df = pd.pivot_table(df, values='value', index=['id', 'type'], columns='attr', aggfunc='first')

But I am not able to understand the output that I am getting below. Why attr, 'key1' and key2 columns hover above than id and type?

attr      key1  key2
id type
1  type1  val1  val2
2  type1  val3  val4
Atihska
  • 4,803
  • 10
  • 56
  • 98
  • @Wen Please check my edits. – Atihska Oct 23 '18 at 19:35
  • 1
    `df = pd.pivot_table(df, values='value', index=['id', 'type'], columns='attr', aggfunc='first').reset_index()` – BENY Oct 23 '18 at 19:39
  • Thanks @Wen. this worked. – Atihska Oct 23 '18 at 19:51
  • The references that helped me besides @Wen's answer who told me the term as pivoting for my problem, were: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html and https://stackoverflow.com/questions/39229005/pivot-table-no-numeric-types-to-aggregate – Atihska Oct 23 '18 at 19:52

0 Answers0