1

I want transform column data to rows like this,how could I perform this?programming language is python

original data:

    data    month   user_id
0   3782.0  01      1
1   1882.0  02      1
2   536.0   03      2
3   526.0   04      2

transformed data:

user_id mo_1 mo_2 mo_3 mo_4
1       3782 1882 
2                 536  526

original data definition:

df = pd.DataFrame({'user_id': {0: 1, 1: 1, 2: 1, 3: 1},
                   'month': {0: '01', 1: '02', 2: '03', 3: '04'},
                  'data': {0: 3782., 1: 1882., 2: 536., 3: 526.},})
F.bob
  • 105
  • 1
  • 5

2 Answers2

0

As per this answer here you need to use transpose by T.

print (df.set_index('fruits').T)
fruits     apples  grapes  figs
numFruits      10      20    15
kopo222
  • 119
  • 11
0

To change row values to column headers, you need to use unstack

df.set_index(['user_id', 'month'], inplace=True)
df = df.unstack()

           data                      
month        01      02     03     04
user_id                              
1        3782.0  1882.0  536.0  526.0
Riley Hun
  • 2,541
  • 5
  • 31
  • 77