科学计算库Numpy

例1: 导入txt文件为ndarray

H:\3.txt的内容:

1,2,3,4,5,我
6,7,8,9,0,额
a,s,d,f,g,个
a,s,d,f,g,好
z,x,c,v,b,就

导入3.txt的代码:

import numpy as np
train = np.genfromtxt(r'H:\3.txt', delimiter = ',', dtype = str)
print(type(train))
print(train)

运行结果:

<class 'numpy.ndarray'>
[['1' '2' '3' '4' '5' '我']
 ['6' '7' '8' '9' '0' '额']
 ['a' 's' 'd' 'f' 'g' '个']
 ['a' 's' 'd' 'f' 'g' '好']
 ['z' 'x' 'c' 'v' 'b' '就']]

注意:

1.在Python中\是转义符,所以绝对路径前面需要加一个r,或者将绝对路径中的\变为\,以免报错;
2.delimiter表示分隔符,若分隔符为空格,则表示为delimiter = ’ ‘;
3.dtype为描述数组元素的类型;
4.print(train.T)可以打印矩阵的转置;

例2: 通过ndarray生成向量和矩阵

代码:

import numpy as np
vector = np.array([1, 2, 3, 6, 7, 8])
print(vector)
print(vector.shape)
matrix = np.array([['a', 'b', 'c'], ['d', 'e', 'f'], [1, 2, 3]])
print(matrix)
print(matrix.shape)

运行结果:

[1 2 3 6 7 8]
(6,)
[['a' 'b' 'c']
 ['d' 'e' 'f']
 ['1' '2' '3']]
(3, 3)

注意:

1.生成矩阵的时候矩阵由一个中括在首尾;
2.字符串类型的元素前后要有引号;
3.若元素行数或列数不对齐,则会生成若干个list;
4.print(vector.shape)可以打印向量或矩阵的结构,可以用于理解算法或者debug;
5.vector.dtype可以描述数组元素的类型,ndarray中所有元素的类型相同;

例3: 矩阵的索引和切片

代码:

import numpy as np
train = np.genfromtxt('H:\\3.txt', delimiter = ',', dtype = str)
print(train)
train_3_5 = train[3, 5] #第四行第六列的元素
print(train_3_5)
train_all_2 = train[:,1] #第二列的全部元素
print(train_all_2)
vector = train_all_2[2:5] #左开右闭,从0计数
print(vector)
matrix = train[:,0:2] #所有行,0列和1列的元素
print(matrix)

运行结果:

[['1' '2' '3' '4' '5' '我']
 ['6' '7' '8' '9' '0' '额']
 ['a' 's' 'd' 'f' 'g' '个']
 ['a' 's' 'd' 'f' 'g' '好']
 ['z' 'x' 'c' 'v' 'b' '就']]
好
['2' '7' 's' 's' 'x']
['s' 's' 'x']
[['1' '2']
 ['6' '7']
 ['a' 's']
 ['a' 's']
 ['z' 'x']]

注意:

1.矩阵的行和列都是从0开始计数;

例4: 判断的运算

代码一(向量):

import numpy as np
vector = np.array([1, 2, 3, 6, 7, 8])
print(vector)
vector == 6

运行结果:

[1 2 3 6 7 8]

array([False, False, False,  True, False, False])

注意:

1.一个模块只能给一次判断的输出,如有多个此类运算,则只输出最后一句;
2.对矩阵的操作相同;
3.没有返回dtypr;

代码二(矩阵):

import numpy as np
vector = np.array([1, 2, 3, 6, 7, 8])
equal_to_seven = (vector == 7)
print(equal_to_seven)
print(vector[equal_to_seven])

运行结果:

[False False False False  True False]
[7]

注意:

1.返回的布尔类型的值可以当成索引,vector[equal_to_ten]中的true返回vector中对应的元素,false不返回;
2.矩阵同理:

import numpy as np
matrix = np.array([['a', 'b', 'c'], ['d', 'e', 'f'], [1, 'e', 3]])
print(matrix)
second_column_e = (matrix[:,1] == 'e') #第二列,元素为e返回true,否则返回false
print(second_column_e)
print(matrix[second_column_e,:]) #打印第二列的元素为e的所有行
[['a' 'b' 'c']
 ['d' 'e' 'f']
 ['1' 'e' '3']]
