0

I'm referring to https://github.com/pandas-dev/pandas/tree/main/doc/cheatsheet.

enter image description here

As you can see, if I use pivot(), then all values are in row number 0 and 1.

But if I do use pivot(), the result was different like below.

DataFrame before pivot():

enter image description here

DataFrame after pivot():

enter image description here

Is the result on purpose?

tdy
  • 36,675
  • 19
  • 86
  • 83
SIMPLY
  • 15
  • 1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 19 '22 at 09:28

1 Answers1

1

In your data, the grey column (index of the row) is missing:

df = pd.DataFrame({'variable': list('aaabbbccc'), 'value': range(9)})
print(df)

# Output
  variable  value
0        a      0
1        a      1
2        a      2
3        b      3
4        b      4
5        b      5
6        c      6
7        c      7
8        c      8

Add the grey column:

df['grey'] = df.groupby('variable').cumcount()
print(df)

# Output
  variable  value  grey
0        a      0     0
1        a      1     1
2        a      2     2
3        b      3     0
4        b      4     1
5        b      5     2
6        c      6     0
7        c      7     1
8        c      8     2

Now you can pivot:

df = df.pivot('grey', 'variable', 'value')
print(df)

# Output
variable  a  b  c
grey             
0         0  3  6
1         1  4  7
2         2  5  8

Take the time to read How can I pivot a dataframe?

Corralien
  • 109,409
  • 8
  • 28
  • 52