Meloun
Meloun

Reputation: 15049

how to transpose dataframe?

I've got a dataframe (result from groupby par "nr")

id  lap  nr  time
 1    1   2    10
 4    2   2   100

I need to rearrange this dataframe to folowing format

nr lap1 time1 lap2 time2
 2    1    10    2    100

Any Idea how can I do it?

Upvotes: 0

Views: 253

Answers (1)

unutbu
unutbu

Reputation: 879103

You can think of this as a pivot. If your DataFrame had an extra column called, say, colnum:

   lap  nr  time  colnum
0    1   2    10       1
1    2   2   100       2

then

df.pivot(index='nr', columns='colnum')

moves the nr column values into the row index, and the colnum column values into the column index:

       lap    time     
colnum   1  2    1    2
nr                     
2        1  2   10  100

This is basically the desired result. All we need to do is fix up the column labels:

df.columns = ['{}{}'.format(col, num) for col,num in df.columns]

Thus, import pandas as pd

df = pd.DataFrame({'id': [1, 4], 'lap': [1, 2], 'nr': [2, 2], 'time': [10, 100]})
df['colnum'] = df.groupby('nr').cumcount()+1
df = df[['lap','nr','time','colnum']]
df = df.pivot(index='nr', columns='colnum')
df.columns = ['{}{}'.format(col, num) for col,num in df.columns]
df = df.reset_index()

yields

   nr  lap1  lap2  time1  time2
0   2     1     2     10    100

Upvotes: 2

Related Questions