Numpy Array Manipulation
Numpy contains some functions for processing arrays, which can be roughly divided into the following categories:
- Modify Array Shape
- Flip Array
- Modify Array Dimensions
- Joining Arrays
- Splitting Arrays
- Adding and Removing Array Elements
Modify Array Shape
| Function | Description |
|---|---|
reshape |
Modify the shape without changing the data |
flat |
Array element iterator |
flatten |
Return a copy of the array. Modifications made to the copy will not affect the original array. |
ravel |
Return a flattened array |
numpy.reshape
The numpy.reshape function can modify the shape without changing the data. The format is as follows:
numpy.reshape(arr, newshape, order='C')
arr: The array whose shape is to be modifiednewshape: An integer or an integer array. The new shape should be compatible with the original shape.- order: 'C' -- by row, 'F' -- by column, 'A' -- original order, 'k' -- the order in which elements appear in memory.
Example
The output is as follows:
原始数组: [0 1 2 3 4 5 6 7] 修改后的数组: [[0 1] [2 3] [4 5] [6 7]]
numpy.ndarray.flat
numpy.ndarray.flat is an array element iterator. Example:
Example
The output is as follows:
原始数组: [0 1 2] [3 4 5] [6 7 8] 迭代后的数组: 0 1 2 3 4 5 6 7 8
numpy.ndarray.flatten
numpy.ndarray.flatten returns a copy of the array. Modifications made to the copy will not affect the original array. The format is as follows:
ndarray.flatten(order='C')
Parameter description:
- order: 'C' -- by row, 'F' -- by column, 'A' -- original order, 'K' -- the order in which elements appear in memory.
Example
The output is as follows:
原数组: [[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() flattens array elements, usually in 'C style' order. It returns an array view (view, somewhat similar to a C/C++ reference). Modifications will affect the original array.
This function accepts two parameters:
numpy.ravel(a, order='C')
Parameter description:
- order: 'C' -- by row, 'F' -- by column, 'A' -- original order, 'K' -- the order in which elements appear in memory.
Example
The output is as follows:
原数组: [[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]
Flip Array
| Function | Description |
|---|---|
transpose |
Swap the dimensions of the array |
ndarray.T |
andself.transpose()Same |
rollaxis |
Roll the specified axis backwards |
swapaxes |
Swap two axes of the array |
numpy.transpose
The numpy.transpose function is used to swap the dimensions of an array. The format is as follows:
numpy.transpose(arr, axes)
Parameter description:
arr: The array to be operated onaxes: A list of integers, corresponding to the dimensions. Usually all dimensions are swapped.
Example
The output is as follows:
原数组: [[ 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 is similar to numpy.transpose:
Example
The output is as follows:
原数组: [[ 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
The numpy.rollaxis function rolls the specified axis backwards to a specific position. The format is as follows:
numpy.rollaxis(arr, axis, start)
Parameter description:
arr: Arrayaxis: The axis to be rolled backwards. The relative positions of the other axes will not change.start: Defaults to zero, indicating a full roll. It will roll to a specific position.
Example
The output is as follows:
原数组: [[[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
The numpy.swapaxes function is used to swap two axes of an array. The format is as follows:
numpy.swapaxes(arr, axis1, axis2)
arr: Input arrayaxis1: An integer corresponding to the first axisaxis2: An integer corresponding to the second axis
Example
The output is as follows:
原数组: [[[0 1] [2 3]] [[4 5] [6 7]]] 调用 swapaxes 函数后的数组: [[[0 4] [2 6]] [[1 5] [3 7]]]
Modify Array Dimensions
| Dimension | Description |
|---|---|
broadcast |
Create an object that mimics broadcasting |
broadcast_to |
Broadcast the array to a new shape |
expand_dims |
Expand the shape of the array |
squeeze |
Remove one-dimensional entries from the shape of the array |
numpy.broadcast
numpy.broadcast is an object used to mimic broadcasting. It returns an object that encapsulates the result of broadcasting one array to another.
This function uses two arrays as input parameters, as in the following example:
Example
The output is:
对 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
The numpy.broadcast_to function broadcasts an array to a new shape. It returns a read-only view on the original array. It is usually non-contiguous. If the new shape does not conform to NumPy's broadcasting rules, the function may throw a ValueError.
numpy.broadcast_to(array, shape, subok)
Example
The output is:
原数组: [[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
The numpy.expand_dims function expands the shape of an array by inserting a new axis at a specified position. The function format is as follows:
numpy.expand_dims(arr, axis)
Parameter description:
arr: Input arrayaxis: The position where the new axis is inserted
Example
The output result is:
数组 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
The numpy.squeeze function removes single-dimensional entries from the shape of a given array. The function format is as follows:
numpy.squeeze(arr, axis)
Parameter description:
arr: input arrayaxis: an integer or a tuple of integers, used to select a subset of single-dimensional entries in the shape
Example
The output result is:
数组 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)
Joining Arrays
| Function | Description |
|---|---|
concatenate |
Join a sequence of arrays along an existing axis. |
stack |
Join a sequence of arrays along a new axis. |
hstack |
Stack arrays in sequence horizontally (column direction). |
vstack |
Stack arrays in sequence vertically (row direction). |
numpy.concatenate
The numpy.concatenate function is used to join two or more arrays of the same shape along a specified axis. The format is as follows:
numpy.concatenate((a1, a2, ...), axis)
Parameter description:
a1, a2, ...: arrays of the same typeaxis: the axis along which the arrays are joined, default is 0
Example
The output result is:
第一个数组: [[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
The numpy.stack function is used to join a sequence of arrays along a new axis. The format is as follows:
numpy.stack(arrays, axis)
Parameter description:
arraysA sequence of arrays of the same shapeaxis: the axis in the returned array along which the input arrays are stacked
Example
The output result is as follows:
第一个数组: [[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 is a convenient wrapper of numpy.concatenate, used to horizontally stack arrays along the second axis (axis=1).
numpy.hstack treats one-dimensional arrays as column vectors for concatenation, equivalent to numpy.concatenate([numpy.atleast_1d(arr) for arr in arrays], axis=1) (when all arrays have dimensions ≥2, they are directly concatenated along axis=1).
Example
The output result is as follows:
第一个数组: [[1 2] [3 4]] 第二个数组: [[5 6] [7 8]] 水平堆叠: [[1 2 5 6] [3 4 7 8]]
numpy.vstack
numpy.vstack is a convenient wrapper of numpy.concatenate, used to vertically stack arrays along the first axis (axis=0).
numpy.vstack automatically promotes one-dimensional arrays to two-dimensional row vectors, and then concatenates them vertically, equivalent to numpy.concatenate([numpy.atleast_2d(arr) for arr in arrays], axis=0).
Example
The output result is:
第一个数组: [[1 2] [3 4]] 第二个数组: [[5 6] [7 8]] 竖直堆叠: [[1 2] [3 4] [5 6] [7 8]]
Splitting Arrays
| Function | Array and operation |
|---|---|
split |
Split an array into multiple sub-arrays. |
hsplit |
Split an array horizontally into multiple sub-arrays (column-wise). |
vsplit |
Split an array vertically into multiple sub-arrays (row-wise). |
numpy.split
The numpy.split function splits an array into sub-arrays along a specific axis. The format is as follows:
numpy.split(ary, indices_or_sections, axis)
Parameter description:
ary: the array to be splitindices_or_sections: if it is an integer, the array is split equally by that number; if it is an array, it specifies the positions along the axis at which to split (left-open and right-closed).axis: sets the direction along which to split. The default is 0, horizontal splitting, i.e., the horizontal direction. When it is 1, it is vertical splitting, i.e., the vertical direction.
Example
The output result is:
第一个数组: [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])]
When axis is 0, split in the horizontal direction; when axis is 1, split in the vertical direction:
Example
a = np.arange(16).reshape(4, 4)
print('First array:')
print(a)
print('\n')
print('Default split (axis 0):')
b = np.split(a,2)
print(b)
print('\n')
print('Split along the horizontal direction:')
c = np.split(a,2,1)
print(c)
print('\n')
print('Split along the horizontal direction:')
d= np.hsplit(a,2)
print(d)
The output result is:
第一个数组:
[[ 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
The numpy.hsplit function is used to split an array horizontally by specifying the number of equally shaped arrays to return.
Example
The output result is:
原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 splits along the vertical axis, and its splitting method is the same as the usage of hsplit.
Example
The output result is:
第一个数组:
[[ 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]])]
Adding and Removing Array Elements
| Function | Element and description |
|---|---|
resize |
Return a new array of the specified shape. |
append |
Add values to the end of the array. |
insert |
Insert values before the specified indices along the specified axis. |
delete |
Delete a sub-array along a certain axis and return the new array after deletion. |
unique |
Find the unique elements in an array. |
numpy.resize
The numpy.resize function returns a new array of the specified size.
If the new array is larger than the original size, it contains copies of the elements from the original array.
numpy.resize(arr, shape)
Parameter description:
arr: the array whose size is to be modifiedshape: the new shape of the returned array
Example
The output result is:
第一个数组: [[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
The numpy.append function adds values to the end of an array. The append operation allocates the entire array and copies the original array into the new array. In addition, the dimensions of the input arrays must match; otherwise, a ValueError will be generated.
The append function always returns a one-dimensional array.
numpy.append(arr, values, axis=None)
Parameter description:
arr: input arrayvalues: to be added toarrThe value to be added must bearrthe same shape (except for the axis to be added)axis: default is None. When axis is undefined, it is horizontal appending, and the return is always a one-dimensional array! When axis is defined, it is respectively 0 and 1. When axis is defined, it is respectively 0 and 1 (the number of columns must be the same). When axis is 1, the array is added to the right (the number of rows must be the same).
Example
The output result is:
第一个数组: [[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
The numpy.insert function inserts values into the input array along the given axis before the given indices.
The function inserts the given values or arrays at the specified positions (or array of positions), and then returns a new array. The inserted elements can be scalar values or arrays. Note that the insert operation returns a new array and does not change the original array.
numpy.insert(arr, obj, values, axis)
Parameter description:
arr: input arrayobj: the index before which values are insertedvalues: the values to be insertedaxis: the axis along which to insert; if not provided, the input array is flattened.
Example
The output result is as follows:
第一个数组: [[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
The numpy.delete function returns a new array with the specified sub-array deleted from the input array. As with the insert() function, if the axis parameter is not provided, the input array is flattened.
Numpy.delete(arr, obj, axis)
Parameter description:
arr: input arrayobj: can be a slice, an integer, or an integer array, indicating the sub-array to be deleted from the input array.axis: the axis along which the given sub-array is deleted; if not provided, the input array is flattened.
Example
The output result is:
第一个数组: [[ 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
The numpy.unique function is used to remove duplicate elements from an array.
numpy.unique(arr, return_index, return_inverse, return_counts)
arr: input array; if it is not a one-dimensional array, it will be flattened.return_index: if it istrue, return the positions (indices) of the new list elements in the old list, and store them in list form.return_inverse: if it istrueReturn the positions (indices) of old list elements in the new list, and store them as a list.return_countsIf it istrueReturn the occurrence counts of the elements in the deduplicated array in the original array
Example
The output result is:
第一个数组: [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]Other extensions