一、numpy创建数组的几种主要方法
1、array()函数-自由创建+reshape()方法
#可通过列表如[1,2,3,4],元组如(1,2,3,4)创建
import numpy as np
# 一维
x=np.array([1,2,3,4])
# 二维
y=np.array([1,2,3,4]).reshape(2,2)# y=np.array([[1,2],[3,4]])同样可以
#三维
z=np.array([1,2,3,4,5,6,7,8]).reshape(2,2,2)#z=np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
print('x =',x)
print('y =',y)
print('z =',z)
x = [1 2 3 4]
y = [[1 2]
[3 4]]
z = [[[1 2]
[3 4]]
[[5 6]
[7 8]]]
查看维度、维度数量维数rank。
print(x.shape)
print(x.ndim)
print(y.shape)
print(y.ndim)
print(z.shape)
print(z.ndim)
(4,)
1
(2, 2)
2
(2, 2, 2)
3
2、arange()方法+reshape()方法。
#一维
x1=np.arange(1,5)
x1
array([1, 2, 3, 4])
#二维
y1=np.arange(1,5).reshape(2,2)
y1
array([[1, 2],
[3, 4]])
#三维
z1=np.arange(1,9).reshape(2,2,2)
z1
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
3、random随机创建
randint()方法
#二维
x2=np.random.randint(1,9,size=(3,3))
x2
array([[5, 1, 3],
[7, 7, 2],
[3, 2, 1]])
#三维
y2=np.random.randint(1,8,size=(2,2,2))
print(y2)
y21=np.random.randint((8),size=(2,2,2))
print(y21)
[[[7 3]
[4 5]]
[[4 5]
[4 2]]]
[[[4 2]
[3 4]]
[[1 4]
[0 2]]]
randn()方法,是从标准正态分布中返回一个或多个样本值
x3=np.random.randn(8).reshape(4,2)
x3
array([[ 0.37746398, -0.02392064],
[ 1.22888408, -0.39583126],
[ 1.52502591, 0.26157022],
[-0.4875009 , -0.01560054]])
rand()、random()方法,(0, 1)之间返回随机浮点数。
#二维
x3=np.random.rand(4).reshape(2,2)#rand()
x31=np.random.random(4).reshape(2,2)#可用reshape方法达到同样效果
x32=np.random.random((2,2))#random可直接选择shape
print(x3)
print(x31)
print(x32)
[[0.29607993 0.62878791]
[0.57983781 0.5999292 ]]
[[0.26581912 0.28468588]
[0.25358821 0.32756395]]
```python
#三维
y3=np.random.random(size=(2,2,2))
y3
array([[[0.2498302 , 0.22246554],
[0.92549316, 0.77187547]],
[[0.76868922, 0.94260006],
[0.16694415, 0.84189517]]])
4、linspace() 创建指定数量数组
a=np.linspace(1,9,5)#范围1-9的5个浮点数
print(a)
print(a.dtype)
[1. 3. 5. 7. 9.]
float64
5、indices() 创建由一维数组堆叠的三维数组
b=np.indices((2,2))
b
array([[[0, 0],
[1, 1]],
[[0, 1],
[0, 1]]])
6、seed()方法,设置seed(x)种子,生成相同的随机数,x为任意整数,但改变x会改变随机数
np.random.seed(5)
z3=np.random.random(size=(2,2,2))
np.random.seed(5)
z4=np.random.random(size=(2,2,2))
print(z3)
print(z4)
[[[0.22199317 0.87073231]
[0.20671916 0.91861091]]
[[0.48841119 0.61174386]
[0.76590786 0.51841799]]]
[[[0.22199317 0.87073231]
[0.20671916 0.91861091]]
[[0.48841119 0.61174386]
[0.76590786 0.51841799]]]
7、ones()、zeros()方法创建全为1和0的数组
x4=np.ones((2,2,2))
x4
array([[[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.]]])
x5=np.zeros((2,2,2))
x5
array([[[0., 0.],
[0., 0.]],
[[0., 0.],
[0., 0.]]])