Realization of Pandas remodeling of stack and axial rotation of pivot

  • 2021-07-24 11:22:00
  • OfStack


import numpy as np
import pandas as pd
from pandas import Series,DataFrame

STEP 1 Reinvent

stack: Rotate the column index of data to the row index unstack: Rotate the row index of data to the column index

df = DataFrame({' Fruit ':[' Apple ',' Pear ',' Strawberries '],
        ' Quantity ':[3,4,5],
        ' Price ':[4,5,6]})
print(df)

Price quantity fruit
0 4 3 Apple
1 5 4 pears
2 6 5 Strawberries

1.stack()


stack_df = df.stack()
print(stack_df)

0 Price 4
Quantity 3
Fruit apple
1 price 5
Quantity 4
Fruit pear
2 Price 6
Quantity 5
Fruit strawberry

dtype: object

2.unstack()


print(stack_df.unstack())

Price quantity fruit
0 4 3 Apple
1 5 4 pears
2 6 5 Strawberries

3. Specify the level of rotation axis with the level parameter (default level=-1)


print(stack_df.unstack(level=0))

0 1 2
Price 4 5 6
Quantity 3 4 5
Fruit, apple, pear and strawberry

2. Axial rotation (pivot)

pivot (index, columns, values): Specify index as a row index, columns as a column index, and values as a value in DataFrame


df = DataFrame({' Fruit type ':[' Apple ',' Apple ',' Pear ',' Pear ',' Strawberries ',' Strawberries '],
        ' Information ':[' Price ',' Quantity ',' Price ',' Quantity ',' Price ',' Quantity '],
        ' Value ':[4,3,5,4,6,5]})
print(df)

Information value fruit type
0 price 4 apples
1 Quantity 3 Apples
2 price 5 pears
3 Quantity 4 Pears
4 Price 6 Strawberries
5 Quantity 5 Strawberries

Index fruit types as rows and information as columns


print(df.pivot(' Fruit type ',' Information ',' Value '))

Information price quantity
Fruit type
Pear 5 4
Apple 4 3
Strawberry 6 5

pivot can be implemented with set_index and unstack equivalents


print(df.set_index([' Fruit type ',' Information ']).unstack())

Value
Information price quantity
Fruit type
Pear 5 4
Apple 4 3
Strawberry 6 5


Related articles: