Numpy Array Manipulation

Numpy contains some functions for processing arrays, which can be roughly divided into the following categories:


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 modified
  • newshape: 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

import numpy as np a = np.arange(8) print ('Original array:') print (a) print ('\n') b = a.reshape(4,2) print ('Modified array:') print (b)

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

import numpy as np a = np.arange(9).reshape(3,3) print ('Original array:') for row in a: print (row) # To process each element in the array, you can use the flat attribute, which is an array element iterator: print ('Array after iteration:') for element in a.flat: print (element)

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

import numpy as np a = np.arange(8).reshape(2,4) print ('Original array:') print (a) print ('\n') # Default is by row print ('Flattened array:') print (a.flatten()) print ('\n') print ('Array flattened in F-style order:') print (a.flatten(order = 'F'))

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

import numpy as np a = np.arange(8).reshape(2,4) print ('Original array:') print (a) print ('\n') print ('After calling the ravel function:') print (a.ravel()) print ('\n') print ('After calling the ravel function in F-style order:') print (a.ravel(order = 'F'))

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 on
  • axes: A list of integers, corresponding to the dimensions. Usually all dimensions are swapped.

Example

import numpy as np a = np.arange(12).reshape(3,4) print ('Original array:') print (a ) print ('\n') print ('Transposed array:') print (np.transpose(a))

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

import numpy as np a = np.arange(12).reshape(3,4) print ('Original array:') print (a) print ('\n') print ('Transposed array:') print (a.T)

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: Array
  • axis: 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

import numpy as np # Created a three-dimensional ndarray a = np.arange(8).reshape(2,2,2) print ('Original array:') print (a) print ('Get a value in the array:') print(np.where(a==6)) print(a[1,1,0]) # is 6 print ('\n') # Roll axis 2 to axis 0 (width to depth) print ('Call the rollaxis function:') b = np.rollaxis(a,2,0) print (b) # View element a[1,1,0], i.e., the coordinate of 6, becomes [0, 1, 1] # The last 0 moves to the front print(np.where(b==6)) print ('\n') # Roll axis 2 to axis 1: (width to height) print ('Call the rollaxis function:') c = np.rollaxis(a,2,1) print (c) # View element a[1,1,0], i.e., the coordinate of 6, becomes [1, 0, 1] # The last 0 swaps positions with the 1 in front of it print(np.where(c==6)) print ('\n')

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 array
  • axis1: An integer corresponding to the first axis
  • axis2: 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) print ('Original array:') print (a) print ('\n') # Now swap axis 0 (depth direction) to axis 2 (width direction) print ('Array after calling the swapaxes function:') print (np.swapaxes(a, 2, 0))

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

import numpy as np x = np.array([[1], [2], [3]]) y = np.array([4, 5, 6]) # Broadcast x against y b = np.broadcast(x,y) # It has an iterator attribute, based on an iterator tuple of its own components print ('Broadcast x against y:') r,c = b.iters # For Python3.x it is next(context), for Python2.x it is context.next() print (next(r), next(c)) print (next(r), next(c)) print ('\n') # The shape attribute returns the shape of the broadcast object print ('Shape of the broadcast object:') print (b.shape) print ('\n') # Manually use broadcast to add x and y b = np.broadcast(x,y) c = np.empty(b.shape) print ('Manually add x and y using broadcast:') print (c.shape) print ('\n') c.flat = [u + v for (u,v) in b] print ('Call the flat function:') print (c) print ('\n') # This yields the same result as NumPy's built-in broadcast support print ('The sum of x and y:') print (x + y)

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

import numpy as np a = np.arange(4).reshape(1,4) print ('Original array:') print (a) print ('\n') print ('After calling the broadcast_to function:') print (np.broadcast_to(a,(4,4)))

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 array
  • axis: The position where the new axis is inserted

Example

import numpy as np x = np.array(([1,2],[3,4])) print ('Array x:') print (x) print ('\n') y = np.expand_dims(x, axis = 0) print ('Array y:') print (y) print ('\n') print ('Shapes of arrays x and y:') print (x.shape, y.shape) print ('\n') # Insert an axis at position 1 y = np.expand_dims(x, axis = 1) print ('Array y after inserting an axis at position 1:') print (y) print ('\n') print ('x.ndim and y.ndim:') print (x.ndim,y.ndim) print ('\n') print ('x.shape and y.shape:') print (x.shape, y.shape)

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 array
  • axis: an integer or a tuple of integers, used to select a subset of single-dimensional entries in the shape

Example

import numpy as np x = np.arange(9).reshape(1,3,3) print ('Array x:') print (x) print ('\n') y = np.squeeze(x) print ('Array y:') print (y) print ('\n') print ('The shapes of arrays x and y:') print (x.shape, y.shape)

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 type
  • axis: the axis along which the arrays are joined, default is 0

Example

