Home > other >  converting rows to cols in pandas
converting rows to cols in pandas

Time:07-11

I want to convert rows into cols by using pandas package in python. I've tried using .pivot but i think that I did it uncoretly and I don't have good result. Here is my sample data and under sample is the result that i want:

list no  temp  some_info
1        1        X1        
2        1        X2
3        1        X3
4        1        X4
5        2        Y1
6        2        Y2
7        2        Y3
8        2        Y4
9        3        Z1
10       3        Z2
11       3        Z3
12       3        Z4

expecting result:

1   2   3
X1  Y1  Z1
X2  Y2  Z2
X3  Y3  Z3
X4  Y4  Z4

CodePudding user response:

You can try

df['list no'] = df.groupby('temp').cumcount()
out = df.pivot(index='list no', columns='temp', values='some_info')
print(out)

temp      1   2   3
list no
0        X1  Y1  Z1
1        X2  Y2  Z2
2        X3  Y3  Z3
3        X4  Y4  Z4

CodePudding user response:

Here is another solution. note that if the groups have different sizes it will not work.

pd.DataFrame(df.groupby('temp').groups).applymap(lambda x: df['some_info'].iloc[x])
  • Related