Numpy

numpy 和 pandas 是科学运算当中最为重要的两个模块,任何关于数据分析的模块都少不了它们两个。它们具有两个优势:

1、运算速度快:numpy 和 pandas 都是采用 C 语言编写, pandas 又是基于 numpy, 是 numpy 的升级版本

2、消耗资源少:采用的是矩阵运算,会比 python 自带的字典或者列表快好多

Numpy

1、Numpy 属性

1) ndim:维度

2) shape:行数和列数

3) size:元素个数

import numpy as np #为了方便使用numpy 采用np简写
#列表转化为矩阵
array = np.array([[1, 2, 3], [2, 3, 4]])
print(array)
# number of dim: 2
print('number of dim:', array.ndim)
# shape : (2, 3)
print('shape :', array.shape)
# size: 6
print('size:', array.size)

2、创建 array 有很多形式

1) array:创建数组

2) dtype:指定数据类型

3) zeros:创建数据全为0

4) ones:创建数据全为1

5) empty:创建数据接近0

6) arrange:按指定范围创建数据

7) linspace:创建线段

a = np.array([2, 23, 4]) 
# [2 23 4]
print(a)
a = np.array([2, 23, 4], dtype = np.int)
# int 64
print(a.dtype)
a = np.array([2, 23, 4], dtype = np.int32)
# int32
print(a.dtype)
a = np.array([2, 23, 4], dtype = np.float)
# float64
print(a.dtype)
a = np.array([2, 23, 4], dtype = np.float32)
# float32
print(a.dtype)
"""
[[ 2 23  4]
 [ 2 32  4]]
"""
a = np.array([[2, 23, 4], [2, 32, 4]])  # 2d 矩阵 2行3列
"""
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
"""
a = np.zeros((3, 4)) # 数据全为0,3行4列
"""
array([[1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]])
"""
a = np.ones((3, 4), dtype = np.int)   # 数据为1,3行4列
"""
array([[  0.00000000e+000,   4.94065646e-324,   9.88131292e-324,
          1.48219694e-323],
       [  1.97626258e-323,   2.47032823e-323,   2.96439388e-323,
          3.45845952e-323],
       [  3.95252517e-323,   4.44659081e-323,   4.94065646e-323,
          5.43472210e-323]])
"""
a = np.empty((3, 4)) # 数据为empty,3行4列
"""
array([10, 12, 14, 16, 18])
"""
a = np.arange(10, 20, 2) # 10-19 的数据,2步长
"""
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
"""
a = np.arange(12).reshape((3, 4))    # 3行4列,0到11
"""
array([  1.        ,   1.47368421,   1.94736842,   2.42105263,
         2.89473684,   3.36842105,   3.84210526,   4.31578947,
         4.78947368,   5.26315789,   5.73684211,   6.21052632,
         6.68421053,   7.15789474,   7.63157895,   8.10526316,
         8.57894737,   9.05263158,   9.52631579,  10.        ])
"""
a = np.linspace(1, 10, 20)    # 开始端1,结束端10,且分割成20个数据,生成线段
"""
array([[  1.        ,   1.47368421,   1.94736842,   2.42105263],
       [  2.89473684,   3.36842105,   3.84210526,   4.31578947],
       [  4.78947368,   5.26315789,   5.73684211,   6.21052632],
       [  6.68421053,   7.15789474,   7.63157895,   8.10526316],
       [  8.57894737,   9.05263158,   9.52631579,  10.        ]])
"""
a = np.linspace(1, 10, 20).reshape((5, 4)) # 更改shape

3、基础运算

1) 一维矩阵(注意:a 和 b 是两个属性为 array 也就是矩阵的变量,而且二者都是 1 行 4 列的矩阵)

a = array([10,  20,  30,  40])
b = array([0,  1,  2,  3])
# 减法结果 array([10, 19, 28, 37])
c = a - b
# 加法结果 array([10, 21, 32, 43])
c = a + b
# 乘法结果 array([0,  20,  60, 120])
c = a * b
# 幂结果 array([0, 1, 4, 9])
c = b ** 2
# 三角函数 array([-5.44021111,  9.12945251, -9.88031624,  7.4511316 ])
c = 10 * np.sin(a)
# 逻辑判断 array([ True,  True,  True, False])
print(b<3)

2) 二维矩阵

a = np.array([[1, 1], [0, 1]])
b = np.array([[0, 1], [2, 3]])
# ([[2, 4],
#  [2, 3]])
c_dot = np.dot(a,b) # 或者 c_dot_2 = a.dot(b)

3) 求和、最大、最小

# ([[ 0.94692159,  0.20821798,  0.35339414,  0.2805278 ],
#   [ 0.04836775,  0.04023552,  0.44091941,  0.21665268]])
a = np.random.random((2, 4))
# 4.4043622002745959
np.sum(a)
# 0.90438450240606416
np.max(a)
# 0.23651223533671784
np.min(a)

4) 操作行/列(当 axis 的值为 0 的时候,将会以列作为查找单元,当 axis 的值为 1 的时候,将会以行作为查找单元)

# sum = [ 1.96877324  2.43558896]
print("sum =", np.sum(a, axis = 1))
# max = [ 0.84869417  0.9043845 ]
print("max =", np.max(a, axis = 1))
# min = [ 0.23651224  0.41900661  0.36603285  0.46456022]
print("min =", np.min(a, axis = 0))

5) 最大元素、最小元素的索引

# array([[ 2, 3, 4, 5]
#        [ 6, 7, 8, 9]
#        [10,11,12,13]])
A = np.arange(2,14).reshape((3,4)) 
# 0   
print(np.argmin(A)) 
# 11
print(np.argmax(A))

