zoukankan      html  css  js  c++  java
  • dateframe 基本操作和运算

    # hanbb
    # come on!!!
    import pandas as pd
    import numpy as np
    df = pd.DataFrame(np.arange(12).reshape(4,3),index=['a','b','c','d'],columns=['1st','2nd','3rd'])
    print(df)
    # 取值
    print(df.values)
    print(df.index)
    print(df.columns)
    
    print(df['1st'])          # 取出列数据,
    print(df.ix['a'])         # 取出行数据
    print(df['3rd']['d'])     # 取出一个数据
    
    # 改变索引,重新索引
    df.reindex(columns=['3rd','2nd','1st'])
    print(df)
    # 新增
    #
    newc = df.columns.insert(4,'4or')             # 增加新的一列 指定列索引,指定自定义索引
    newd = df.reindex(columns=newc,fill_value=20) # 填充固定值
    print(newd)
    #
    newi = df.index.insert(5,'e')
    newd1= df.reindex(index=newi,fill_value=30)
    print(newd1)
    
    # 删除
    newc2= df.columns.delete(2)                # 核心是基于行列索引来操作数据
    newd3= df.reindex(columns=newc2)
    print(newd3)
    
    # drop 直接删除 行和列
    print(df.drop('c'))          # 默认是行
    print(df.drop('2nd',axis=1)) # 改为1,即为列

    更新行列数据的提取:

    import pandas as pd
    
    # 数据的导入
    data = pd.read_table("E:\python\part 2\017\TRD_Index.txt",sep='	')  # 注意分隔符
    print(data.tail())
    
    # 获取 行标签 相同的数据
    sh_data=data[data.Indexcd==1]
    print(sh_data["Retindex"].tail())    # 这两个格式效果一致的
    print(sh_data.Retindex.tail())
    # 多列
    sh_data_2=data[data['Indexcd']<=2] # 取出列标签 Indexcd 小于等于2的数据
    # 获取列数据
    print(data["Indexcd"].tail())        # 这两个格式效果一致的
    print(data.Indexcd.tail())
    # 获取两列数据
    print(data[['Indexcd','Trddt']]) # 注意符号

     2.基本运算

    import pandas as pd
    import numpy as np
    df1 = pd.DataFrame(np.arange(12).reshape(4,3),index=['a','b','c','d'],columns=['1st','2nd','3rd'])
    df2 = pd.DataFrame(np.arange(16).reshape(4,4),index=['a','b','c','d'],columns=['1st','2nd','3rd','4or'])
    
    # 直接符号运算
    print(df1+df2)
    print(df1-df2)
    print(df1*df2)
    
    # 可以填充值的加减乘除
    print(df1.add(df2,fill_value=20))
    print(df1.sub(df2,fill_value=20))
    print(df1.mul(df2,fill_value=20))
    print(df1.div(df2,fill_value=20))
    
    # 比较运算,必须是相同维度的比较
    print(df2['1st']>df1['1st'])
  • 相关阅读:
    C#中Socket多线程编程实例
    VBA之Range对象在Excel单元格赋值示例
    c# 怎么关闭Excel
    C#结构体定义的详解
    asp.net C#调用mencoder处理视频的方法
    Win7系统找回“显示桌面”按钮,Win7系统将显示桌面添加到开始按钮旁
    使用 Visual Studio .NET 客户端执行自动化功能后不退出 Office 应用程序
    c#操作excel后关闭excel.exe的方法
    asp文件的连接11种方法
    Excel对象模型的一些使用心得(C#)
  • 原文地址:https://www.cnblogs.com/hanbb/p/7860226.html
Copyright © 2011-2022 走看看