import numpy as np a = np.array([[1,2],[3,4]]) print ('First array:') print (a) print ('\n') b = np.array([[5,6],[7,8]]) print ('Second array:') print (b) print ('\n') # The two arrays have the same dimensions print ('Join the two arrays along axis 0:') print (np.concatenate((a,b))) print ('\n') print ('Join the two arrays along axis 1:') print (np.concatenate((a,b),axis = 1))

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 shape
  • axis: 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]]) print ('First array:') print (a) print ('\n') b = np.array([[5,6],[7,8]]) print ('Second array:') print (b) print ('\n') print ('Stack the two arrays along axis 0:') print (np.stack((a,b),0)) print ('\n') print ('Stack the two arrays along axis 1:') print (np.stack((a,b),1))

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

import numpy as np a = np.array([[1,2],[3,4]]) print ('First array:') print (a) print ('\n') b = np.array([[5,6],[7,8]]) print ('Second array:') print (b) print ('\n') print ('Horizontal stacking:') c = np.hstack((a,b)) print (c) print ('\n')

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

import numpy as np a = np.array([[1,2],[3,4]]) print ('First array:') print (a) print ('\n') b = np.array([[5,6],[7,8]]) print ('Second array:') print (b) print ('\n') print ('Vertical stacking:') c = np.vstack((a,b)) print (c)

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 split
  • indices_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

import numpy as np a = np.arange(9) print ('First array:') print (a) print ('\n') print ('Split the array into three sub-arrays of equal size:') b = np.split(a,3) print (b) print ('\n') print ('Split the array at the positions indicated in the one-dimensional array:') b = np.split(a,[4,7]) print (b)

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

import numpy as np

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

import numpy as np harr = np.floor(10 * np.random.random((2, 6))) print ('Original array:') print(harr) print ('After splitting:') print(np.hsplit(harr, 3))

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

import numpy as np a = np.arange(16).reshape(4,4) print ('First array:') print (a) print ('\n') print ('Vertical split:') b = np.vsplit(a,2) print (b)

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 modified
  • shape: the new shape of the returned array

Example

import numpy as np a = np.array([[1,2,3],[4,5,6]]) print ('First array:') print (a) print ('\n') print ('Shape of the first array:') print (a.shape) print ('\n') b = np.resize(a, (3,2)) print ('Second array:') print (b) print ('\n') print ('Shape of the second array:') print (b.shape) print ('\n') # Note that the first row of a appears repeatedly in b because the size has become larger. print ('Modify the size of the second array:') b = np.resize(a,(3,3)) print (b)

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 array
  • values: 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

import numpy as np a = np.array([[1,2,3],[4,5,6]]) print ('First array:') print (a) print ('\n') print ('Add elements to the array:') print (np.append(a, [7,8,9])) print ('\n') print ('Add elements along axis 0:') print (np.append(a, [[7,8,9]],axis = 0)) print ('\n') print ('Add elements along axis 1:') print (np.append(a, [[5,5,5],[7,8,9]],axis = 1))

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 array
  • obj: the index before which values are inserted
  • values: the values to be inserted
  • axis: 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]]) print ('First array:') print (a) print ('\n') print ('The Axis parameter is not passed. The input array is flattened before deletion.') print (np.insert(a,3,[11,12])) print ('\n') print ('The Axis parameter is passed. The value array is broadcast to match the input array.') print ('Broadcast along axis 0:') print (np.insert(a,1,[11],axis = 0)) print ('\n') print ('Broadcast along axis 1:') print (np.insert(a,1,11,axis = 1))

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 array
  • obj: 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

import numpy as np a = np.arange(12).reshape(3,4) print ('First array:') print (a) print ('\n') print ('The Axis parameter is not passed. The input array is flattened before insertion.') print (np.delete(a,5)) print ('\n') print ('Delete the second column:') print (np.delete(a,1,axis = 1)) print ('\n') print ('Slice containing the alternative values to be deleted from the array:') a = np.array([1,2,3,4,5,6,7,8,9,10]) print (np.delete(a, np.s_[::2]))

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

import numpy as np a = np.array([5,2,6,2,7,5,6,8,2,9]) print ('First array:') print (a) print ('\n') print ('Deduplicated values of the first array:') u = np.unique(a) print (u) print ('\n') print ('Index array of the deduplicated array:') u,indices = np.unique(a, return_index = True) print (indices) print ('\n') print ('We can see that each value corresponds to the index of the original array:') print (a) print ('\n') print ('Indices of the deduplicated array:') u,indices = np.unique(a,return_inverse = True) print (u) print ('\n') print ('The indices are:') print (indices) print ('\n') print ('Reconstruct the original array using indices:') print (u[indices]) print ('\n') print ('Return the duplicate counts of deduplicated elements:') u,indices = np.unique(a,return_counts = True) print (u) print (indices)

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