• ndarray对象的方法


    数组的修剪和压缩

    1. clip方法返回一个修剪过的数组, 就是将所有比给定最大值还大的元素全部设为给定的最大值, 把所有比给定义最小值还小的元素全部设为给定的最小值

    import numpy as np
    
    a = np.arange(5)
    print(a)
    # [0 1 2 3 4]
    print(a.clip(1,2))
    # [1 1 2 2 2]

    2. compress方法返回一个根据给定条件筛选后的数组

    a = np.arange(4)
    print(a)
    # [0 1 2 3]
    print(a.compress(a > 2))
    # [3]

    阶乘

    1.prod()方法, 计算数组中所有元素的乘积

    import numpy as np
    
    b = np.arange(1, 9)
    print(b)
    # [1 2 3 4 5 6 7 8]
    print(b.prod())
    # 40320

    2.cumprod方法, 计算数组元素的累计乘积

    import numpy as np
    
    b = np.arange(1, 9)
    print(b)
    # [1 2 3 4 5 6 7 8]
    print(b.cumprod())
    # [    1     2     6    24   120   720  5040 40320]

    读写文件

    numpy的loadtxt()方法

    import numpy as np
    c = np.loadtxt('my.csv', delimiter=',', usecols=(6,), unpack=True)

    def datestr2num(s):
        '''将日期转换成数字'''
        s = s.decode("utf-8")
        return datetime.datetime.strptime(s,"%d-%m-%Y").date().weekday()

    # converters类似于lambda,可以将数据列和转换函数连接起来,输出转换后的数值列
    date, open_p, high, low, close = np.loadtxt('my.csv',delimiter=',', usecols=(1,2,3,4,5), 
        converters={1:datestr2num},unpack=True)

    参数             作用
    fname          被读取的文件名(文件的相对地址或者绝对地址)
    dtype           指定读取后数据的数据类型
    comments        跳过文件中指定参数开头的行(即不读取)
    delimiter           指定读取文件中数据的分割符
    converters        对读取的数据进行预处理
    skiprows           选择跳过的行数
    usecols          指定需要读取的列
    unpack          选择是否将数据进行向量输出
    encoding          对读取的文件进行预编码

    numpy的loadtxt()方法

    import numpy as np
    i2=np.eye(6)
    np.savetxt("eye.txt",i2)

    常用的统计函数

    min max median函数

    返回数组的最小值, 最大值和中位数, 中位数对于奇数是中间的, 对于偶数, 是中间两个数的平均值

    diff函数

    import numpy as np
    # 读取my.csv文件,逗号为分隔符,只读取4,7列,并返回两列,而不是一个元组
    h, l = np.loadtxt("my.csv", delimiter=',', usecols=(4,5), unpack=True)
    
    difference = np.diff(h)
    print(difference)
    # diff计算相邻数据的差,std是标准差,var是方差

    apply_along_axis函数

    numpy.apply_along_axis(funcaxisarr*args**kwargs):

    必选参数:func,axis,arr。

      其中func是我们自定义的一个函数,函数func(arr)中的arr是一个数组,函数的主要功能就是对数组里的每一个元素进行变换,得到目标的结果。

      其中axis表示函数func对数组arr作用的轴。

    可选参数:*args**kwargs。都是func()函数额外的参数。

    返回值:numpy.apply_along_axis()函数返回的是一个根据func()函数以及维度axis运算后得到的的数组.

    import numpy as np
    import datetime
    
    def datestr2num(s):
        '''将日期转换成数字'''
        s = s.decode("utf-8")
        return datetime.datetime.strptime 
        (s,"%d-%m-%Y").date().weekday()
        
    #ret = datestr2num("18-08-2019")
    #print(ret)
        
    # converters类似于lambda
    date, open_p, high, low, close = np.loadtxt('my.csv',delimiter=',', usecols=(1,2,3,4,5),  
        converters={1:datestr2num},unpack=True)
    # date:日期 open_p:开盘价 high:最高价 low:最低价 close:收盘价
    print("Dates =", date)
    
    averages = np.zeros(5)
    
    for i in range(5):
        indices = np.where(date == i)
        # np.take按照第二个参数索引去拿索引对应列中()第一个参数)的数字
        prices = np.take(close, indices)
        avg = np.mean(prices)  # 求平均值
        print("Day", i ,"price", prices, "Average", avg)
        averages[i] = avg
        
    top = np.max(averages)
    print("Hight average", top)
    print("Top dat of the week", np.argmax(averages))  # 返回最大值的索引
    bottom = np.min(averages)
    print("Lowest average",bottom)
    print("Bottom day of the week", np.argmin(averages))  # 返回最小值的索引
    
    close = close[:16]
    date = date[:16]
    # np.where会输出多维度的np.array
    first_monday = np.ravel(np.where(date == 0))[0]
    last_friday = np.ravel(np.where(date==4))[-1]
    
    weeks_indices = np.arange(first_monday, last_friday + 1)
    # 将一个np.arange切分成5个array
    weeks_indices = np.split(weeks_indices, 5)
    print(weeks_indices)
    # [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9]), array([10, 11, 12]), array([13, 14, 15])]
    
    
    def summarize(a,o,h,l,c):
        monday_open = o[a[0]]
        week_high = np.max(np.take(h,a))
        week_low = np.min(np.take(l,a))
        friday_close = c[a[-1]]
        return ("APPL", monday_open, week_high, week_low, friday_close)
    
    weekssummary = np.apply_along_axis(summarize,1,weeks_indices,open_p,high,low,close)
    
    
    np.savetxt("weeksummary.csv", weekssummary,delimiter=",", fmt="%s")

    linspace exp函数

    import numpy as np
    
    x = np.arange(5)
    
    # np.exp()函数
    print(np.exp(x))    # 生成e关于x的指数
    # [  1.      2.71828183   7.3890561   20.08553692  54.59815003]
    
    # np.linspace()函数
    print(np.linspace(-1, 0, 5))    # 注意:不是linespace
    # [-1.   -0.75 -0.5  -0.25  0.  ]
    # 生成从-1到0的数量为5的等差数列
    
    # 生成权重值
    N = 5
    weights = np.exp(np.linspace(-1, 0, N))
    # [ 0.36787944  0.47236655  0.60653066  0.77880078  1.        ]
  • 相关阅读:
    SpringBoot系列: Pebble模板引擎语法介绍
    SpringBoot系列: Pebble模板引擎
    SpringBoot系列: CommandLineRunner接口的用处
    SpringBoot系列: 设计Restful风格的API
    SpringBoot系列: 所有配置属性和官方文档
    Spring Security 之API 项目安全验证(基于basic-authentication)
    Spring Security 之方法级的安全管控
    SpringBoot系列: 使用 Swagger 生成 API 文档
    SpringBoot系列: Web应用鉴权思路
    SpringBoot系列: RestTemplate 快速入门
  • 原文地址:https://www.cnblogs.com/draven123/p/11386186.html
Copyright © 2020-2023  润新知