zoukankan      html  css  js  c++  java
  • Python的Numpy库简述

    numpy 是 python 的科学计算库
    import numpy as np

    1、使用numpy读取txt文件

    # dtype = "str":指定数据格式
    # delimiter = "	":指定分割符
    # skip_header = 1:跳过第一行
    npinfo = np.genfromtxt("titanic_train.txt", delimiter = "	", dtype = "U75", skip_header = 1)

    2、ayyay数组,数据类型是必须相同。

    vector = np.array([5, 10, 15, 20])
    matrix = np.array([[5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60]])
    print(vector)
    print(matrix)

    3、numpy的数据类型,一般用到四种数据类型 bool、 int32/64、 float32/64、 string

    print(vector.dtype)
    print(matrix.dtype)

    4、获取第1行的第4个数

    npinfo[0, 3]
    # 取1-3行和1-3列数据
    npinfo[0: 3, 0: 3]
    # 如果:省略前后数字表示所有数据
    npinfo[:, :]

    5、判断array中元素的值

    vector == 10
    matrix[:, 0] == 25

    6、取出等于10的元素

    token = (vector == 10)
    vector[token]

    7、取出有25的这一行

    token_25 = (matrix[:, 0] == 25)
    matrix[token_25]

    8、string 转 float 类型

    vector = np.array(["10", "20", "30", "40"])
    vector = vector.astype(float)
    print(vector)

    9、基本运算

    vector.sum()    # 求和
    vector.mean()    # 均值
    matrix.sum(axis = 0)    # 按列求和
    matrix.sum(axis = 1)    # 按行求和

    10、缺失值填补

    nan_4 = np.isnan(npinfo[:, 4])
    npinfo[nan_4, 4] = 0    # 缺失值填补,对有缺失值的第4列填补0

    11、使用 numpy 创建数组和矩阵

    # 创建一个3行5列的矩阵
    a = np.arange(15).reshape(3, 5)
    print(a)

    12、查看当前数组是几维的

    a.ndim

    13、其它查看

    a.dtype
    a.size

    14、创建一个空矩阵

    np.zeros((3, 4))

    15、创建一个1矩阵 3维

    np.ones((3, 4, 5), dtype = np.int32)

    16、创建有步长的矩阵:np.arange( 起始,结束,步长 )

    np.arange( 10, 15, 1 )

    17、随机初始化矩阵

    np.random.random((3, 4))

    18、创建一个指定数量的矩阵

    # np.linspace( 起始,结束,数量 )
    from numpy import pi
    np.linspace( 0, 2*pi, 100 )

    19、求正弦

    np.sin(np.linspace( 0, 2*pi, 100 ))

    20、数组计算

    a = np.array([10, 15, 20, 25])
    b = np.arange(4)
    
    a - b
    b ** 2 #注意:这个是n次方,不是乘法。
    a < 20

    21、# 求内积 外积

    A = np.array( [[1, 2], 
    [0, 3]] )
    B = np.array( [[2, 0], 
    [3, 4]] )
    
    # 内积 对应位置相乘
    A * B
    
    # 矩阵相乘
    A.dot(B)
    np.dot(A, B)
    # 矩阵相乘 原理
    #A=
    #a b c 
    #d e f 
    #g h i
    
    #B=
    #A D 
    #B E 
    #C F
    
    #A.dot(B)=
    #aA+bB+cC aD+bE+cF
    #dA+eB+fC dD+eE+fF
    #gA+hB+iC gD+hE+iF

    22、e的x次幂

    A = np.arange(3)
    np.exp(A)

    23、开根号

    np.sqrt(A)

    24、向下取整

    C = np.floor(10*np.random.random((3, 4)))

    25、转化为行向量

    C.ravel()

    26、重新shape,如:由3行4列转为2行6列

    C.shape = (2, 6)

    27、行列转置

    C.T

    28、其它reshape方法

    C.resize((2, 6))
    C.reshape(3, -1)

    29、矩阵拼接

    x = np.floor(10*np.random.random((3, 4)))
    y = np.floor(10*np.random.random((3, 4)))
    
    # 按行拼接
    np.vstack((x, y))
    # 按列拼接
    np.hstack((x, y))

    30、矩阵切分

    x = np.floor(10*np.random.random((3, 12)))
    # 按列切成3份
    np.hsplit(x, 3)
    # 如果想切两刀怎么办?
    np.hsplit(x, (3, 5))
    
    y = np.floor(10*np.random.random((12, 2)))
    # 按行切分
    np.vsplit(y, 3)

    31、矩阵相互赋值问题

    z = np.arange(12)
    
    t = z     # 共享内存
    t is z    # 结果是True
    # print(id(t)) 和 print(id(z)) 的结果是一样的。
    
    t1 = z.view() #共享数据,但不共享内存
    t1 is z       # 结果是False
    # print(id(t)) 和 print(id(z)) 的结果是不同的。
    
    t2 = z.copy() #完全是两个对象

    32、排序和索引

    data = np.sin(np.arange(20).reshape(5, 4))
    # 找最大值
    ind = data.argmax(axis = 0)    # 最大值的索引
    data_max = data[ind, np.arange(data.shape[1])]
    print(data_max)
    
    不过有最函数:data.max(axis = 0)

    33、# 排序

    sx = np.floor(10*np.random.random((3, 4)))
    print(np.sort(sx, axis = 0))    # 按列排序
    print(np.sort(sx, axis = 1))    # 按行排序
    也可以这么写:sx.sort(axis = 1)

    34、复制 tile

    a = np.arange(0, 40, 10)
    print(a)
    # 将a的行复制2倍,列复制3倍
    b = np.tile(a, (2, 3))
    print(b)

    35、8*8棋盘矩阵,其中1、3、5、7行和0、2、4、6列的元素置为1;1 ,3,5,7列和0,2,4,6行也是1

    z = np.zeros((8,8), dtype = int)
    z[1::2,::2] = 1    # 注意:双冒号的用法
    z[::2,1::2] = 1
    print(z)

    36、多赋值方法

    z = np.random.random((10,10))
    zmin, zmax = z.min(), z.max()

    37、归一化,将矩阵规格化到0~1,即最小的变成0,最大的变成1,最小与最大之间的等比缩放

    z = 10*np.random.random((5,5))
    zmin, zmax = z.min(), z.max()
    z = (z-zmin)/(zmax-zmin) #归一化公式
    print(z)

    38、矩阵相加

    z = np.zeros((5,5))
    z += np.arange(5)
    print(z)

    39、生成0~10之间均匀分布的11个数,包括0和10

    z = np.linspace(0, 10, 11, endpoint=True, retstep=True)
    print(z)

    40、交换矩阵的其中两行

    a = np.arange(25).reshape(5,5)
    a[[0,1]] = a[[1,0]]
    print(a)

    41、找出数组中与给定值最接近的数

    z = np.array([[0,1,2,3],[4,5,6,7]])
    a = 5.1
    print(np.abs(z-a).argmin())

    42、判断二维矩阵中有没有一整列数为0?

    z = np.random.randint(0,3,(2,10))
    print(z.any(axis = 0))

    43、生成二维的高斯矩阵

    x,y = np.meshgrid(np.linspace(-1,1,10),np.linspace(-1,1,10))
    D = np.sqrt(x**2 + y**2)
    sigma, mu = 1, 0
    a = np.exp(-(D-mu)**2 / (2*sigma**2))
    print(a)
  • 相关阅读:
    HDU 5583 Kingdom of Black and White 水题
    HDU 5578 Friendship of Frog 水题
    Codeforces Round #190 (Div. 2) E. Ciel the Commander 点分治
    hdu 5594 ZYB's Prime 最大流
    hdu 5593 ZYB's Tree 树形dp
    hdu 5592 ZYB's Game 树状数组
    hdu 5591 ZYB's Game 博弈论
    HDU 5590 ZYB's Biology 水题
    cdoj 1256 昊昊爱运动 预处理/前缀和
    cdoj 1255 斓少摘苹果 贪心
  • 原文地址:https://www.cnblogs.com/hunttown/p/7089870.html
Copyright © 2011-2022 走看看