Python--pandas--unstack() 与stack

2019-06-13  本文已影响0人  李小李的路

概述

入门级demo

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2019-06-12 23:48
# @Author  : LiYahui
# @Description :  stack demo
import pandas as pd
import numpy as np
from pandas import Series,DataFrame
data=DataFrame(np.arange(12).reshape((3,4)),index=pd.Index(['street1','street2','street3']),
               columns=pd.Index(['store1','store2','store3','store4']))
print('----------data--------')
print(data)
print('-------------data2----------------------------\n')
data2=data.stack()
data3=data2.unstack()
print(data2)
print('--------------data3---------------------------\n')
print(data3)

data4=data2.unstack(level=0)
print('-------data4----------')
print(data4)
data5=data2.unstack(level=-1) # 默认的level=-1,内层的索引
print('------data5--------')
print(data5)
'''
----------data--------
         store1  store2  store3  store4
street1       0       1       2       3
street2       4       5       6       7
street3       8       9      10      11
-------------data2----------------------------

street1  store1     0
         store2     1
         store3     2
         store4     3
street2  store1     4
         store2     5
         store3     6
         store4     7
street3  store1     8
         store2     9
         store3    10
         store4    11
dtype: int64
--------------data3---------------------------

         store1  store2  store3  store4
street1       0       1       2       3
street2       4       5       6       7
street3       8       9      10      11
-------data4----------
        street1  street2  street3
store1        0        4        8
store2        1        5        9
store3        2        6       10
store4        3        7       11
------data5--------
         store1  store2  store3  store4
street1       0       1       2       3
street2       4       5       6       7
street3       8       9      10      11
'''

data4=data2.unstack(level=0)
print(data4)
'''
        street1  street2  street3
store1        0        4        8
store2        1        5        9
store3        2        6       10
store4        3        7       11
'''

上一篇下一篇

猜你喜欢

热点阅读