1

I have something like this:

Values     Time
  22        0
  45        1
  65        2
  78        0
  12        1
  45        2

and I want this:

Time    0    1    2 
Val1    22   45   65
Val2    78   12   45

How can I do it?

HugoB
  • 121
  • 7

3 Answers3

4

This is pivot creating the index with cumcount

df['idx'] = 'Val' + (df.groupby('Time').cumcount()+1).astype(str)
df.pivot(index='idx', columns='Time', values='Values').rename_axis(None)

Output:

Time   0   1   2
Val1  22  45  65
Val2  78  12  45
ALollz
  • 57,915
  • 7
  • 66
  • 89
  • 1
    @HugoB Yes, pivot is very useful. https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe is a very informative post, though it does not cover the index creation step, required to solve your question fully. – ALollz May 26 '19 at 22:06
  • Thanks a lot! I'll use it for sure! So kind! – HugoB May 27 '19 at 21:08
1

You need to transpose your array/matrix.

Use

list(map(list, zip(*l)))

where list is your list

Marta
  • 37
  • 10
1

If your time-delta is constant, ordered and has no missing values:

DELTA = 3
new_values = [df['Values'].iloc[i*DELTA:i*DELTA+DELTA].values.transpose() for i in range(int(len(df)/DELTA))]
df_new = pd.DataFrame(new_values , index=['Val'+str(i+1) for i in range(len(new_values ))])

print(df_new)
         0   1   2
Val1    22  45  65
Val2    78  12  45

Not a pretty solution, but maybe it helps. :-)

ilja
  • 2,592
  • 2
  • 16
  • 23