[False  True  True]
[['d' 'e' 'f']
 ['1' 'e' '3']]

例5: 逻辑运算

代码一(与):

import numpy as np
vector = np.array([5,10,15,20])
equal_to_five_and_ten = (vector == 5) & (vector == 10) #等于5且等于10的元素
print(equal_to_five_and_ten)

运行结果:

[False False False False]

代码二(或):

import numpy as np
vector = np.array([5,10,15,20])
equal_to_five_or_ten = (vector == 5) | (vector == 10) #等于5或等于10的元素
print(equal_to_five_or_ten)

运行结果:

[ True  True False False]

代码三(替换):

import numpy as np
vector = np.array([5,10,15,20])
equal_to_five_or_ten = (vector == 5) | (vector == 10)
vector[equal_to_five_or_ten] = 2 #将满足等于5或等于10的元素替换为2
print(vector)

运行结果:

[ 2  2 15 20]

例6: Numpy.array的部分属性

代码一(数据类型属性):

import numpy as np
vector = np.array(['1', '2', '3'])
print(vector.dtype)
print(vector)
vector_int = vector.astype(int)
print(vector_int.dtype)
print(vector_int)

运行结果:

<U1
['1' '2' '3']
int32
[1 2 3]

代码二(最大值最小值属性):

import numpy as np
matrix = np.array([[5,10,15,20],[3,5,7,9],[13,23,33,43]])
print('min:{}'.format(matrix.min()))
print('max:{}'.format(matrix.max()))

运行结果:

min:3
max:43

代码三(求和属性):

import numpy as np
matrix = np.array([[5,10,15,20],
                   [3,5,7,9],
                   [13,23,33,43]])
print('sum_axis_1:{}'.format(matrix.sum(axis=1))) #对行求和
print('sum_axis_0:{}'.format(matrix.sum(axis=0))) #对列求和

运行结果:

sum_axis_1:[ 50  24 112]
sum_axis_0:[21 38 55 72]

代码四(arange、reshape、shape、ndim、size):

import numpy as np
vector = np.arange(27) #生成元素为0到26的向量
print('vector={}'.format(vector))
matrix = vector.reshape(3,3,3) #切成三维矩阵
print('matrix={}'.format(matrix))
print('shape:{}'.format(matrix.shape))
print('ndim:{}'.format(matrix.ndim))
print('size:{}'.format(matrix.size))

运行结果:

vector=[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 24 25 26]
matrix=[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]
  [24 25 26]]]
shape:(3, 3, 3)
ndim:3
size:27

代码五(zeros、ones、arange):

import numpy as np
matrix_0 = np.zeros((3,4))
print('3*4的全0矩阵:\n{}'.format(matrix_0))
matrix_1 = np.ones((2,3,4),dtype=np.int)
print('2*3*4的全1矩阵:\n{}'.format(matrix_1))
print(np.arange(20,30,2)) #[20,30)左闭右开,步长为2

运行结果:

3*4的全0矩阵:
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
2*3*4的全1矩阵:
[[[1 1 1 1]
  [1 1 1 1]
  [1 1 1 1]]

 [[1 1 1 1]
  [1 1 1 1]
  [1 1 1 1]]]
[20 22 24 26 28]

代码六(random):

import numpy as np
print(np.random.random((2,2)))       #random()中输入的数组(2,2)要带括号
print( random.randint(1,10) )        # 产生 1 到 10 的一个整数型随机数
print( random.random() )             # 产生 0 到 1 之间的随机浮点数
print( random.uniform(1.1,5.4) )     # 产生  1.1 到 5.4 之间的随机浮点数,区间可以不是整数
print( random.randrange(1,100,2) )   # 生成从1到100的间隔为2的随机整数
print( random.choice(np.arange(20,30,2)))   # 从序列中随机选取一个元素

运行结果:

[[0.26732446 0.74322009]
 [0.85329226 0.31602406]]
4
0.5181676732299492
5.111853171586805
93
22

代码七(linspace):

