Home > Mobile >  Transposing a dataframe by converting rows into multiple columns without any aggregate function
Transposing a dataframe by converting rows into multiple columns without any aggregate function

Time:06-10

Convert the following table:

Type s h
A 1 4
A 2 5
B 4 7
B 5 2

into this:

Type s_1 h_1 s_2 h_2
A 1 4 2 5
B 4 7 5 2

CodePudding user response:

In your case doing the cumcount with groupby get the key then we can pivot

out = df.assign(key = df.groupby('Type').cumcount() 1).pivot(index='Type',columns='key').sort_index(level=1,axis=1)
out.columns = out.columns.map('{0[0]}_{0[1]}'.format)
out = out.reset_index()
out
Out[581]: 
  Type  h_1  s_1  h_2  s_2
0    A    4    1    5    2
1    B    7    4    2    5

CodePudding user response:

df = df.groupby('Type').agg(list)
df[['s_1', 's_2']] = df.apply(lambda x: x['s'], axis=1, result_type='expand')
df[['h_1', 'h_2']] = df.apply(lambda x: x['h'], axis=1, result_type='expand')
df = df.drop(['s', 'h'], axis=1).reset_index()
print(df)

Output:

  Type  s_1  s_2  h_1  h_2
0    A    1    2    4    5
1    B    4    5    7    2
  • Related