zoukankan      html  css  js  c++  java
  • (4)pandas 构建层次化索引

    步骤1、环境准备

    右击桌面上选择【Open in Terminal】 打开终端。
    在弹出的终端中输入【ipython】进入Python的解释器中,如图1所示。

    图1 ipython解释器

    步骤2、导入所需要的包

    导入实验常用的python包。如图2所示。
    【import pandas as pd】pandas用来做数据处理。
    【import numpy as np】numpy用来做高维度矩阵运算.
    【import matplotlib.pyplot as plt】matplotlib用来做数据可视化。

    图2 导入所需要的包

    步骤3、正式实验

    数据维度转换,如图3所示。
    【df = pd.Series(np.random.randn(10),index=[[‘a’,’a’,’a’,’b’,’b’,’b’,’c’,’c’,’d’,’d’], [‘1’,’2’,’3’,’1’,’2’,’3’,’1’,’2’,’2’,’3’]])】生成一个有多层索引数据
    【df】查看生成的数据
    【df.unstack()】将数据处理为高纬度数据
    【df.unstack().stack()】将高纬度处理为低纬度

    数据获取,如图4所示。
    【df】查看数据
    【df[‘a’]】以外层索引的方式获取数据
    【df[:,’2’]】以内层索引的方式获取数据

    图4 数据的获取

    DataFrame数据排序,如图5所示。
    【df2 = pd.DataFrame(np.random.randn(10,4),index=[[‘a’,’a’,’a’,’b’,’b’,’b’,’c’,’c’,’d’,’d’],[‘1’,’2’,’3’,’1’,’2’,’3’,’1’,’2’,’2’,’3’]],columns=[[‘A’,’A’,’B’,’B’],[‘1’,’2’,’1’,’2’]])】生成数据
    【df2.index.names=[‘key1’,’key2’]】对行索引指定名称
    【df2.columns.names=[‘value1’,’value2’]】对列索引指定名称
    【df2】查看生成的数据
    【df2.swaplevel(‘key1’,’key2’)】将两个索引互换位置
    【df2.sortlevel(0)】按key1列进行排序
    【df2.sum(level=’key1’)】将key1进行求和

    图5 数据排序2

  • 相关阅读:
    Running ASP.NET Applications in Debian and Ubuntu using XSP and Mono
    .net extjs 封装
    ext direct spring
    install ubuntu tweak on ubuntu lts 10.04,this software is created by zhouding
    redis cookbook
    aptana eclipse plugin install on sts
    ubuntu open folderpath on terminal
    ubuntu install pae for the 32bit system 4g limited issue
    EXT Designer 正式版延长使用脚本
    用 Vagrant 快速建立開發環境
  • 原文地址:https://www.cnblogs.com/creazylinux/p/7921960.html
Copyright © 2011-2022 走看看