6) 计算均值、中位数、累加函数、累差函数

在cumsum()函数中,生成的每一项矩阵元素均是从原矩阵首项累加到对应项的元素之和

累差函数计算的便是每一行中后一项与前一项之差。故一个 3 行 4 列矩阵通过函数计算得到的矩阵便是 3 行 3 列的矩阵

# 求和
# 7.5
print(np.mean(A)) # 或 print(A.mean()) 
# 7.5
print(np.average(A))

# 求中位数
# 7.5
print(np.median(A))

# 求累加
# [2 5 9 14 20 27 35 44 54 65 77 90]
print(np.cumsum(A)) 

# 求累差
# [[1 1 1]
#  [1 1 1]
#  [1 1 1]]
print(np.diff(A)) 

 7) 获取非零元素的索引。这个函数将所有非零元素的行与列坐标分割开,重构成两个分别关于行和列的矩阵

A[1][2] = 0
b, c = np.nonzero(A)
# 行索引 [0 0 0 0 1 1 1 2 2 2 2]
print(b)
# 列索引 [0 1 2 3 0 1 3 0 1 2 3]
print(c)

8) 排序、矩阵转置

注意:这里的排序函数仍然仅针对每一行进行从小到大排序操作

# [[14 13 12 11]
#  [10  9  8  7]
#  [ 6  5  4  3]]
A = np.arange(14, 2, -1).reshape(3, 4)
# [[11 12 13 14]
#  [ 7  8  9 10]
#  [ 3  4  5  6]]
print(np.sort(A))

# [[14 10  6]
#  [13  9  5]
#  [12  8  4]
#  [11  7  3]]
print(np.transpose(A)) # 或 print(A.T)

9) clip() 函数的格式是 clip(Array,Array_min,Array_max),顾名思义,Array 指的是将要被执行用的矩阵,而后面的最小值最大值则用于让函数判断矩阵中元素是否有比最小值小的或者比最大值大的元素,并将这些指定的元素转换为最小值或者最大值

# [[9 9 9 9]
#  [9 9 8 7]
#  [6 5 5 5]]
print(np.clip(A, 5, 9))

4、索引

import numpy as np
# array([3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
A = np.arange(3,15)
# 一维
# 6
print(A[3])

# 二维
# array([[ 3,  4,  5,  6]
     [ 7,  8,  9, 10]
#   [11, 12, 13, 14]])
A = A.reshape((3,4))

# [11 12 13 14]
print(A[2])         

# 8
print(A[1][1])

# [8 9]
print(A[1, 1:3])   

# 打印行
# [ 3,  4,  5, 6]
# [ 7,  8,  9, 10]
# [11, 12, 13, 14]
for row in A:
    print(row)

# 打印列
# [ 3,  7,  11]
# [ 4,  8,  12]
# [ 5,  9,  13]
# [ 6, 10,  14]
for column in A.T:
    print(column)

# flatten 将多维的矩阵进行展开成 1 行的数列
# array([3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
print(A.flatten())

5、合并

 1) 垂直合并、水平合并

import numpy as np
A = np.array([1, 1, 1])
B = np.array([2, 2, 2])

# 垂直合并
# [[1, 1, 1]
#  [2, 2, 2]]
C = np.vstack((A, B))
print(C)
# (3,) (2, 3)
print(A.shape,C.shape)

# 水平合并
# [1, 1, 1, 2, 2, 2]
D = np.hstack((A, B))
print(D)
# (3,) (6,)
print(A.shape, D.shape)

2) 插入新维度 newaxis

# (3,)
print(A.shape)

# [[1 1 1]]
print(A[np.newaxis, :])
# (1, 3)
print(A[np.newaxis, :].shape)

3) 合并多个矩阵或序列

C = np.concatenate((A, B, B, A), axis = 0)
"""
array([[1],
       [1],
       [1],
       [2],
       [2],
       [2],
       [2],
       [2],
       [2],
       [1],
       [1],
       [1]])
"""
print(C)

D = np.concatenate((A, B, B, A), axis = 1)
"""
array([[1, 2, 2, 1],
       [1, 2, 2, 1],
       [1, 2, 2, 1]])
"""
print(D)

6、分割

1) 横向分割、纵向分割

注意:只能等量对分

import numpy as np
a = np.arange(12).reshape((3, 4))
"""
array([[ 0,  1,  2,  3],
    [ 4,  5,  6,  7],
    [ 8,  9, 10, 11]])
"""
print(a)

# 横向分割
# [array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8,  9, 10, 11]])]
print(np.split(a, 3, axis = 0)) # 或 print(np.vsplit(a, 3))

# 纵向分割
"""
[array([[0, 1],
        [4, 5],
        [8, 9]]),
array([[ 2,  3],
        [ 6,  7],
        [10, 11]])]
"""
print(np.split(a, 2, axis = 1)) # 或 print(np.hsplit(a, 2)) 

2) 不等量分割

"""
[array([[0, 1],
        [4, 5],
        [8, 9]]), 
array([[ 2],
        [ 6],
        [10]]), 
array([[ 3],
        [ 7],
        [11]])]
"""
print(np.array_split(A, 3, axis = 1))

7、copy & deep copy

= 的赋值方式会带有关联性,copy() 的赋值方式没有关联性

import numpy as np

# array([0, 1, 2, 3])
a = np.arange(4)
b = a
c = a.copy()

a[3] = 44
# array([0, 1, 2, 44])
print(a)
# array([0, 1, 2, 44])
print(b)
# array([0, 1, 2, 3])
print(c)
原文地址:https://www.cnblogs.com/zerotoinfinity/p/12894999.html