1.ndarray对象
1.1 属性
属性名字 | 属性解释 |
---|---|
ndarray.shape | 数组维度的元组 |
ndarray.ndim | 数组维数 |
ndarray.size | 数组中的元素数量 |
ndarray.itemsize | 一个数组元素的长度(字节) |
ndarray.dtype | 数组元素的类型 |
2. 数组生成
2.1 linspace(等差数组)
- 描述
numpy.linspace
函数用于创建一个一维数组,数组是一个等差数列构成的(指定数量)
- 用法
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
参数 |
start
| 序列的起始值 | | —- | —- | |stop
| 序列的终止值,如果endpoint
为true
,该值包含于数列中 | |num
| 要生成的等步长的样本数量,默认为50
| |endpoint
| 该值为true
时,数列中包含stop
值,反之不包含,默认是True。 | |retstep
| 如果为 True 时,生成的数组中会显示间距,反之不显示。 | |dtype
|ndarray
的数据类型 |返回值
返回一个ndarray
数组,数组内元素的类型为numpy.float64
用法
import numpy as np
a = np.linspace(1,10,10)
print(a)
# [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
2.2 生成0/1数组
描述
生成全0或全1的数组
- 用法
np.ones(shape, dtype)
np.ones_like(a, dtype)
np.zeros(shape, dtype)
np.zeros_like(a, dtype)
参数 |
shape:列表
| 生成的数组形状 | | —- | —- | |a:array_like
| 生成与数组a
形状相同的数组 | |dtype:np.dtype
| 数据类型,默认为浮点数 |返回值
2.3 从现有数组生成
- 描述
从已有的数组生成一个ndarray
数组,有两种方法,这两种略有不同
- 用法
np.array(array_like)
np.asarray(array_like)
参数 |
array_like
| 用于生成ndarray数组的列表或数组 | | —- | —- |二者区别
array属于深拷贝,即他是复制一份新的数组用于生成
而asarray属于浅拷贝,即他是直接用原有数组的内存空间生成
所以当原有数组里的元素修改时,array
生成的数组不会变化,而asarray
生成的数组的元素会随着变化
2.4 arange(等差数组)
- 描述
创建等差数组。(指定步长)
- 用法
np.arange(start,stop, step, dtype)
- 参数
|
start
| 序列起始值 | | —- | —- | |stop
| 序列终止值 | |step
| 步长 |
2.5 logspace (等比数列)
- 描述
创建等比数列数组
用法
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
参数 | 参数 | 描述 | | :—- | :—- | |
start
| 序列的起始值为:base start | |stop
| 序列的终止值为:base stop。如果endpoint
为true
,该值包含于数列中 | |num
| 要生成的等步长的样本数量,默认为50
| |endpoint
| 该值为true
时,数列中中包含stop
值,反之不包含,默认是True。 | |base
| 对数 log 的底数。 | |dtype
|ndarray
的数据类型 |
注意:start和stop相当于等比数列的次数,base即等比数列的基数,默认为10
示例
np.logspace(0, 4, 5, base=2)
# array([ 1., 2., 4., 8., 16.])
2.5 随机数组生成
2.5.1 正态分布
正态分布记作,决定了其位置,其标准差决定了分布的幅度。当时的正态分布是标准正态分布。标准差越大,则正态分布图像开口越大。
np.random.normal(loc=0.0,scale=1.0,size=None)
loc:float
此概率分布的均值(对应着整个分布的中心centre)
scale:float
此概率分布的标准差(对应于分布的宽度,scale越大越矮胖,scale越小,越瘦高)
size:int or tuple of ints
输出的shape,默认为None,只输出一个值
np.random.standard_normal(size=None)
2.5.2 均匀分布
np.random.randn(d0,d1,d2...)
创建给定形状的数组,并使用上均匀分布的随机数填充数组,随机数范围在,d0,d1,d2..
指的是数组的维度。
注意:参数只能填int数,不能填列表或元组
np.random.uniform(low=0.0, high=1.0, size=None)
low
: 采样下界,float类型,默认值为0;high
: 采样上界,float类型,默认值为1;size
: 输出样本数目,为int或元组(tuple)类型,例如,size=(m,n,k), 则输出m_n_k个样本,缺省时输出1个值。
np.random.randint(low, high=None, size=None, dtype='l')
- 一个均匀分布中随机采样,生成一个整数或N维整数数组,
- 取数范围:若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数。
3. 数学函数与数组运算
3.1 三角函数
- 描述
计算三角函数值
- 用法
np.sin(x)
、np.cos(x)
参数 |
x
:array_like
| 一个类数组,列表、元组、adarray等 | | —- | —- |返回值
3.2 通用判断函数
np.all(判断语句)
对判断语句中数组的所有元素进行判断,如果全部为True
,返回True
,否则返回False
np.any(判断语句)
对判断语句中数组的所有元素进行判断,如果存在True
,返回True
,如果全是False
返回False
- 示例
score = np.random.randint(30,100,(5,4))
#array([[96, 63, 35, 80],
# [72, 84, 39, 92],
# [77, 61, 91, 72],
# [50, 67, 76, 48]])
np.all(score[0:2] > 60) # False
np.any(score[0:2] > 60) # True
注意:这里返回的是一个
bool
值,不是一个ndarray
3.3 where(三元运算符)
这个函数类似于for循环遍历数组的所有元素,然后根据判断条件(True/False)对其进行修改
- 用法
np.where(逻辑判断,true_value, false_value)
参数 | 逻辑判断 | 是指对数组的每个元素按条件进行判断转化成bool值 | | —- | —- | |
true_value
| 如果对应位置上的bool值是true,则转化成true_value
| |false_value
| 如果是False,则替换成false_value
|返回值
返回修改过后的ndarray。
- 示例
```python
temp
array([[96, 63, 35, 80],
[72, 84, 39, 92]])
np.where(temp>60,’及格’,’不及格’)array([[‘及格’, ‘及格’, ‘不及格’, ‘及格’],
[‘及格’, ‘及格’, ‘不及格’, ‘及格’]], dtype=’<U3’)
np.where(np.logical_or(temp>80,temp<60),1,0)
array([[1, 0, 1, 0],
[0, 1, 1, 1]])
np.where(np.logical_and(temp>70,temp<90),1,0)
array([[0, 0, 0, 1],
[1, 1, 0, 0]])
---
<a name="JxkJj"></a>
## 3.4 统计运算
- `min(a, axis)` # 最小值
- Return the minimum of an array or minimum **along an axis**.
- `max(a, axis])` # 最大值
- Return the maximum of an array or maximum along an axis.
- `median(a, axis)` # 中位数
- Compute the median along the specified axis.
- `mean(a, axis, dtype)` # 平均值
- Compute the arithmetic mean along the specified axis.
- `std(a, axis, dtype)` # 标准差 =方差开根
- Compute the standard deviation along the specified axis.
- `var(a, axis, dtype)` # 方差
- Compute the variance along the specified axis.
**axis 0代表列, axis 1代表行去进行统计, 如果不指定轴,则是对整个数组元素进行操作****。**
- 示例
```python
array([[96, 63, 35, 80],
[72, 84, 39, 92],
[36, 57, 94, 46],
[77, 61, 91, 72],
[50, 67, 76, 48]])
np.max(score,axis=0) # array([96, 84, 94, 92])
np.max(score,axis=1) # array([96, 92, 94, 91, 76])
np.max(score) # 96
- np.argmax(temp, axis=)
- np.argmin(temp, axis=)
- 不是返回最大/最小值,而是返回下标。
- 示例
array([[96, 63, 35, 80], [72, 84, 39, 92], [36, 57, 94, 46], [77, 61, 91, 72], [50, 67, 76, 48]]) np.argmin(score) # 2 np.argmin(score, axis=1) #array([2, 2, 0, 1, 3], dtype=int64)
注意:下标不是类似于索引的形式,而是一行一行数,数它是第几个元素。
3.5 广播机制
满足一下任一条件即可广播
- 1.数组的某一维度等长。
- 2.其中一个数组的某一维度为1 。
且数组之间的加减乘除数学运算是对每个元素进行运算,与列表不一样,列表的乘(*)是复制元素
3.6 矩阵乘法
np.matmul(矩阵A,矩阵B)
np.dot
二者都是矩阵乘法。 np.matmul
中禁止矩阵与标量的乘法。 在矢量乘矢量的內积运算中,np.matmul
与np.dot
没有区别。其实矩阵与标量的乘法就是ndarray*scale
3.7 np.argmax()
numpy.argmax(array, axis)
用于返回一个numpy数组中最大值的索引值。当一组中同时出现几个最大值时,返回第一个最大值的索引值。
one_dim_array = np.array([1, 4, 5, 3, 7, 2, 6])
print(np.argmax(one_dim_array)) # 4
#--------------------------------------
two_dim_array = np.array([[1, 3, 5], [0, 4, 3]])
max_index_axis0 = np.argmax(two_dim_array, axis = 0)
max_index_axis1 = np.argmax(two_dim_array, axis = 1)
print(max_index_axis0) # [0 1 0]
print(max_index_axis1) # [2 1]
4. 数组形状/类型修改
4.1 resize
- 描述
将数组修改成指定的形状,如果修改后的形状大于原先形状,则自动填充,有两种调用方式,其填充不同
- 用法
np.resize(a, new_shape)
ndarray.resize(new_shape)
,是in-place
操作,即在数组内存空间引用上修改
- 参数
|
a:array_like
| Array to be resized. | | —- | —- | |new_shape:int or tuple of int
| Shape of resized array. |
注意:
np.resize
在元素不足时复制原数组的元素进行填充,而ndarray.resize
填充的是0。
- 返回值
4.2 reshape
- 描述
与resize
类似,但当修改后的形状大于原形状,无填充能力。可自己选择以什么样的顺序去填充新的数组
- 用法
np.reshape(a, newshape, order='C')
ndarray.reshape(newshape, order='C')
参数 |
a:array_like
| Array to be resized. | | —- | —- | |new_shape:int or tuple of int
| Shape of resized array.允许存在-1,此时-1维度由程序自己推出 | |order:{‘C’,‘F’,‘A’}, ``optional
| ‘C’的意思就是说按照索引顺序横着读取原数组元素,然后按照行的顺序写入新数组,’F’则是竖(列)着读,竖(列)着写 |示例
old = np.arange(0, 6).reshape((2,3)) #array([[0, 1, 2], # [3, 4, 5]]) new = np.reshape(old, (3,2),'F') #列读取/写入 #array([[0, 4], # [3, 2], # [1, 5]]) new = np.reshape(old, (3,2),'C') #行读取/写入 #array([[0, 1], # [2, 3], # [4, 5]])
4.3 转置
ndarray.T
4.4 类型修改
ndarray.astype(type)
4.5 vstack
按垂直方向(行顺序)堆叠数组构成一个新的数组。就是一行一行的放。
a = np.array([1,2,3]) # array([1, 2, 3])
np.vstack(a)
#array([[1],
# [2],
# [3]])
b = np.array([4,5,6])
np.vstack([a,b])
# array([[1, 2, 3],
# [4, 5, 6]])