Numpy Array Operations
Numpy contains some functions for processing arrays, which can be roughly divided into the following categories:
- Modify array shape
- Transpose arrays
- Modify array dimensions
- Join arrays
- Split arrays
- Add and delete array elements
Modify array shape
| function | Description |
|---|---|
reshape |
Modify shape without changing data |
flat |
Array element iterator |
flatten |
Return a copy of the array; modifications made to the copy do 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 array of integers, 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
import
numpy
as
np
a
=
np
.
arange
(
8
)
(
'
Original array:
'
)
(
a
)
(
'
\n
'
)
b
=
a
.
reshape
(
4
,
2
)
(
'
Modified array:
'
)
(
b
)
The output is as follows:
原始数组:
[0 1 2 3 4 5 6 7]
Modified array:
[[0 1]
[2 3]
[4 5]
[6 7]]
numpy.ndarray.flat
numpy.ndarray.flat is an array element iterator, as shown in the following example:
Example
import
numpy
as
np
a
=
np
.
arange
(
9
)
.
reshape
(
3
,
3
)
(
'
Original array:
'
)
for
row
in
a
:
(
row
)
# To process each element in the array, you can use the flat attribute, which is an array element iterator:
(
'
Array after iteration:
'
)
for
element
in
a
.
flat
:
(
element
)
The output is as follows:
原始数组:
[0 1 2]
[3 4 5]
[6 7 8]
Array after iteration:
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 do 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
import
numpy
as
np
a
=
np
.
arange
(
8
)
.
reshape
(
2
,
4
)
(
'
Original array:
'
)
(
a
)
(
'
\n
'
)
By row by default
(
'
Flattened array:
'
)
(
a
.
flatten
(
)
)
(
'
\n
'
)
(
'
Array flattened in F-style order:
'
)
(
a
.
flatten
(
order
=
'
F
'
)
)
The output is as follows:
原数组:
[[0 1 2 3]
[4 5 6 7]]
Expanded array:
[0 1 2 3 4 5 6 7]
Array expanded in F-style order:
[0 4 1 5 2 6 3 7]
numpy.ravel
numpy.ravel() flattens the array elements, usually in 'C style', and returns a view of the array (view, somewhat similar to a C/C++ reference), so 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
import
numpy
as
np
a
=
np
.
arange
(
8
)
.
reshape
(
2
,
4
)
(
'
Original array:
'
)
(
a
)
(
'
\n
'
)
(
'
After calling the ravel function:
'
)
(
a
.
ravel
(
)
)
(
'
\n
'
)
(
'
After calling the ravel function in F-style order:
'
)
(
a
.
ravel
(
order
=
'
F
'
)
)
The output is as follows:
原数组:
[[0 1 2 3]
[4 5 6 7]]
After calling the ravel function:
[0 1 2 3 4 5 6 7]
After calling the ravel function in F-style order:
[0 4 1 5 2 6 3 7]
Transpose arrays
| function | Description |
|---|---|
transpose |
Transpose the dimensions of an array |
ndarray.T |
and self.transpose() are the same |
rollaxis |
Roll a specified axis backward |
swapaxes |
Swap two axes of an array |
numpy.transpose
The numpy.transpose function is used to transpose the dimensions of an array. The format is as follows:
numpy.transpose(arr, axes)
Parameter description:
arr: the array to operate onaxes: a list of integers corresponding to the dimensions; usually all dimensions are transposed.
Example
import
numpy
as
np
a
=
np
.
arange
(
12
)
.
reshape
(
3
,
4
)
(
'
Original array:
'
)
(
a
)
(
'
\n
'
)
(
'
Transposed array:
'
)
(
np
.
transpose
(
a
)
)
The output is as follows:
Original array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Swap array:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
numpy.ndarray.T is similar to numpy.transpose:
Example
import
numpy
as
np
a
=
np
.
arange
(
12
)
.
reshape
(
3
,
4
)
(
'
Original array:
'
)
(
a
)
(
'
\n
'
)
(
'
Transposed array:
'
)
(
a
.
T
)
The output is as follows:
原数组:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Transpose array:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
numpy.rollaxis
The numpy.rollaxis function rolls a specific axis backward to a specific position. The format is as follows:
numpy.rollaxis(arr, axis, start)
Parameter Description:
arr: arrayaxis: the axis to roll backward; the relative positions of the other axes do not changestart: defaults to zero, meaning a full roll. It will roll to a specific position.
Example
import
numpy
as
np
Created a three-dimensional ndarray
a
=
np
.
arange
(
8
)
.
reshape
(
2
,
2
,
2
)
(
'
Original array:
'
)
(
a
)
(
'
Get a value from the array:
'
)
(
np
.
where
(
a
==
6
)
)
(
a
[
1
,
1
,
0
]
)
is 6
(
'
\n
'
)
Roll axis 2 to axis 0 (width to depth)
(
'
Call the rollaxis function:
'
)
b
=
np
.
rollaxis
(
a
,
2
,
0
)
(
b
)
Check element a[1,1,0], i.e. the coordinate of 6, becomes [0, 1, 1]
The last 0 moves to the very front
(
np
.
where
(
b
==
6
)
)
(
'
\n
'
)
Roll axis 2 to axis 1: (width to height)
(
'
Call the rollaxis function:
'
)
c
=
np
.
rollaxis
(
a
,
2
,
1
)
(
c
)
Check element a[1,1,0], i.e. the coordinate of 6, becomes [1, 0, 1]
The last 0 and the 1 before it swap positions
(
np
.
where
(
c
==
6
)
)
(
'
\n
'
)
The output is as follows:
Original array:
[[[0 1]
[2 3]]
[[4 5]
[6 7]]]
# Get a value from the array:
(array([1]), array([1]), array([0]))
6
Call the rollaxis function:
[[[0 2]
[4 6]]
[[1 3]
[5 7]]]
(array([0]), array([1]), array([1]))
Call the rollaxis function:
[[[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: the input arrayaxis1: an integer corresponding to the first axisaxis2: an integer corresponding to the second axis
Example
import
numpy
as
np
Created a three-dimensional ndarray
a
=
np
.
arange
(
8
)
.
reshape
(
2
,
2
,
2
)
(
'
Original array:
'
)
(
a
)
(
'
\n
'
)
Now swap axis 0 (depth direction) to axis 2 (width direction)
(
'
Array after calling the swapaxes function:
'
)
(
np
.
swapaxes
(
a
,
2
,
0
)
)
The output is as follows:
原数组:
[[[0 1]
[2 3]]
[[4 5]
[6 7]]]
Array after calling the swapaxes function:
[[[0 4]
[2 6]]
[[1 5]
[3 7]]]
Modify array dimensions
| Dimension | Description |
|---|---|
broadcast |
Create an object that mimics broadcasting |
broadcast_to |
Broadcast an array to a new shape |
expand_dims |
Expand the shape of an array |
squeeze |
Remove one-dimensional entries from the shape of an array |
numpy.broadcast
numpy.broadcast is used to mimic a broadcasting object; 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
import
numpy
as
np
x
=
np
.
array
(
[
[
1
]
,
[
2
]
,
[
3
]
]
)
y
=
np
.
array
(
[
4
,
5
,
6
]
)
Broadcast x over y
b
=
np
.
broadcast
(
x
,
y
)
It has an iterator attribute, a tuple of iterators based on its own components
(
'
Broadcasting x over y:
'
)
r
,
c
=
b
.
iters
Python3.x uses next(context), Python2.x uses context.next()
(
next
(
r
)
,
next
(
c
)
)
(
next
(
r
)
,
next
(
c
)
)
(
'
\n
'
)
The shape attribute returns the shape of the broadcast object
(
'
Shape of the broadcast object:
'
)
(
b
.
shape
)
(
'
\n
'
)
Manually add x and y using broadcast
b
=
np
.
broadcast
(
x
,
y
)
c
=
np
.
empty
(
b
.
shape
)
(
'
Manually adding x and y using broadcast:
'
)
(
c
.
shape
)
(
'
\n
'
)
c
.
flat
=
[
u
v
for
(
u
,
v
)
in
b
]
(
'
Call the flat function:
'
)
(
c
)
(
'
\n
'
)
Get the same result as NumPy's built-in broadcasting support
(
'
Sum of x and y:
'
)
(
x
y
)
The output is:
对 y 广播 x:
1 4
1 5
Shape of the broadcast object:
(3, 3)
# Manually use broadcast to add x and y:
(3, 3)
Call the flat function:
[[5. 6. 7.]
[6. 7. 8.]
[7. 8. 9.]]
The sum of x and 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 raise a ValueError.
numpy.broadcast_to(array, shape, subok)
Example
import
numpy
as
np
a
=
np
.
arange
(
4
)
.
reshape
(
1
,
4
)
(
'
Original array:
'
)
(
a
)
(
'
\n
'
)
(
'
After calling the broadcast_to function:
'
)
(
np
.
broadcast_to
(
a
,
(
4
,
4
)
)
)
The output is:
原数组:
[[0 1 2 3]]
After calling the broadcast_to function:
[[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
import
numpy
as
np
x
=
np
.
array
(
(
[
1
,
2
]
,
[
3
,
4
]
)
)
(
'
Array x:
'
)
(
x
)
(
'
\n
'
)
y
=
np
.
expand_dims
(
x
,
axis
=
0
)
(
'
Array y:
'
)
(
y
)
(
'
\n
'
)
(
'
Shapes of arrays x and y:
'
)
(
x
.
shape
,
y
.
shape
)
(
'
\n
'
)
Insert an axis at position 1
y
=
np
.
expand_dims
(
x
,
axis
=
1
)
(
'
Array y after inserting an axis at position 1:
'
)
(
y
)
(
'
\n
'
)
(
'
x.ndim and y.ndim:
'
)
(
x
.
ndim
,
y
.
ndim
)
(
'
\n
'
)
(
'
x.shape and y.shape:
'
)
(
x
.
shape
,
y
.
shape
)
The output is:
数组 x:
[[1 2]
[3 4]]
数组 y:
[[[1 2]
[3 4]]]
Shape of arrays x and 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 one-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 tuple of integers, used to select a subset of the one-dimensional entries in the shape
Example
import
numpy
as
np
x
=
np
.
arange
(
9
)
.
reshape
(
1
,
3
,
3
)
(
'
Array x:
'
)
(
x
)
(
'
\n
'
)
y
=
np
.
squeeze
(
x
)
(
'
Array y:
'
)
(
y
)
(
'
\n
'
)
(
'
Shapes of arrays x and y:
'
)
(
x
.
shape
,
y
.
shape
)
The output is:
数组 x:
[[[0 1 2]
[3 4 5]
[6 7 8]]]
数组 y:
[[0 1 2]
[3 4 5]
[6 7 8]]
Shape of arrays x and y:
(1, 3, 3) (3, 3)
Join 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 a sequence horizontally (column-wise) |
vstack |
Stack arrays in a sequence vertically (row-wise) |
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, defaults to 0
Example
import
numpy
as
np
a
=
np
.
array
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
b
=
np
.
array
(
[
[
5
,
6
]
,
[
7
,
8
]
]
)
(
'
The second array:
'
)
(
b
)
(
'
\n
'
)
The two arrays have the same dimensions
(
'
Join two arrays along axis 0:
'
)
(
np
.
concatenate
(
(
a
,
b
)
)
)
(
'
\n
'
)
(
'
Join two arrays along axis 1:
'
)
(
np
.
concatenate
(
(
a
,
b
)
,
axis
=
1
)
)
The output is:
第一个数组:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Concatenate two arrays along axis 0:
[[1 2]
[3 4]
[5 6]
[7 8]]
Connect two arrays along axis 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 with the same shapeaxis: the axis in the returned array along which the input arrays are stacked
Example
import
numpy
as
np
a
=
np
.
array
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
b
=
np
.
array
(
[
[
5
,
6
]
,
[
7
,
8
]
]
)
(
'
The second array:
'
)
(
b
)
(
'
\n
'
)
(
'
Stack two arrays along axis 0:
'
)
(
np
.
stack
(
(
a
,
b
)
,
0
)
)
(
'
\n
'
)
(
'
Stack two arrays along axis 1:
'
)
(
np
.
stack
(
(
a
,
b
)
,
1
)
)
The output is as follows:
第一个数组:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Stack two arrays along axis 0:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Stack two arrays along axis 1:
[[[1 2]
[5 6]]
[[3 4]
[7 8]]]
numpy.hstack
numpy.hstack is a convenient wrapper for numpy.concatenate, used to stack arrays horizontally 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 dimension >=2, concatenation is performed directly along axis=1).
Example
import
numpy
as
np
a
=
np
.
array
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
b
=
np
.
array
(
[
[
5
,
6
]
,
[
7
,
8
]
]
)
(
'
The second array:
'
)
(
b
)
(
'
\n
'
)
(
'
Horizontal stacking:
'
)
c
=
np
.
hstack
(
(
a
,
b
)
)
(
c
)
(
'
\n
'
)
The output is as follows:
第一个数组:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Horizontal stacking:
[[1 2 5 6]
[3 4 7 8]]
numpy.vstack
numpy.vstack is a convenient wrapper for numpy.concatenate, used to stack arrays vertically along the first axis (axis=0).
numpy.vstack automatically promotes one-dimensional arrays to two-dimensional row vectors before concatenating them vertically, equivalent to numpy.concatenate([numpy.atleast_2d(arr) for arr in arrays], axis=0).
Example
import
numpy
as
np
a
=
np
.
array
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
b
=
np
.
array
(
[
[
5
,
6
]
,
[
7
,
8
]
]
)
(
'
The second array:
'
)
(
b
)
(
'
\n
'
)
(
'
Vertical stacking:
'
)
c
=
np
.
vstack
(
(
a
,
b
)
)
(
c
)
The output is:
第一个数组:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Vertical stacking:
[[1 2]
[3 4]
[5 6]
[7 8]]
Split arrays
| function | Arrays and operations |
|---|---|
split |
Split an array into multiple sub-arrays |
hsplit |
Split an array horizontally into multiple sub-arrays (by column) |
vsplit |
Split an array vertically into multiple sub-arrays (by row) |
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 an integer, split evenly into that many parts; if an array, the positions along the axis at which to split (left-open, right-closed)axis: sets the direction along which to split, defaults to 0, horizontal split, i.e. the horizontal direction. When 1, vertical split, i.e. the vertical direction.
Example
import
numpy
as
np
a
=
np
.
arange
(
9
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
(
'
Split the array into three sub-arrays of equal size:
'
)
b
=
np
.
split
(
a
,
3
)
(
b
)
(
'
\n
'
)
(
'
Split the array at the positions indicated in the one-dimensional array:
'
)
b
=
np
.
split
(
a
,
[
4
,
7
]
)
(
b
)
The output is:
第一个数组:
[0 1 2 3 4 5 6 7 8]
Divide the array into three equally sized subarrays:
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
Split the positions indicated by the array in a one-dimensional array:
[array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8])]
When axis is 0, split horizontally; when axis is 1, split vertically:
Example
import
numpy
as
np
a
=
np.
arange
(
16
)
.
reshape
(
4
,
4
)
(
'First array:'
)
(
a
)
(
'\n'
)
(
'Default split (axis 0):'
)
b
=
np.
split
(
a
,
2
)
(
b
)
(
'\n'
)
(
'Split horizontally:'
)
c
=
np.
split
(
a
,
2
,
1
)
(
c
)
(
'\n'
)
(
'Split horizontally:'
)
d
=
np.
hsplit
(
a
,
2
)
(
d
)
The output 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]])]
Split along the horizontal direction:
[array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]]), array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])]
Split along the horizontal direction:
[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, splitting the original array by specifying the number of arrays of the same shape to return.
Example
import
numpy
as
np
harr
=
np
.
floor
(
10
np
.
random
.
random
(
(
2
,
6
)
)
)
(
'
Original array:
'
)
(
harr
)
(
'
After splitting:
'
)
(
np
.
hsplit
(
harr
,
3
)
)
The output is:
原array:
[[4. 7. 6. 3. 2. 6.]
[6. 3. 6. 7. 9. 7.]]
After splitting:
[array([[4., 7.],
[6., 3.]]), array([[6., 3.],
[6., 7.]]), array([[2., 6.],
[9., 7.]])]
numpy.vsplit
numpy.vsplit splits along the vertical axis, in the same way as hsplit.
Example
import
numpy
as
np
a
=
np
.
arange
(
16
)
.
reshape
(
4
,
4
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
(
'
Vertical split:
'
)
b
=
np
.
vsplit
(
a
,
2
)
(
b
)
The output is:
第一个数组:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
Vertical Split:
[array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])]
Add and delete array elements
| function | Element and description |
|---|---|
resize |
Return a new array of the specified shape |
append |
Append values to the end of an array |
insert |
Insert values before the specified index along the specified axis |
delete |
Delete a sub-array along an axis and return a new array with the deletion applied |
unique |
Find the unique elements within an array |
numpy.resize
The numpy.resize function returns a new array of the specified size.
If the new array size is larger than the original, 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
import
numpy
as
np
a
=
np
.
array
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
]
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
(
'
Shape of the first array:
'
)
(
a
.
shape
)
(
'
\n
'
)
b
=
np
.
resize
(
a
,
(
3
,
2
)
)
(
'
The second array:
'
)
(
b
)
(
'
\n
'
)
(
'
Shape of the second array:
'
)
(
b
.
shape
)
(
'
\n
'
)
Note that the first row of a appears repeatedly in b because the size became larger
(
'
Resize the second array:
'
)
b
=
np
.
resize
(
a
,
(
3
,
3
)
)
(
b
)
The output is:
第一个数组:
[[1 2 3]
[4 5 6]]
Shape of the first array:
(2, 3)
Second array:
[[1 2]
[3 4]
[5 6]]
Shape of the second array:
(3, 2)
Modify the size of the second array:
[[1 2 3]
[4 5 6]
[1 2 3]]
numpy.append
The numpy.append function adds values at 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 or 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: values to add toarrthe value to add needs to have the samearrshape as (except along the axis to be added)axis: defaults to None. When axis is undefined, it is a horizontal addition and the return is always a one-dimensional array! When axis is defined, it can be 0 or 1. When axis is defined, it can be 0 or 1 (the number of columns must be the same). When axis is 1, the array is added on the right (the number of rows must be the same).
Example
import
numpy
as
np
a
=
np
.
array
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
]
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
(
'
Add elements to an array:
'
)
(
np
.
append
(
a
,
[
7
,
8
,
9
]
)
)
(
'
\n
'
)
(
'
Add elements along axis 0:
'
)
(
np
.
append
(
a
,
[
[
7
,
8
,
9
]
]
,
axis
=
0
)
)
(
'
\n
'
)
(
'
Add elements along axis 1:
'
)
(
np
.
append
(
a
,
[
[
5
,
5
,
5
]
,
[
7
,
8
,
9
]
]
,
axis
=
1
)
)
The output is:
第一个数组:
[[1 2 3]
[4 5 6]]
Add elements to the array:
[1 2 3 4 5 6 7 8 9]
Add element along axis 0:
[[1 2 3]
[4 5 6]
[7 8 9]]
# Add element to axis 1:
[[1 2 3 5 5 5]
[4 5 6 7 8 9]]
numpy.insert
The numpy.insert function inserts values into an input array along a given axis, before the given index.
The function inserts the given value or array at the specified position (or array of positions) and 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 value to insertaxis: the axis along which to insert; if not provided, the input array is flattened
Example
import
numpy
as
np
a
=
np
.
array
(
[
[
1
,
2
]
,
[
3
,
4
]
,
[
5
,
6
]
]
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
(
'
The Axis parameter is not passed. The input array is flattened before deletion.
'
)
(
np
.
insert
(
a
,
3
,
[
11
,
12
]
)
)
(
'
\n
'
)
(
'
The Axis parameter is passed. The value array is broadcast to match the input array.
'
)
(
'
Broadcast along axis 0:
'
)
(
np
.
insert
(
a
,
1
,
[
11
]
,
axis
=
0
)
)
(
'
\n
'
)
(
'
Broadcast along axis 1:
'
)
(
np
.
insert
(
a
,
1
,
11
,
axis
=
1
)
)
The output is as follows:
第一个数组:
[[1 2]
[3 4]
[5 6]]
未传递 Axis 参数。 在删除之前输入数组会被展开。
[ 1 2 3 11 12 4 5 6]
传递了 Axis 参数。 会广播值数组来配输入数组。
Broadcast along axis 0:
[[ 1 2]
[11 11]
[ 3 4]
[ 5 6]]
Broadcast along axis 1:
[[ 1 11 2]
[ 3 11 4]
[ 5 11 6]]
numpy.delete
The numpy.delete function returns a new array with the specified sub-arrays 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 array of integers, indicating the sub-arrays to delete from the input arrayaxis: the axis along which the given sub-arrays are deleted; if not provided, the input array is flattened
Example
import
numpy
as
np
a
=
np
.
arange
(
12
)
.
reshape
(
3
,
4
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
(
'
The Axis parameter is not passed. The input array is flattened before insertion.
'
)
(
np
.
delete
(
a
,
5
)
)
(
'
\n
'
)
(
'
Delete the second column:
'
)
(
np
.
delete
(
a
,
1
,
axis
=
1
)
)
(
'
\n
'
)
(
'
A slice containing alternative values to delete from the array:
'
)
a
=
np
.
array
(
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
]
)
(
np
.
delete
(
a
,
np
.
s_
[
::
2
]
)
)
The output 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]
Delete the second column:
[[ 0 2 3]
[ 4 6 7]
[ 8 10 11]]
Slice containing replacement values deleted from the array:
[ 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 one-dimensional, it will be flattenedreturn_index: iftrue, returns the positions (indices) of the new list elements in the old list, stored as a listreturn_inverse: iftrue, returns the positions (indices) of the old list elements in the new list, stored as a listreturn_counts: iftrue, returns the number of occurrences of the elements in the deduplicated array in the original array
Example
import
numpy
as
np
a
=
np
.
array
(
[
5
,
2
,
6
,
2
,
7
,
5
,
6
,
8
,
2
,
9
]
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
(
'
Deduplicated values of the first array:
'
)
u
=
np
.
unique
(
a
)
(
u
)
(
'
\n
'
)
(
'
Index array of the deduplicated array:
'
)
u
,
indices
=
np
.
unique
(
a
,
return_index
=
True
)
(
indices
)
(
'
\n
'
)
(
'
We can see each value corresponding to an index of the original array:
'
)
(
a
)
(
'
\n
'
)
(
'
Indices of the deduplicated array:
'
)
u
,
indices
=
np
.
unique
(
a
,
return_inverse
=
True
)
(
u
)
(
'
\n
'
)
(
'
The indices are:
'
)
(
indices
)
(
'
\n
'
)
(
'
Reconstruct the original array using the indices:
'
)
(
u
[
indices
]
)
(
'
\n
'
)
(
'
Return the repetition count of the deduplicated elements:
'
)
u
,
indices
=
np
.
unique
(
a
,
return_counts
=
True
)
(
u
)
(
indices
)
The output is:
第一个数组:
[5 2 6 2 7 5 6 8 2 9]
Unique values of the first array:
[2 5 6 7 8 9]
Index array of the deduplicated array:
[1 0 2 4 7 9]
We can see the value corresponding to each index of the original array:
[5 2 6 2 7 5 6 8 2 9]
Index of the deduplicated array:
[2 5 6 7 8 9]
Index is:
[1 0 2 0 3 1 2 4 0 5]
Reconstruct the original array using indices:
[5 2 6 2 7 5 6 8 2 9]
Return the count of duplicates of the unique elements:
[2 5 6 7 8 9]
[3 2 2 1 1 1]