以下代码均需要导入numpy,故省略 import numpy as np
1、基本操作:
import numpy as np
a = np.array([1, 2, 3])
print(a)
print(type(a)) # 查看数组类型
print(a.shape) # 查看大小
# 通过使用reshape明确将数组指定行列关系
b = a.reshape(1, -1) # 第一个1表示整个数组只有一行,后面的-1是占位符,实际表示的是3
print(b.shape)
结果为:
[1 2 3]
<class ‘numpy.ndarray’>
(3,)
(1, 3)
2、改变数组中的元素:
c = np.array([1, 2, 3, 4, 5, 6])
c = c.reshape((-1, 2))
print(c.shape)
print(c)
print(c[2, 0])
c[2, 0] = 55
print(c)
结果为:
(3, 2)
[[1 2]
[3 4]
[5 6]]
5
[[ 1 2]
[ 3 4]
[55 6]]
4、zeros 创建全部为0的数组
d = np.zeros((3, 3))
print(d)
结果为:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
5、ones 创建全部为1的数组
e = np.ones((2, 3))
print(e)
结果为:
[[1. 1. 1.]
[1. 1. 1.]]
6、full可代替zeros和ones的功能:
a = np.full((3, 3), 0)
print(a)
a = np.full((2, 3), 1)
print(a)
结果为:
[[0 0 0]
[0 0 0]
[0 0 0]]
[[1 1 1]
[1 1 1]]
7、eye 单位矩阵
f = np.eye(3)
print(f)
结果为:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
8、 生成(0-1)的随机数矩阵
g = np.random.random((3, 4))
print(g)
结果为:
[[0.00242217 0.73087671 0.19172274 0.53419157]
[0.86524713 0.01398055 0.5349048 0.65108886]
[0.39684444 0.38109035 0.89926698 0.1114804 ]]
题目描述:
对于一维数组或者列表,unique函数去除其中重复的元素,并按元素由大到小返回一个新的无元素重复的元组或者列表.
import numpy as np
A = [1, 2, 2, 5, 3, 4, 3]
print(np.unique(A))
B = (1, 2, 2, 5, 3, 4, 3)
print(np.unique(B))
结果为:
[1 2 3 4 5]
[1 2 3 4 5]