0

i have a dataframe

df = pd.Dataframe ({"nam":["a", "b", "a", "b"],
                    "dat":["2022-01-01","2022-01-01","2022-01-01","2022-01-01"],
                    "tim": ['10:00:00', '10:00:00' , '11:00:00', '11:00:00'],
                     "va1":[1,2,3,4],
                     "val2":[11,22,33,44]}

)

and i want to convert it into without using pd.pivot_table as i cant see the results of pivot in debug mode in pycharm ( ref to pandas pivot_table : NoneType object is not callable ) and hence i cant progress with my code ahead in debug mode.

Hence looking for an alternate option of pd.pivot_table which can provide me this result.

     | nam |  dat        |  val1      |    val1     | val2       |    val2     | 
--------------------------------------------------------------------------------
tim  |     |             | '10:00:00' | '11:00:00'  | '10:00:00' | '11:00:00'  |
--------------------------------------------------------------------------------
 0   | "a" | "2022-01-01"|   1        |    3        |    11      |  33         |
--------------------------------------------------------------------------------
 1   | "b" | "2022-01-01"|   2        |    4        |    22      |  44         |
--------------------------------------------------------------------------------
Amit
  • 763
  • 1
  • 5
  • 14

1 Answers1

1

Here are alternatives - if no aggregation necessary:

df1 = df.pivot(index=['nam','dat'], columns='tim')
print (df1)
                    va1              val2         
tim            10:00:00 11:00:00 10:00:00 11:00:00
nam dat                                           
a   2022-01-01        1        3       11       33
b   2022-01-01        2        4       22       44


df1 = df.set_index(['nam','dat','tim']).unstack()
print (df1)
                    va1              val2         
tim            10:00:00 11:00:00 10:00:00 11:00:00
nam dat                                           
a   2022-01-01        1        3       11       33
b   2022-01-01        2        4       22       44

If need aggregate like pivot_table:

df2 = df.groupby(['nam','dat','tim']).mean().unstack()
print (df2)

                    va1              val2         
tim            10:00:00 11:00:00 10:00:00 11:00:00
nam dat                                           
a   2022-01-01        1        3       11       33
b   2022-01-01        2        4       22       44
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252