import numpy as np
#####
##定义数组
#####
nump_1d = np.array([1,2,3,])
nump_2d = np.array([[1,2],[3,4]])
##使用dtype 来固定类型(np.bool是布尔类型)
nump_1da = np.array([1,0,1,1,1,0],dtype=np.bool)
print(nump_1d)
print(nump_2d)
print(nump_1da)
输出结果:
[1 2 3]
[[1 2]
?[3 4]]
属性
import numpy as np
#####
##定义数组
#####
nump_1d = np.array([[1,2,3,4],[2,3,4,5],[3,4,5,6]])
##维度
print(nump_1d.ndim)
##形状
print(nump_1d.shape)
##元组类型
print(nump_1d.dtype)
##元素总个数
print(nump_1d.size)
结果:
2
(3, 4)
int32
12
import numpy as np
#####
##定义数组
#####
nump_1d = np.array([[1,2,3,4],[2,3,4,5],[3,4,5,6]])
#有12个元素,都为0
nump1 = np.zeros(12)
nump11 = np.zeros((3,4))
#10个元素都为1的数组
nump2 = np.ones(10)
nump22 = np.ones((3,4))
#空数组
nump3 = np.empty(10)
print(nump_1d)
print(nump1)
print(nump11)
print(nump2)
print(nump22)
print(nump3)
结果:
[[1 2 3 4]
?[2 3 4 5]
?[3 4 5 6]]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[[0. 0. 0. 0.]
?[0. 0. 0. 0.]
?[0. 0. 0. 0.]]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[[1. 1. 1. 1.]
?[1. 1. 1. 1.]
?[1. 1. 1. 1.]]
[6.95322033e-310 1.02356692e-259 4.88573032e+252 7.68283953e+170
?2.58634777e+161 1.67494829e+243 1.95132487e+227 1.23781356e-259
?1.12547024e-153 3.98384720e+252]
构建数组
import numpy as np
#####
##定义数组
#####
#np.arange(开始,结束,步长)
nump1 = np.arange(0,10,1)
nump2 = np.arange(0,10,2)
print(nump1)
print(nump2)
#np.linspace(开始,结束,元素个数)
nump3 = np.linspace(0,10,5)
print(nump3)
#np.logspace(开始,结束,元素个数)
nump4 = np.logspace(0,10,5)
print(nump4)
#随机数填充,指定数组形状
nump5 = np.random.random((2,2,4))
print(nump5)
结果
[0 1 2 3 4 5 6 7 8 9]
[0 2 4 6 8]
[ 0. 2.5 5. 7.5 10. ]
[1.00000000e+00 3.16227766e+02 1.00000000e+05 3.16227766e+07
1.00000000e+10]
[[[0.45437438 0.53447569 0.05279042 0.41002003]
[0.1963433 0.53625337 0.52967245 0.58340509]]
[[0.81364533 0.41562179 0.00581232 0.83009324]
[0.4319811 0.07269586 0.67920929 0.18875023]]]
|