0

I'm trying to transform a data frame in the form:

Record  Value1 Value2 Value3
   0       1      2      3
   0       4      5      6
   0       7      8      9
   1       1      2      3
   1       4      5      6
   1       7      8      9
   2       1      2      3
   2       4      5      6
   2       7      8      9

To a wide format where row contains all related values like this:

Record  Value1_1 Value2_1 Value3_1 Value1_2 Value2_2 Value3_2 Value1_3 Value2_3 Value3_3
   0        1      2         3         4        5       6        7        8        9
   1        1      2         3         4        5       6        7        8        9
   2        1      2         3         4        5       6        7        8        9

I've been trying to use pivot, pivot_table and reindex, methods but I either get cryptic errors on "column value is not 1-dimensional" or other undescriptive errors.

Any clues on how to do that? Pivoting and multi-indexes are very complicated subjects and I still can't wrap my head around them :(

Thanks!

Daniel
  • 4,272
  • 8
  • 35
  • 48
  • 2
    use : `final=(df.assign(k=df.groupby('Record').cumcount()) .set_index(['Record','k']).unstack().sort_index(level=1,axis=1))` then`final.columns=[f'{a}_{b}' for a,b in final.columns]` – anky Nov 10 '19 at 17:31
  • 1
    @anky_91 works perfectly, thank you! :) But it looks super magic even despite I understand what's what those methods actually do. I went reading the manual until I'll understand it. – Daniel Nov 10 '19 at 17:57
  • 1
    try executing step by step (assigning each step in a variable) to understand better :) – anky Nov 10 '19 at 17:58

0 Answers0