Numpy 数组操作
修改数组形状
函数 | 描述 |
---|---|
reshape | 不改变数据的条件下修改形状 |
flat | 数组元素迭代器 |
flatten | 返回一份数组拷贝, 对拷贝所做的修改不会影响原始数组 |
ravel | 返回展开数组 |
numpy.reshape
numpy.reshape
函数可以在不改变数据的条件下修改形状, 格式如下:
numpy.reshape(arr, newshape, order='C')
arr
为要修改形状的数组. newshape
为整数或者整数数组, 新的形状应当兼容原有形状. order
是可选参数, C — 按行, F– 按列, A — 原顺序, k– 元素在内存中的出现顺序.
import numpy as np
a = np.arange(8)
print ('原始数组: ')
print (a)
print ('\n')
b = a.reshape(4,2)
print ('修改后的数组: ')
print (b)
输出:
原始数组:
[0 1 2 3 4 5 6 7]
修改后的数组:
[[0 1]
[2 3]
[4 5]
[6 7]]
numpy.ndarray.flat
numpy.ndarray.flat
是一个数组元素迭代器, 实例如下:
import numpy as np
a = np.arange(9).reshape(3,3)
print ('原始数组: ')
for row in a:
print (row) #对数组中每个元素都进行处理, 可以使用flat属性, 该属性是一个数组元素迭代器:
print ('迭代后的数组: ')
for element in a.flat:
print (element)
输出结果如下:
原始数组:
[0 1 2]
[3 4 5]
[6 7 8]
迭代后的数组:
0
1
2
3
4
5
6
7
8
numpy.ndarray.flatten
numpy.ndarray.flatten
返回一份数组拷贝, 对拷贝所做的修改不会影响原始数组, 格式如下:
ndarray.flatten(order='C')
order
是可选参数, C — 按行, F– 按列, A — 原顺序, k– 元素在内存中的出现顺序.
import numpy as np
a = np.arange(8).reshape(2,4)
print ('原数组: ')
print (a)
print ('\n') # 默认按行
print ('展开的数组: ')
print (a.flatten())
print ('\n')
print ('以 F 风格顺序展开的数组: ')
print (a.flatten(order = 'F'))
输出结果如下:
原数组:
[[0 1 2 3]
[4 5 6 7]]
展开的数组:
[0 1 2 3 4 5 6 7]
以 F 风格顺序展开的数组:
[0 4 1 5 2 6 3 7]
numpy.ravel
numpy.ravel()
展平的数组元素, 顺序通常C风格, 返回的是数组视图, 修改会影响原始数组.
该函数接收两个参数:
numpy.ravel(a, order='C')
a
为要修改形状的数组. order
是可选参数, C — 按行, F– 按列, A — 原顺序, k– 元素在内存中的出现顺序.
import numpy as np a = np.arange(8).reshape(2,4) print (‘原数组: ‘) print (a) print (‘\n’) print (‘调用 ravel 函数之后: ‘) print (a.ravel()) print (‘\n’) print (‘以 F 风格顺序调用 ravel 函数之后: ‘) print (a.ravel(order = ‘F’))
输出结果如下:
原数组:
[[0 1 2 3]
[4 5 6 7]]
调用 ravel 函数之后:
[0 1 2 3 4 5 6 7]
以 F 风格顺序调用 ravel 函数之后:
[0 4 1 5 2 6 3 7]
翻转数组
函数 | 描述 |
---|---|
transpose | 对换数组的维度 |
ndarray.T | 和 self.transpose() 相同 |
rollaxis | 向后滚动指定的轴 |
swapaxes | 对换数组的两个轴 |
numpy.transpose
numpy.transpose
函数用于对换数组的维度, 格式如下:
numpy.transpose(arr, axes)
arr
为要操作的数组. axes
是整数列表, 对应维度, 通常所有维度都会对换.
import numpy as np
a = np.arange(12).reshape(3,4)
print ('原数组: ')
print (a )
print ('\n')
print ('对换数组: ')
print (np.transpose(a))
输出:
原数组:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
对换数组:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
numpy.ndarray.T
类似 numpy.transpose
:
import numpy as np
a = np.arange(12).reshape(3,4)
print ('原数组: ')
print (a)
print ('\n')
print ('转置数组: ')
print (a.T)
输出:
原数组:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
转置数组:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
numpy.rollaxis
numpy.rollaxis
函数向后滚动特定的轴到一个特定位置, 格式如下:
numpy.rollaxis(arr, axis, start)
arr
为数组, axis
为要向后滚动的轴, 其它轴的相对位置不会改变.start
默认为零, 表示完整的滚动. 会滚动到特定位置.
import numpy as np # 创建了三维的
ndarray a = np.arange(8).reshape(2,2,2)
print ('原数组: ')
print (a)
print ('获取数组中一个值: ')
print(np.where(a==6))
print(a[1,1,0]) # 6
print ('\n') # 将轴 2 滚动到轴 0(宽度到深度)
print ('调用 rollaxis 函数: ')
b = np.rollaxis(a,2,0)
print (b)
# 查看元素 a[1,1,0], 即 6 的坐标, 变成 [0, 1, 1]
# 最后一个 0 移动到最前面
print(np.where(b==6))
print ('\n') # 将轴 2 滚动到轴 1: (宽度到高度)
print ('调用 rollaxis 函数: ')
c = np.rollaxis(a,2,1)
print (c)
# 查看元素 a[1,1,0], 即 6 的坐标, 变成 [1, 0, 1]
# 最后的 0 和 它前面的 1 对换位置
print(np.where(c==6))
print ('\n')
输出:
原数组:
[[[0 1]
[2 3]]
[[4 5]
[6 7]]]
获取数组中一个值:
(array([1]), array([1]), array([0]))
6
调用 rollaxis 函数:
[[[0 2]
[4 6]]
[[1 3]
[5 7]]]
(array([0]), array([1]), array([1]))
调用 rollaxis 函数:
[[[0 2]
[1 3]]
[[4 6]
[5 7]]]
(array([1]), array([0]), array([1]))
numpy.swapaxes
numpy.swapaxes 函数用于交换数组的两个轴, 格式如下:
numpy.swapaxes(arr, axis1, axis2)
arr
为输入的数组, axis1
为对应第一个轴的整数, axis2
为对应第二个轴的整数.
import numpy as np # 创建了三维的 ndarray
a = np.arange(8).reshape(2,2,2)
print ('原数组: ')
print (a)
print ('\n') # 现在交换轴 0(深度方向)到轴 2(宽度方向)
print ('调用 swapaxes 函数后的数组: ')
print (np.swapaxes(a, 2, 0))
输出:
原数组:
[[[0 1]
[2 3]]
[[4 5]
[6 7]]]
调用 swapaxes 函数后的数组:
[[[0 4]
[2 6]]
[[1 5]
[3 7]]]
修改数组维度
维度 | 描述 |
---|---|
broadcast | 产生模仿广播的对象 |
broadcast_to | 将数组广播到新形状 |
expand_dims | 扩展数组的形状 |
squeeze | 从数组的形状中删除一维条目 |
numpy.broadcast
numpy.broadcast
用于模仿广播的对象, 它返回一个对象, 该对象封装了将一个数组广播到另一个数组的结果.
该函数使用两个数组作为输入参数, 如下:
import numpy as np
x = np.array([[1], [2], [3]])
y = np.array([4, 5, 6])
# 对 y 广播 x
b = np.broadcast(x,y)
# 它拥有 iterator 属性, 基于自身组件的迭代器元组
print ('对 y 广播 x: ')
r,c = b.iters
# Python3.x 为 next(context) , Python2.x 为 context.next()
print (next(r), next(c))
print (next(r), next(c))
print ('\n')
# shape 属性返回广播对象的形状
print ('广播对象的形状: ')
print (b.shape)
print ('\n')
# 手动使用 broadcast 将 x 与 y 相加
b = np.broadcast(x,y)
c = np.empty(b.shape)
print ('手动使用 broadcast 将 x 与 y 相加: ')
print (c.shape)
print ('\n')
c.flat = [u + v for (u,v) in b]
print ('调用 flat 函数: ')
print (c)
print ('\n')
# 获得了和 NumPy 内建的广播支持相同的结果
print ('x 与 y 的和: ')
print (x + y)
输出结果为:
对 y 广播 x:
1 4
1 5
广播对象的形状:
(3, 3)
手动使用 broadcast 将 x 与 y 相加:
(3, 3)
调用 flat 函数:
[[5. 6. 7.]
[6. 7. 8.]
[7. 8. 9.]]
x 与 y 的和:
[[5 6 7]
[6 7 8]
[7 8 9]]
numpy.broadcast_to
numpy.broadcast_to
函数将数组广播到新形状. 它在原始数组上返回只读视图. 它通常不连续. 如果新形状不符合 NumPy 的广播规则, 该函数可能会抛出ValueError.
numpy.broadcast_to(array, shape, subok)
import numpy as np
a = np.arange(4).reshape(1,4)
print ('原数组: ')
print (a)
print ('\n')
print ('调用 broadcast_to 函数之后: ')
print (np.broadcast_to(a,(4,4)))
输出:
原数组:
[[0 1 2 3]]
调用 broadcast_to 函数之后:
[[0 1 2 3]
[0 1 2 3]
[0 1 2 3]
[0 1 2 3]]
numpy.expand_dims
numpy.expand_dims
函数通过在指定位置插入新的轴来扩展数组形状, 函数格式如下:
numpy.expand_dims(arr, axis)
arr
为输入数组,axis
为新轴插入的位置.
import numpy as np
x = np.array(([1,2],[3,4]))
print ('数组 x: ')
print (x) print ('\n') y = np.expand_dims(x, axis = 0) print ('数组 y: ') print (y) print ('\n') print ('数组 x 和 y 的形状: ') print (x.shape, y.shape) print ('\n') # 在位置 1 插入轴 y = np.expand_dims(x, axis = 1) print ('在位置 1 插入轴之后的数组 y: ') print (y) print ('\n') print ('x.ndim 和 y.ndim: ') print (x.ndim,y.ndim) print ('\n') print ('x.shape 和 y.shape: ') print (x.shape, y.shape)
输出:
数组 x:
[[1 2]
[3 4]]
数组 y:
[[[1 2]
[3 4]]]
数组 x 和 y 的形状:
(2, 2) (1, 2, 2)
在位置 1 插入轴之后的数组 y:
[[[1 2]]
[[3 4]]]
x.ndim 和 y.ndim:
2 3
x.shape 和 y.shape:
(2, 2) (2, 1, 2)
numpy.squeeze
numpy.squeeze
函数从给定数组的形状中删除一维的条目, 函数格式如下:
numpy.squeeze(arr, axis)
arr
为输入数组,axis
: 整数或整数元组, 用于选择形状中一维条目的子集.
import numpy as np
x = np.arange(9).reshape(1,3,3)
print ('数组 x: ')
print (x)
print ('\n')
y = np.squeeze(x)
print ('数组 y: ')
print (y)
print ('\n')
print ('数组 x 和 y 的形状: ')
print (x.shape, y.shape)=
输出:
数组 x:
[[[0 1 2]
[3 4 5]
[6 7 8]]]
数组 y:
[[0 1 2]
[3 4 5]
[6 7 8]]
数组 x 和 y 的形状:
(1, 3, 3) (3, 3)
连接数组
函数 | 描述 |
---|---|
concatenate | 连接沿现有轴的数组序列 |
stack | 沿着新的轴加入一系列数组. |
hstack | 水平堆叠序列中的数组(列方向) |
vstack | 竖直堆叠序列中的数组(行方向) |
numpy.concatenate
numpy.concatenate
函数用于沿指定轴连接相同形状的两个或多个数组, 格式如下:
numpy.concatenate((a1, a2, ...), axis)
a1, a2, ...
为相同类型的数组,axis
为沿着它连接数组的轴, 默认为 0.
import numpy as np
a = np.array([[1,2],[3,4]])
print ('第一个数组: ')
print (a)
print ('\n')
b = np.array([[5,6],[7,8]])
print ('第二个数组: ')
print (b)
print ('\n') # 两个数组的维度相同
print ('沿轴 0 连接两个数组: ')
print (np.concatenate((a,b)))
print ('\n')
print ('沿轴 1 连接两个数组: ')
print (np.concatenate((a,b),axis = 1))
输出:
第一个数组:
[[1 2]
[3 4]]
第二个数组:
[[5 6]
[7 8]]
沿轴 0 连接两个数组:
[[1 2]
[3 4]
[5 6]
[7 8]]
沿轴 1 连接两个数组:
[[1 2 5 6]
[3 4 7 8]]
numpy.stack
numpy.stack
函数用于沿新轴连接数组序列, 格式如下:
numpy.stack(arrays, axis)
arrays
为相同形状的数组序列, axis
为返回数组中的轴, 输入数组沿着它来堆叠
import numpy as np
a = np.array([[1,2],[3,4]])
print ('第一个数组: ')
print (a)
print ('\n')
b = np.array([[5,6],[7,8]])
print ('第二个数组: ')
print (b)
print ('\n')
print ('沿轴 0 堆叠两个数组: ')
print (np.stack((a,b),0))
print ('\n')
print ('沿轴 1 堆叠两个数组: ')
print (np.stack((a,b),1))
输出:
第一个数组:
[[1 2]
[3 4]]
第二个数组:
[[5 6]
[7 8]]
沿轴 0 堆叠两个数组:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
沿轴 1 堆叠两个数组:
[[[1 2]
[5 6]]
[[3 4]
[7 8]]]
numpy.hstack
numpy.hstack
是 numpy.stack
函数的变体, 它通过水平堆叠来生成数组.
import numpy as np
a = np.array([[1,2],[3,4]])
print ('第一个数组: ')
print (a)
print ('\n')
b = np.array([[5,6],[7,8]])
print ('第二个数组: ')
print (b)
print ('\n')
print ('水平堆叠: ')
c = np.hstack((a,b))
print (c)
print ('\n')
输出:
第一个数组:
[[1 2]
[3 4]]
第二个数组:
[[5 6]
[7 8]]
水平堆叠:
[[1 2 5 6]
[3 4 7 8]]
numpy.vstack
numpy.vstack
是 numpy.stack
函数的变体, 它通过垂直堆叠来生成数组.
import numpy as np
a = np.array([[1,2],[3,4]])
print ('第一个数组: ')
print (a)
print ('\n')
b = np.array([[5,6],[7,8]])
print ('第二个数组: ')
print (b)
print ('\n')
print ('竖直堆叠: ')
c = np.vstack((a,b))
print (c)
输出:
第一个数组:
[[1 2]
[3 4]]
第二个数组:
[[5 6]
[7 8]]
竖直堆叠:
[[1 2]
[3 4]
[5 6]
[7 8]]
分割数组
函数 | 数组及操作 |
---|---|
split | 将一个数组分割为多个子数组 |
hsplit | 将一个数组水平分割为多个子数组(按列) |
vsplit | 将一个数组垂直分割为多个子数组(按行) |
numpy.split
numpy.split
函数沿特定的轴将数组分割为子数组, 格式如下:
numpy.split(ary, indices_or_sections, axis)
ary
为被分割的数组.indices_or_sections
是可选参数, 如果是一个整数, 就用该数平均切分, 如果是一个数组, 为沿轴切分的位置(左开右闭).axis
设置沿着哪个方向进行切分, 默认为 0, 横向切分, 即水平方向. 为 1 时, 纵向切分, 即竖直方向.
import numpy as np a = np.arange(9) print ('第一个数组: ') print (a) print ('\n') print ('将数组分为三个大小相等的子数组: ') b = np.split(a,3) print (b) print ('\n') print ('将数组在一维数组中表明的位置分割: ') b = np.split(a,[4,7]) print (b)
输出:
第一个数组:
[0 1 2 3 4 5 6 7 8]
将数组分为三个大小相等的子数组:
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
将数组在一维数组中表明的位置分割:
[array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8])]
axis 为 0 时在水平方向分割, axis 为 1 时在垂直方向分割:
import numpy as np
a = np.arange(16).reshape(4, 4)
print('第一个数组: ')
print(a)
print('\n')
print('默认分割(0轴): ')
b = np.split(a,2)
print(b)
print('\n')
print('沿水平方向分割: ')
c = np.split(a,2,1)
print(c)
print('\n')
print('沿水平方向分割: ')
d= np.hsplit(a,2)
print(d)
输出:
第一个数组:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
默认分割(0轴):
[array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])]
沿水平方向分割:
[array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]]), array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])]
沿水平方向分割:
[array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]]), array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])]
numpy.hsplit
numpy.hsplit
函数用于水平分割数组, 通过指定要返回的相同形状的数组数量来拆分原数组.
import numpy as np
harr = np.floor(10 * np.random.random((2, 6)))
print ('原array: ')
print(harr)
print ('拆分后: ')
print(np.hsplit(harr, 3))
输出:
原array:
[[4. 7. 6. 3. 2. 6.]
[6. 3. 6. 7. 9. 7.]]
拆分后:
[array([[4., 7.],
[6., 3.]]), array([[6., 3.],
[6., 7.]]), array([[2., 6.],
[9., 7.]])]
numpy.vsplit
numpy.vsplit 沿着垂直轴分割, 其分割方式与hsplit用法相同.
import numpy as np
a = np.arange(16).reshape(4,4)
print ('第一个数组: ')
print (a)
print ('\n')
print ('竖直分割: ')
b = np.vsplit(a,2)
print (b)
输出:
第一个数组:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
竖直分割:
[array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])]
数组元素的添加与删除
函数 | 元素及描述 |
---|---|
resize | 返回指定形状的新数组 |
append | 将值添加到数组末尾 |
insert | 沿指定轴将值插入到指定下标之前 |
delete | 删掉某个轴的子数组, 并返回删除后的新数组 |
unique | 查找数组内的唯一元素 |
numpy.resize
numpy.resize
函数返回指定大小的新数组. 如果新数组大小大于原始大小, 则包含原始数组中的元素的副本.
numpy.resize(arr, shape)
arr
为要修改大小的数组.shape
返回数组的新形状
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print ('第一个数组: ')
print (a)
print ('\n')
print ('第一个数组的形状: ')
print (a.shape)
print ('\n')
b = np.resize(a, (3,2))
print ('第二个数组: ')
print (b)
print ('\n')
print ('第二个数组的形状: ')
print (b.shape)
print ('\n') # 注意 a 的第一行在 b 中重复出现, 因为尺寸变大了
print ('修改第二个数组的大小: ')
b = np.resize(a,(3,3))
print (b)
输出:
第一个数组:
[[1 2 3]
[4 5 6]]
第一个数组的形状:
(2, 3)
第二个数组:
[[1 2]
[3 4]
[5 6]]
第二个数组的形状:
(3, 2)
修改第二个数组的大小:
[[1 2 3]
[4 5 6]
[1 2 3]]
numpy.append
numpy.append
函数在数组的末尾添加值. 追加操作会分配整个数组, 并把原来的数组复制到新数组中. 此外, 输入数组的维度必须匹配否则将生成ValueError. append
函数返回的始终是一个一维数组.
numpy.append(arr, values, axis=None)
arr
为输入数组, values
为要向arr
添加的值, 需要和arr
形状相同( 除了要添加的轴). axis
默认为 None. 当axis无定义时, 是横向加成, 返回总是为一维数组. 当axis有定义的时候, 分别为0和1的时候. 当axis有定义的时候, 分别为0和1的时候(列数要相同). 当axis为1时, 数组是加在右边(行数要相同).
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print ('第一个数组: ')
print (a)
print ('\n')
print ('向数组添加元素: ')
print (np.append(a, [7,8,9]))
print ('\n')
print ('沿轴 0 添加元素: ')
print (np.append(a, [[7,8,9]],axis = 0))
print ('\n')
print ('沿轴 1 添加元素: ')
print (np.append(a, [[5,5,5],[7,8,9]],axis = 1))
输出:
第一个数组:
[[1 2 3]
[4 5 6]]
向数组添加元素:
[1 2 3 4 5 6 7 8 9]
沿轴 0 添加元素:
[[1 2 3]
[4 5 6]
[7 8 9]]
沿轴 1 添加元素:
[[1 2 3 5 5 5]
[4 5 6 7 8 9]]
numpy.insert
numpy.insert
函数在给定索引之前, 沿给定轴在输入数组中插入值. 函数会在指定位置(或位置数组)插入给定的值或数组, 然后返回新的数组. 被插入的元素可以是标量值, 也可以是数组. 需要注意的是, 插入操作会返回一个新的数组, 而不会改变原始数组.
numpy.insert(arr, obj, values, axis)
arr
为 输入数组. obj
为在其之前插入值的索引. values
为要插入的值. axis
为沿着它插入的轴, 如果未提供, 则输入数组会被展开.
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print ('第一个数组: ')
print (a)
print ('\n')
print ('未传递 Axis 参数. 在删除之前输入数组会被展开. ')
print (np.insert(a,3,[11,12]))
print ('\n')
print ('传递了 Axis 参数. 会广播值数组来配输入数组. ')
print ('沿轴 0 广播: ')
print (np.insert(a,1,[11],axis = 0))
print ('\n')
print ('沿轴 1 广播: ')
print (np.insert(a,1,11,axis = 1))
输出:
第一个数组:
[[1 2]
[3 4]
[5 6]]
未传递 Axis 参数. 在删除之前输入数组会被展开.
[ 1 2 3 11 12 4 5 6]
传递了 Axis 参数. 会广播值数组来配输入数组.
沿轴 0 广播:
[[ 1 2]
[11 11]
[ 3 4]
[ 5 6]]
沿轴 1 广播:
[[ 1 11 2]
[ 3 11 4]
[ 5 11 6]]
numpy.delete
numpy.delete
函数返回从输入数组中删除指定子数组的新数组. 与 insert()
函数的情况一样, 如果未提供轴参数, 则输入数组将展开.
Numpy.delete(arr, obj, axis)
arr
为输入数组. obj
表明要从输入数组删除的子数组, 可以被切片, 整数或者整数数组. axis
: 沿着它删除给定子数组的轴, 如果未提供, 则输入数组会被展开.
import numpy as np
a = np.arange(12).reshape(3,4)
print ('第一个数组: ')
print (a)
print ('\n')
print ('未传递 Axis 参数. 在插入之前输入数组会被展开. ')
print (np.delete(a,5))
print ('\n')
print ('删除第二列: ')
print (np.delete(a,1,axis = 1))
print ('\n')
print ('包含从数组中删除的替代值的切片: ')
a = np.array([1,2,3,4,5,6,7,8,9,10])
print (np.delete(a, np.s_[::2]))
输出:
第一个数组:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
未传递 Axis 参数. 在插入之前输入数组会被展开.
[ 0 1 2 3 4 6 7 8 9 10 11]
删除第二列:
[[ 0 2 3]
[ 4 6 7]
[ 8 10 11]]
包含从数组中删除的替代值的切片:
[ 2 4 6 8 10]
numpy.unique
numpy.unique
函数用于去除数组中的重复元素.
numpy.unique(arr, return_index, return_inverse, return_counts)
arr
为输入数组, 如果不是一维数组则会展开.return_index
如果为true
, 返回新列表元素在旧列表中的位置(下标), 并以列表形式储存.return_inverse
如果为true
, 返回旧列表元素在新列表中的位置(下标), 并以列表形式储存. return_counts
如果为true
, 返回去重数组中的元素在原数组中的出现次数.
import numpy as np
a = np.array([5,2,6,2,7,5,6,8,2,9])
print ('第一个数组: ')
print (a)
print ('\n')
print ('第一个数组的去重值: ')
u = np.unique(a)
print (u)
print ('\n')
print ('去重数组的索引数组: ')
u,indices = np.unique(a, return_index = True)
print (indices)
print ('\n')
print ('我们可以看到每个和原数组下标对应的数值: ')
print (a)
print ('\n')
print ('去重数组的下标: ')
u,indices = np.unique(a,return_inverse = True)
print (u)
print ('\n')
print ('下标为: ')
print (indices)
print ('\n')
print ('使用下标重构原数组: ')
print (u[indices])
print ('\n')
print ('返回去重元素的重复数量: ')
u,indices = np.unique(a,return_counts = True)
print (u)
print (indices)
输出:
第一个数组:
[5 2 6 2 7 5 6 8 2 9]
第一个数组的去重值:
[2 5 6 7 8 9]
去重数组的索引数组:
[1 0 2 4 7 9]
我们可以看到每个和原数组下标对应的数值:
[5 2 6 2 7 5 6 8 2 9]
去重数组的下标:
[2 5 6 7 8 9]
下标为:
[1 0 2 0 3 1 2 4 0 5]
使用下标重构原数组:
[5 2 6 2 7 5 6 8 2 9]
返回去重元素的重复数量:
[2 5 6 7 8 9]
[3 2 2 1 1 1]
arcsin, arccos, 和 arctan 函数返回给定角度的 sin, cos 和 tan 的反三角函数.
这些函数的结果可以通过 numpy.degrees()
函数将弧度转换为角度.
import numpy as np
a = np.array([0,30,45,60,90])
print ('含有正弦值的数组: ')
sin = np.sin(a*np.pi/180)
print (sin)
print ('\n')
print ('计算角度的反正弦, 返回值以弧度为单位: ')
inv = np.arcsin(sin)
print (inv)
print ('\n')
print ('通过转化为角度制来检查结果: ')
print (np.degrees(inv))
print ('\n')
print ('arccos 和 arctan 函数行为类似: ')
cos = np.cos(a*np.pi/180)
print (cos)
print ('\n')
print ('反余弦: ')
inv = np.arccos(cos)
print (inv)
print ('\n')
print ('角度制单位: ')
print (np.degrees(inv))
print ('\n')
print ('tan 函数: ')
tan = np.tan(a*np.pi/180)
print (tan)
print ('\n')
print ('反正切: ')
inv = np.arctan(tan)
print (inv)
print ('\n')
print ('角度制单位: ')
print (np.degrees(inv))
输出:
含有正弦值的数组:
[0. 0.5 0.70710678 0.8660254 1. ]
计算角度的反正弦, 返回值以弧度为单位:
[0. 0.52359878 0.78539816 1.04719755 1.57079633]
通过转化为角度制来检查结果:
[ 0. 30. 45. 60. 90.]
arccos 和 arctan 函数行为类似:
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]
反余弦:
[0. 0.52359878 0.78539816 1.04719755 1.57079633]
角度制单位:
[ 0. 30. 45. 60. 90.]
tan 函数:
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]
反正切:
[0. 0.52359878 0.78539816 1.04719755 1.57079633]
角度制单位:
[ 0. 30. 45. 60. 90.]
舍入函数
numpy.around() 函数返回指定数字的四舍五入值.
numpy.around(a,decimals)
a为数组, decimals为舍入的小数位数. 默认值为0. 如果为负, 整数将四舍五入到小数点左侧的位置
import numpy as np
a = np.array([1.0,5.55, 123, 0.567, 25.532])
print ('原数组: ')
print (a)
print ('\n')
print ('舍入后: ')
print (np.around(a))
print (np.around(a, decimals = 1))
print (np.around(a, decimals = -1))
输出:
原数组:
[ 1. 5.55 123. 0.567 25.532]
舍入后:
[ 1. 6. 123. 1. 26.]
[ 1. 5.6 123. 0.6 25.5]
[ 0. 10. 120. 0. 30.]
numpy.floor()
numpy.floor()
返回小于或者等于指定表达式的最大整数, 即向下取整.
import numpy as np
a = np.array([-1.7, 1.5, -0.2, 0.6, 10])
print ('提供的数组: ')
print (a)
print ('\n')
print ('修改后的数组: ')
print (np.floor(a))
输出结果为:
提供的数组:
[-1.7 1.5 -0.2 0.6 10. ]
修改后的数组:
[-2. 1. -1. 0. 10.]
numpy.ceil()
numpy.ceil()
返回大于或者等于指定表达式的最小整数, 即向上取整.
import numpy as np
a = np.array([-1.7, 1.5, -0.2, 0.6, 10])
print ('提供的数组: ')
print (a)
print ('\n')
print ('修改后的数组: ')
print (np.ceil(a))
输出:
提供的数组:
[-1.7 1.5 -0.2 0.6 10. ]
修改后的数组:
[-1. 2. -0. 1. 10.]
NumPy 位运算
位运算是一种在二进制数字的位级别上进行操作的一类运算, 它们直接操作二进制数字的各个位, 而不考虑数字的整体值.
NumPy 提供了一系列位运算函数, 允许对数组中的元素进行逐位操作, 这些操作与 Python 的位运算符类似, 但作用于 NumPy 数组, 支持矢量化处理, 性能更高. 位运算在计算机科学中广泛应用于优化和处理底层数据.
NumPy bitwise_
开头的函数是位运算函数.
NumPy 位运算包括以下几个函数:
操作 | 函数/运算符 | 描述 |
---|---|---|
按位与 | numpy.bitwise_and(x1, x2) | 对数组的每个元素执行逐位与操作. |
按位或 | numpy.bitwise_or(x1, x2) | 对数组的每个元素执行逐位或操作. |
按位异或 | numpy.bitwise_xor(x1, x2) | 对数组的每个元素执行逐位异或操作. |
按位取反 | numpy.invert(x) | 对数组的每个元素执行逐位取反(按位非). |
左移 | numpy.left_shift(x1, x2) | 将数组的每个元素左移指定的位数. |
右移 | numpy.right_shift(x1, x2) | 将数组的每个元素右移指定的位数. |
import numpy as np
arr1 = np.array([True, False, True], dtype=bool)
arr2 = np.array([False, True, False], dtype=bool)
result_and = np.bitwise_and(arr1, arr2)
result_or = np.bitwise_or(arr1, arr2)
result_xor = np.bitwise_xor(arr1, arr2)
result_not = np.bitwise_not(arr1)
print("AND:", result_and) # [False, False, False]
print("OR:", result_or) # [True, True, True]
print("XOR:", result_xor) # [True, True, True]
print("NOT:", result_not) # [False, True, False]
# 按位取反
arr_invert = np.invert(np.array([1, 2], dtype=np.int8))
print("Invert:", arr_invert) # [-2, -3]
# 左移位运算
arr_left_shift = np.left_shift(5, 2)
print("Left Shift:", arr_left_shift) # 20
# 右移位运算
arr_right_shift = np.right_shift(10, 1)
print("Right Shift:", arr_right_shift) # 5
也可以使用 &
, ~
, |
和 ^
等操作符进行计算:
- **与运算(&): ** 对应位上的两个数字都为1时, 结果为1;否则, 结果为0. 例如: 1010 & 1100 = 1000
- **或运算(|): ** 对应位上的两个数字有一个为1时, 结果为1;否则, 结果为0. 例如: 1010 | 1100 = 1110
- **异或运算(^): ** 对应位上的两个数字相异时, 结果为1;相同时, 结果为0. 例如: 1010 ^ 1100 = 0110
- **取反运算(~): ** 对数字的每个位取反, 即0变为1, 1变为0. 例如: ~1010 = 0101
- **左移运算(<<): ** 将数字的所有位向左移动指定的位数, 右侧用0填充. 例如: 1010 << 2 = 101000
- **右移运算(>>): ** 将数字的所有位向右移动指定的位数, 左侧根据符号位或补零. 例如: 1010 >> 2 = 0010
bitwise_and
bitwise_and()
函数对数组中整数的二进制形式执行位与运算.
import numpy as np
print ('13 和 17 的二进制形式: ')
a,b = 13,17
print (bin(a), bin(b))
print ('\n')
print ('13 和 17 的位与: ')
print (np.bitwise_and(13, 17))
输出:
13 和 17 的二进制形式:
0b1101 0b10001
13 和 17 的位与:
1
位与操作运算规律如下:
A | B | AND |
---|---|---|
1 | 1 | 1 |
1 | 0 | 0 |
0 | 1 | 0 |
0 | 0 | 0 |
bitwise_or
bitwise_or()
函数对数组中整数的二进制形式执行位或运算.
import numpy as np
a,b = 13,17
print ('13 和 17 的二进制形式: ')
print (bin(a), bin(b))
print ('13 和 17 的位或: ')
print (np.bitwise_or(13, 17))
输出:
13 和 17 的二进制形式:
0b1101 0b10001
13 和 17 的位或:
29
位或操作运算规律如下:
A | B | OR |
---|---|---|
1 | 1 | 1 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
invert
invert()
函数对数组中整数进行位取反运算, 即 0 变成 1, 1 变成 0.
对于有符号整数, 取该二进制数的补码, 然后 +1. 二进制数, 最高位为0表示正数, 最高位为 1 表示负数.
看看 ~1 的计算步骤:
- 将
1
(这里叫: 原码)转二进制 =00000001
- 按位取反 =
11111110
- 发现符号位(即最高位)为
1
(表示负数), 将除符号位之外的其他数字取反 =10000001
- 末位加1取其补码 =
10000010
- 转换回十进制 =
-2
表达式 | 二进制值(2 的补数) | 十进制值 |
---|---|---|
5 | 00000000 00000000 00000000 00000101 | 5 |
~5 | 11111111 11111111 11111111 11111010 | -6 |
import numpy as np
print ('13 的位反转, 其中 ndarray 的 dtype 是 uint8: ')
print (np.invert(np.array([13], dtype = np.uint8)))
print ('\n')
# 比较 13 和 242 的二进制表示, 我们发现了位的反转
print ('13 的二进制表示: ')
print (np.binary_repr(13, width = 8))
print ('\n')
print ('242 的二进制表示: ')
print (np.binary_repr(242, width = 8))
输出:
13 的位反转, 其中 ndarray 的 dtype 是 uint8:
[242]
13 的二进制表示:
00001101
242 的二进制表示:
11110010
left_shift
left_shift()
函数将数组元素的二进制形式向左移动到指定位置, 右侧附加相等数量的 0.
import numpy as np
print ('将 10 左移两位: ')
print (np.left_shift(10,2))
print ('\n')
print ('10 的二进制表示: ')
print (np.binary_repr(10, width = 8))
print ('\n')
print ('40 的二进制表示: ')
print (np.binary_repr(40, width = 8))
# '00001010' 中的两位移动到了左边, 并在右边添加了两个 0.
输出:
将 10 左移两位:
40
10 的二进制表示:
00001010
40 的二进制表示:
00101000
right_shift
right_shift()
函数将数组元素的二进制形式向右移动到指定位置, 左侧附加相等数量的 0.
import numpy as np
print ('将 40 右移两位: ')
print (np.right_shift(40,2))
print ('\n')
print ('40 的二进制表示: ')
print (np.binary_repr(40, width = 8))
print ('\n')
print ('10 的二进制表示: ')
print (np.binary_repr(10, width = 8))
# '00001010' 中的两位移动到了右边, 并在左边添加了两个 0.
输出结果为:
将 40 右移两位:
10
40 的二进制表示:
00101000
10 的二进制表示:
00001010
NumPy 字符串函数
以下函数用于对 dtype 为 numpy.string_
或 numpy.unicode_
的数组执行向量化字符串操作.
它们基于 Python 内置库中的标准字符串函数. 这些函数在字符数组类(numpy.char)中定义.
函数 | 描述 |
---|---|
add() | 对两个数组的逐个字符串元素进行连接 |
multiply() | 返回按元素多重连接后的字符串 |
center() | 居中字符串 |
capitalize() | 将字符串第一个字母转换为大写 |
title() | 将字符串的每个单词的第一个字母转换为大写 |
lower() | 数组元素转换为小写 |
upper() | 数组元素转换为大写 |
split() | 指定分隔符对字符串进行分割, 并返回数组列表 |
splitlines() | 返回元素中的行列表, 以换行符分割 |
strip() | 移除元素开头或者结尾处的特定字符 |
join() | 通过指定分隔符来连接数组中的元素 |
replace() | 使用新字符串替换字符串中的所有子字符串 |
decode() | 数组元素依次调用str.decode |
encode() | 数组元素依次调用str.encode |
numpy.char.add()
numpy.char.add()
函数依次对两个数组的元素进行字符串连接.
import numpy as np
print ('连接两个字符串: ')
print (np.char.add(['hello'],[' xyz']))
print ('\n') print ('连接示例: ')
print (np.char.add(['hello', 'hi'],[' abc', ' xyz']))
输出结果为:
连接两个字符串:
['hello xyz']
连接示例:
['hello abc' 'hi xyz']
numpy.char.multiply()
numpy.char.multiply()
函数执行多重连接.
import numpy as np
print (np.char.multiply('Shiqi ',3))
#输出Shiqi Shiqi Shiqi
numpy.char.center()
numpy.char.center()
函数用于将字符串居中, 并使用指定字符在左侧和右侧进行填充.
np.char.center(str , width,fillchar)
str
为字符串, width
为长度,fillchar
为填充字符
import numpy as np
print (np.char.center('Shiqi', 20,fillchar = '*'))
#输出*******Shiqi********
numpy.char.capitalize()
numpy.char.capitalize()
函数将字符串的第一个字母转换为大写:
import numpy as np
print (np.char.capitalize('shiqi'))
#输出Shiqi
numpy.char.title()
numpy.char.title()
函数将字符串的每个单词的第一个字母转换为大写:
import numpy as np
print (np.char.title('i like shiqi'))
#输出I Like Shiqi
numpy.char.lower()
numpy.char.lower()
函数对数组的每个元素转换为小写. 它对每个元素调用 str.lower.
import numpy as np
#操作数组
print (np.char.lower(['SHIQI','PYTHON']))
# 操作字符串
print (np.char.lower('SHIQI'))
输出:
['shiqi' 'python']
shiqi
numpy.char.upper()
numpy.char.upper()
函数对数组的每个元素转换为大写. 它对每个元素调用 str.upper.
import numpy as np
#操作数组
print (np.char.upper(['shiqi','python']))
# 操作字符串
print (np.char.upper('python'))
输出:
['SHIQI' 'PYTHON']
PYTHON
numpy.char.split()
numpy.char.split()
通过指定分隔符对字符串进行分割, 并返回数组. 默认情况下, 分隔符为空格.
import numpy as np
# 分隔符默认为空格
print (np.char.split ('i like shiqi?')) # 分隔符为 .
print (np.char.split ('www.shiqi.top', sep = '.'))
输出:
['i', 'like', 'shiqi?']
['www', 'shiqi', 'top']
numpy.char.splitlines()
numpy.char.splitlines()
函数以换行符作为分隔符来分割字符串, 并返回数组.
import numpy as np
# 换行符 \n
print (np.char.splitlines('i\nlike shiqi?'))
print (np.char.splitlines('i\rlike shiqi?'))
输出:
['i', 'like shiqi?']
['i', 'like shiqi?']
\n
, \r
, \r\n
都可用作换行符.
numpy.char.strip()
numpy.char.strip()
函数用于移除开头或结尾处的特定字符.
import numpy as np
# 移除字符串头尾的 a 字符
print (np.char.strip('ashok ashiqia','a'))
# 移除数组元素头尾的 a 字符
print (np.char.strip(['ashiqia','admin','java'],'a'))
输出:
shok ashiqi
['shiqi' 'dmin' 'jav']
numpy.char.join()
numpy.char.join()
函数通过指定分隔符来连接数组中的元素或字符串
import numpy as np
# 操作字符串
print (np.char.join(':','shiqi'))
# 指定多个分隔符操作数组元素
print (np.char.join([':','-'],['shiqi','python']))
输出:
s:h:i:q:i
['s:h:i:q:i' 'p-y-t-h-o-n']
numpy.char.replace()
numpy.char.replace()
函数使用新字符串替换字符串中的所有子字符串.
import numpy as np
print (np.char.replace ('i like shiqi', 'i', 'c'))
输出:
c lcke shcqc
numpy.char.encode()
numpy.char.encode()
函数对数组中的每个元素调用 str.encode
函数. 默认编码是 utf-8, 可以使用标准 Python 库中的编解码器.
import numpy as np
a = np.char.encode('shiqi', 'cp500')
print (a)
输出:
np.bytes_(b'\xa2\x88\x89\x98\x89')
numpy.char.decode()
numpy.char.decode()
函数对编码的元素进行 str.decode()
解码.
import numpy as np
a = np.char.encode('shiqi', 'cp500')
print (a)
print (np.char.decode(a,'cp500'))
输出:
np.bytes_(b'\xa2\x88\x89\x98\x89')
shiqi
NumPy 数学函数
NumPy 包含大量的各种数学运算的函数, 包括三角函数, 算术运算的函数, 复数处理函数等.
三角函数
NumPy 提供了标准的三角函数: sin()
、cos()
、tan()
.
import numpy as np
a = np.array([0,30,45,60,90])
print ('不同角度的正弦值: ') # 通过乘 pi/180 转化为弧度
print (np.sin(a*np.pi/180))
print ('\n')
print ('数组中角度的余弦值: ')
print (np.cos(a*np.pi/180))
print ('\n')
print ('数组中角度的正切值: ')
print (np.tan(a*np.pi/180))
输出:
不同角度的正弦值:
[0. 0.5 0.70710678 0.8660254 1. ]
数组中角度的余弦值:
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]
数组中角度的正切值:
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]
NumPy 算术函数
NumPy 算术函数包含简单的加减乘除: add()
, subtract()
, multiply()
和 divide()
.
数组必须具有相同的形状或符合数组广播规则.
import numpy as np
a = np.arange(9, dtype = np.float_).reshape(3,3)
print ('第一个数组: ')
print (a)
print ('\n')
print ('第二个数组: ')
b = np.array([10,10,10])
print (b) print ('\n')
print ('两个数组相加: ')
print (np.add(a,b))
print ('\n')
print ('两个数组相减: ')
print (np.subtract(a,b))
print ('\n')
print ('两个数组相乘: ')
print (np.multiply(a,b))
print ('\n')
print ('两个数组相除: ')
print (np.divide(a,b))
输出:
第一个数组:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
第二个数组:
[10 10 10]
两个数组相加:
[[10. 11. 12.]
[13. 14. 15.]
[16. 17. 18.]]
两个数组相减:
[[-10. -9. -8.]
[ -7. -6. -5.]
[ -4. -3. -2.]]
两个数组相乘:
[[ 0. 10. 20.]
[30. 40. 50.]
[60. 70. 80.]]
两个数组相除:
[[0. 0.1 0.2]
[0.3 0.4 0.5]
[0.6 0.7 0.8]]
此外 Numpy 也包含了其他重要的算术函数.
numpy.reciprocal()
numpy.reciprocal()
函数返回参数逐元素的倒数. 如 1/4 倒数为 4/1.
import numpy as np a = np.array([0.25, 1.33, 1, 100]) print ('我们的数组是: ') print (a) print ('\n') print ('调用 reciprocal 函数: ') print (np.reciprocal(a))
输出:
我们的数组是:
[ 0.25 1.33 1. 100. ]
调用 reciprocal 函数:
[4. 0.7518797 1. 0.01 ]
numpy.power()
numpy.power()
函数将第一个输入数组中的元素作为底数, 计算它与第二个输入数组中相应元素的幂.
import numpy as np
a = np.array([10,100,1000])
print ('我们的数组是;')
print (a)
print ('\n')
print ('调用 power 函数: ')
print (np.power(a,2))
print ('\n')
print ('第二个数组: ')
b = np.array([1,2,3])
print (b)
print ('\n')
print ('再次调用 power 函数: ')
print (np.power(a,b))
输出:
我们的数组是;
[ 10 100 1000]
调用 power 函数:
[ 100 10000 1000000]
第二个数组:
[1 2 3]
再次调用 power 函数:
[ 10 10000 1000000000]
numpy.mod()
numpy.mod()
计算输入数组中相应元素的相除后的余数. 函数numpy.remainder()
也产生相同的结果.
import numpy as np
a = np.array([10,20,30])
b = np.array([3,5,7])
print ('第一个数组: ')
print (a)
print ('\n')
print ('第二个数组: ')
print (b)
print ('\n')
print ('调用 mod() 函数: ')
print (np.mod(a,b))
print ('\n')
print ('调用 remainder() 函数: ')
print (np.remainder(a,b))
输出:
第一个数组:
[10 20 30]
第二个数组:
[3 5 7]
调用 mod() 函数:
[1 0 2]
调用 remainder() 函数:
[1 0 2]