03_11pandas_ Data Refactoring Stack

Source: Internet
Author: User
Import NumPy as NP
import pandas as PD
Stack

Rotate the row index to a column index and complete the hierarchy index.

In the following example, first create a box of 5x2 dataframe.

It is then stack, so the original row index becomes the outer index, and the original column index becomes an inner index.

Df_obj = PD. Dataframe (Np.random.randint (0,10, (5,2)), columns=[' data1 ', ' data2 '])
print Df_obj
   Data1  data2
0      9      0
1      7      4 2 6 1 3 2 7 4 9      1
Stacked = Df_obj.stack ()
print stacked
0  data1    9
   data2    0
1  data1    7
   data2    4
2  data1    6
   data2    1
3  data1    2
   data2    7
4  data1    9
   data2    1
Dtype:int64

The type of data after the refactoring was printed and found to have been transformed from Dataframe to series type.

Prints the type of index of the new data, discovering that the format of the indexes has become a multi-tiered index.

Print type (stacked)
print type (stacked.index)
<class ' pandas.core.series.Series ' >
<class ' pandas.indexes.multi.MultiIndex ' >
Unstack

Unstack the default series of multi-tier indexes into Dataframe, which by default is an internal index that is about to be converted to dataframe column indexes.

You can also specify the index level of the operation. Lavel=0 represents the Operation outer Index.

# Default Action inner-layer index
print stacked.unstack ()
   Data1  data2
0      9      0
1      7      4 2 6 1 3 2 7 4 9      1
# Specify the level of the action index through levels
print Stacked.unstack (level=0)
       0  1  2  3  4
data1  9 7 6 2 9
data2  0  4 1  7  1

Note: Some examples come from the Little Elephant College Robin course

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.