import numpy as np
print(np.linspace(0,98,10)) #0到98等间隔取10个值

运行结果:

[ 0.         10.88888889 21.77777778 32.66666667 43.55555556 54.44444444
 65.33333333 76.22222222 87.11111111 98.        ]

例7: 运算

代码一(向量):

import numpy as np
a = np.arange(4)
print(a)
print(a**2)
print(a**2-a)
print(a<4)
print(np.exp(a))
print(np.sqrt(a))

运行结果:

[0 1 2 3]
[0 1 4 9]
[0 0 2 6]
[ True  True  True  True]
[ 1.          2.71828183  7.3890561  20.08553692]
[0.         1.         1.41421356 1.73205081]

代码二(矩阵):

import numpy as np
A = np.array([[1,2],
              [3,4]])
B = np.array([[0,2],
              [4,6]])
print('A=\n{}'.format(A))
print('B=\n{}'.format(B))
print('矩阵对应位置相乘:\n{}'.format(A*B)) #矩阵A和矩阵B对应位置元素相乘!!!
print('矩阵相乘:\n{}'.format(A.dot(B))) #矩阵乘法
print('矩阵相乘:\n{}'.format(np.dot(A,B))) #矩阵乘法

运行结果:

A=
[[1 2]
 [3 4]]
B=
[[0 2]
 [4 6]]
矩阵对应位置相乘:
[[ 0  4]
 [12 24]]
矩阵相乘:
[[ 8 14]
 [16 30]]
矩阵相乘:
[[ 8 14]
 [16 30]]

代码三(矩阵2):

import numpy as np
C = np.floor(10*np.random.random((2,2))) #floor表示向下取整
print(C)
D = np.ravel(C) #将矩阵展开成向量
print(D)
E = C.ravel() #将矩阵展开成向量
print(E)
X = D.reshape(4,1) #D切割后的矩阵赋给X
print(X)
E.shape = (4,1) #直接改变E的shape
print(E)
print(C.T) #转置

运行结果:

[[2. 1.]
 [9. 6.]]
[2. 1. 9. 6.]
[2. 1. 9. 6.]
[[2.]
 [1.]
 [9.]
 [6.]]
[[2.]
 [1.]
 [9.]
 [6.]]
[[2. 9.]
 [1. 6.]]

代码四(矩阵拼接):

import numpy as np
a = np.floor(10*np.random.random((2,2)))
b = np.floor(10*np.random.random((2,2)))
print('a=\n{}'.format(a))
print('b=\n{}'.format(b))
print(np.hstack((a,b))) #行拼接,左a右b
print(np.vstack((b,a))) #列拼接,上b下a

运行结果:

a=
[[2. 9.]
 [4. 3.]]
b=
[[4. 3.]
 [6. 0.]]
[[2. 9. 4. 3.]
 [4. 3. 6. 0.]]
[[4. 3.]
 [6. 0.]
 [2. 9.]
 [4. 3.]]

代码五(矩阵拆分):

import numpy as np
c = np.floor(10*np.random.random((4,6)))
print(c)
print(np.hsplit(c,3)) #将矩阵c按列等分三份
print(np.vsplit(c,2)) #将矩阵c按行等分两份
print(np.hsplit(c,(2,3,4))) #(2,3,4)为切分的位置,总共分为四个子矩阵

运行结果:

[[6. 8. 5. 7. 4. 9.]
 [8. 8. 4. 0. 7. 1.]
 [0. 7. 7. 9. 4. 2.]
 [0. 7. 0. 0. 0. 2.]]
[array([[6., 8.],
       [8., 8.],
       [0., 7.],
       [0., 7.]]), array([[5., 7.],
       [4., 0.],
       [7., 9.],
       [0., 0.]]), array([[4., 9.],
       [7., 1.],
       [4., 2.],
       [0., 2.]])]
[array([[6., 8., 5., 7., 4., 9.],
       [8., 8., 4., 0., 7., 1.]]), array([[0., 7., 7., 9., 4., 2.],
       [0., 7., 0., 0., 0., 2.]])]
