Pandas Pivot Table Using Data Index Data

I want to create a pivot table from the pandas framework using dataframe.pivot () and include not only the data columns, but also the data in the data index. Could not find any documents that show how to do this. Any tips?

+4
source share
1 answer

Use reset_indexto make an index a column:

In [45]: df = pd.DataFrame({'y': [0, 1, 2, 3, 4, 4], 'x': [1, 2, 2, 3, 1, 3]}, index=np.arange(6)*10)

In [46]: df
Out[46]: 
    x  y
0   1  0
10  2  1
20  2  2
30  3  3
40  1  4
50  3  4

In [47]: df.reset_index()
Out[47]: 
   index  x  y
0      0  1  0
1     10  2  1
2     20  2  2
3     30  3  3
4     40  1  4
5     50  3  4

So pivot uses the index as values:

In [48]: df.reset_index().pivot(index='y', columns='x')
Out[48]: 
   index        
x      1   2   3
y               
0      0 NaN NaN
1    NaN  10 NaN
2    NaN  20 NaN
3    NaN NaN  30
4     40 NaN  50    
+6
source

Source: https://habr.com/ru/post/1525934/


All Articles