[array([[6., 8.],
       [8., 8.],
       [0., 7.],
       [0., 7.]]), array([[5.],
       [4.],
       [7.],
       [0.]]), array([[7.],
       [0.],
       [9.],
       [0.]]), array([[4., 9.],
       [7., 1.],
       [4., 2.],
       [0., 2.]])]

例8: 复制的相关说明

代码一(用等号赋值):

import numpy as np
a = np.arange(12)
b = a
print(b is a) #矩阵a和b相等
b.shape= (3,4) #将b变成3*4的矩阵
print(a.shape) #查看a的shape,也变为(3,4)
print(id(a)) #a的id
print(id(b)) #b的id和a的id相同,代表变量名a和b存储在同一位置,改变其一则另一个也会改变

运行结果:

True
(3, 4)
2046808552512
2046808552512

代码二(用.view()):

import numpy as np
a = np.arange(12)
c = a.view()
print(a is c)
c.shape = (3,4)
print(a)
print(c)
print(a.shape) #a为向量,a.T还是a,shape为(12,)
print(c.shape)
print(id(a))
print(id(c))
c[1,2]=999 #变量名a和c=a.view()虽然存储在不同位置,shape也可以不同,但是共用同一元素
print(a)
print(c)

运行结果:

False
[ 0  1  2  3  4  5  6  7  8  9 10 11]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
(12,)
(3, 4)
2046825424576
2046825425536
[  0   1   2   3   4   5 999   7   8   9  10  11]
[[  0   1   2   3]
 [  4   5 999   7]
 [  8   9  10  11]]

代码三(用.copy):

import numpy as np
a = np.arange(12)
d = a.copy()
print(a is d)
a[1]=999
print(a)
print(d)

运行结果:

False
[  0 999   2   3   4   5   6   7   8   9  10  11]
[ 0  1  2  3  4  5  6  7  8  9 10 11]

代码四(查找每行/每列的最大值/最小值):

import numpy as np
data = np.sin(np.arange(20).reshape(5,4))
print(data)
ind = data.argmax(axis=0) #返回每列最大的元素所在行
print(ind)
data_int = data[ind,range(data.shape[1])] #返回每列最大值所在行对应的元素,range(start, stop[, step])
print(data.shape[0])#.shape[0] 为第一维的长度,c.shape[1] 为第二维的长度
print(data.shape[1])
print(data_int)
z = data[[2,0,3,1],[0,1,2,3]] #等效于此过程
print(z)

运行结果:

[[ 0.          0.84147098  0.90929743  0.14112001]
 [-0.7568025  -0.95892427 -0.2794155   0.6569866 ]
 [ 0.98935825  0.41211849 -0.54402111 -0.99999021]
 [-0.53657292  0.42016704  0.99060736  0.65028784]
 [-0.28790332 -0.96139749 -0.75098725  0.14987721]]
[2 0 3 1]
5
4
[0.98935825 0.84147098 0.99060736 0.6569866 ]
[0.98935825 0.84147098 0.99060736 0.6569866 ]

代码五(tile重复):

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a)
b = np.tile(a,(2,3))
print(b)

运行结果:

[[1 2 3]
 [4 5 6]]
[[1 2 3 1 2 3 1 2 3]
 [4 5 6 4 5 6 4 5 6]
 [1 2 3 1 2 3 1 2 3]
 [4 5 6 4 5 6 4 5 6]]

代码六(sort排序):

import numpy as np
a = np.array([[3,8,5],[7,6,9]])
print('a:\n{}'.format(a))
b0 = np.sort(a,axis=0) #每列元素按由小到大排序
b1 = np.sort(a,axis=1) #每行元素按由小到大排序
print('b0:\n{}'.format(b0))
print('b1:\n{}'.format(b1))
c0 = np.argsort(a,axis=0) #每列元素由小到大从0排序
c1 = np.argsort(a,axis=1) #每行元素由小到大从0排序
print('c0:\n{}'.format(c0))
print('c1:\n{}'.format(c1))

运行结果:

a:
[[3 8 5]
 [7 6 9]]
b0:
[[3 6 5]
 [7 8 9]]
b1:
[[3 5 8]
 [6 7 9]]
c0:
[[0 1 0]
 [1 0 1]]
c1:
[[0 2 1]
 [1 0 2]]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值