Numpy foundation - a complete collection of array operations (modify, flip, merge, split, add and delete, and de duplication)

Array operation

1, Modify array shape
reshapeModify shape without changing data
flatArray element iterator
flattenReturns a copy of the array. Changes made to the copy will not affect the original array
ravelReturns an expanded array


numpy. The reshape function can modify the shape without changing the data. The format is as follows:

numpy.reshape(arr, newshape, order='C')
  • arr: array of shapes to modify
  • newshape: integer or integer array. The new shape should be compatible with the original shape
  • Order: 'C' - by row, 'F' - by column, 'A' - original order, 'k' - order of elements in memory.
a = np.arange(9)
b = a.reshape(3, 3)
for row in b:    #Traverse each line
#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 b.flat:
#[0 1 2]
#[3 4 5]
#[6 7 8]

flatten() expands a two-dimensional array into one dimension

np. Travel (the same function as flatten. When modifying the travel object, the original array is also modified!!! But this will not happen when modifying the flatten object, so try to use flatten at ordinary times)

numpy. The array elements flattened by travel() are usually in "C style" order, and the array view is returned. Modification will affect the original array.

numpy.ravel(a, order='C')
  • Order: 'C' - by row, 'F' - by column, 'A' - original order, 'K' - order of elements in memory.
2, Flip array
transposeSwapping the dimensions of an array
ndarray.TAnd self Same as transfer()
rollaxisScrolls the specified axis backward
swapaxesSwap the two axes of the array (multidimensional case)


numpy. The transfer function is used to exchange the dimensions of the array. The format is as follows:

numpy.transpose(arr, axes)

Parameter Description:

  • arr: array to operate on
  • axes: a list of integers, corresponding to dimensions. Usually, all dimensions are exchanged.
3, Merge array
concatenateJoin array sequences along existing axes
stackAdd a series of arrays along the new axis.
hstackArray in horizontal stack sequence (column direction)
vstackStack arrays in the sequence vertically (row direction)


numpy. The concatenate function is used to connect two or more arrays of the same shape along the 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 array is connected. The default value is 0
a = np.arange(4).reshape(2, 2)
b = np.arange(5, 9).reshape(2, 2)
ic(np.concatenate((a, b)))  #axis=0, along the vertical axis (default), and two parentheses should be set here
ic(np.concatenate((a, b), axis=1))
#ic| np.concatenate((a, b)): array([[0, 1],
#                                   [2, 3],
#                                   [5, 6],
#                                   [7, 8]])
#ic| np.concatenate((a, b), axis=1): array([[0, 1, 5, 6],
#                                          [2, 3, 7, 8]])


numpy. The stack function is used to connect the array sequence along the new axis (the result of the combination of two two-dimensional arrays is a three-dimensional array). The format is as follows:

numpy.stack(arrays, axis)

Merge along the X, y, z axes

np.hstack() and NP Vstack() is still a two-dimensional array after merging

ic(np.hstack((a, b)))  #about
ic(np.vstack((a, b)))  #Up and down
#ic| np.hstack((a, b)): array([[0, 1, 5, 6],
#                              [2, 3, 7, 8]])
#ic| np.vstack((a, b)): array([[0, 1],
#                              [2, 3],
#                              [5, 6],
#                              [7, 8]])
4, Split array
functionArray and operation
splitSplits an array into subarrays
hsplitSplit an array horizontally into multiple sub arrays (by column)
vsplitSplit an array vertically into multiple sub arrays (by row)


numpy. The split function divides an array into subarrays along a specific axis. The format is as follows:

numpy.split(ary, indices_or_sections, axis)

Parameter Description:

  • ary: array to be split
  • indices_or_sections: if it is an integer, the number is used to divide evenly. If it is an array, it is the position cut along the axis (left open and right closed)
  • axis: sets the direction along which to slice. The default value is 0. The horizontal direction is the horizontal direction. When it is 1, it is divided longitudinally, that is, in the vertical direction.
a = np.arange(9)
b = np.split(a, 3)   #Divide into three equal parts
c = np.split(a, [4, 7]) #Cut at the specified position
d = np.arange(16).reshape(4, 4)
ic(np.hsplit(d, 2))  #Vertical segmentation
#ic| b: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
#ic| c: [array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8])]
#ic| np.hsplit(d ,2): [array([[ 0,  1],
#                            [ 4,  5],
#                            [ 8,  9],
#                            [12, 13]]),
#                      array([[ 2,  3],
#                            [ 6,  7],
#                            [10, 11],
#                            [14, 15]])]
5, Addition and deletion of elements
functionElement and description
resizeReturns a new array of specified shapes
appendAdds a value to the end of the array
insertInserts the value along the specified axis before the specified subscript
deleteDelete the subarray of an axis and return the deleted new array
uniqueFind a unique element in an array

numpy. Resize (generally used for reduction)

numpy. The resize function returns a new array of the specified size.

If the new array size is larger than the original size, a copy of the elements in the original array is included.

numpy.resize(arr, shape)

Parameter Description:

  • arr: array to change size
  • Shape: returns the new shape of the array

resize can be used in two ways: one is to directly modify the original data without a return value, and the other is to have a return value, so the original array value will not be modified.

a = np.array([[1, 2, 3], [4, 5, 6]])
ic(np.resize(a, (3, 3)))  #The first row is copied without changing the original array
a2 = a.resize((2, 2))
ic(a2)   #The return value here is None
ic(a)    #At this point, a has been modified
#ic| np.resize(a, (3, 3)): array([[1, 2, 3],
#                                 [4, 5, 6],
#                                 [1, 2, 3]])
#ic| a2: None
#ic| a: array([[1, 2],
#              [3, 4]])


numpy. The append function adds a value to the end of the array. The append operation allocates the entire array and copies the original array to the new array. In addition, the dimensions of the input array 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: the value to be added to arr needs to be the same shape as arr (except for the axis to be added)
  • Axis: None by default. When axis is undefined, it is a horizontal addition, and the return is always a one-dimensional array! When axis is defined, it is 0 and 1 respectively. When axis is defined, it is 0 and 1 respectively (the number of columns should be the same). When axis is 1, the array is added to the right (the number of rows should be the same).
a = np.array([[1, 2, 3], [4, 5, 6]])
ic(np.append(a, [[7, 8, 9]], axis=0))
#Add element along axis 0:
#[[1 2 3]
# [4 5 6]
# [7 8 9]]


numpy. The insert function inserts a value into the input array along a given axis before a given index.

If the type of the value is converted to be inserted, it is different from the input array. If you insert an array that is not in place, the function returns a new array. In addition, if no axis is provided, the input array is expanded.

numpy.insert(arr, obj, values, axis)

Parameter Description:

  • arr: input array
  • obj: index before which the value is inserted
  • values: the value to insert
  • Axis: along the axis it is inserted. If not provided, the input array will be expanded
a = np.array([[1, 2], [3, 4], [5, 6]])
ic(np.insert(a, 1, 11))
ic(np.insert(a, 1, 11, axis=0))
ic(np.insert(a, 1, 11, axis=1))
#ic| np.insert(a, 1, 11): array([ 1, 11,  2,  3,  4,  5,  6])
#ic| np.insert(a, 1, 11, axis=0): array([[ 1,  2],
#                                        [11, 11],
#                                        [ 3,  4],
#                                        [ 5,  6]])
#ic| np.insert(a, 1, 11, axis=1): array([[ 1, 11,  2],
#                                        [ 3, 11,  4],
#                                        [ 5, 11,  6]])


numpy. The delete function returns a new array that deletes the specified subarray from the input array. As in the case of the insert() function, if no axis parameter is provided, the input array is expanded.

Numpy.delete(arr, obj, axis)

Parameter Description:

  • arr: input array
  • obj: can be sliced, integer or integer array, indicating the subarray to be deleted from the input array
  • Axis: the axis along which the sub array is deleted. If it is not provided, the input array will be expanded
a = np.arange(12).reshape(3, 4)
ic(np.delete(a, 5)) #If the axis parameter is not passed, the array will be expanded before insertion
ic(np.delete(a, 1, axis=0))  #Delete the second line
b = np.arange(1, 11)
ic(b[np.s_[::2]])   #np.s_ Can be used as an index
ic(np.delete(b, np.s_[::2])) #Delete elements with an index of 2 multiples
#ic| a: array([[ 0,  1,  2,  3],
#              [ 4,  5,  6,  7],
#              [ 8,  9, 10, 11]])
#ic| np.delete(a, 5): array([ 0,  1,  2,  3,  4,  6,  7,  8,  9, 10, 11])
#ic| np.delete(a, 1, axis=0): array([[ 0,  1,  2,  3],
#                                    [ 8,  9, 10, 11]])
#ic| b: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
#ic| b[np.s_[::2]]: array([1, 3, 5, 7, 9])
#ic| np.delete(b, np.s_[::2]): array([ 2,  4,  6,  8, 10])


numpy. The unique function removes duplicate elements from the array.

numpy.unique(arr, return_index, return_inverse, return_counts)
  • arr: input array. If it is not a one-dimensional array, it will be expanded
  • return_index: if true, returns the position (subscript) of the new list element in the old list and stores it as a list
  • return_inverse: if true, returns the position (subscript) of the old list element in the new list and stores it in a list
  • return_counts: if true, returns the number of occurrences of elements in the de duplicated array in the original array
a = np.array([5, 2, 6, 2, 7, 5, 6, 8, 2, 9])
u = np.unique(a)
u, indices = np.unique(a, return_index=True) #Returns the index of the element in the original array after de duplication
u, indices2 = np.unique(a, return_inverse=True) #Returns the position of the element before de duplication in the list after de duplication (the length is equal to the meta array)
ic(u[indices2])   #The original array is reconstructed by using the de duplicated array u and index indices2
#ic| a: array([5, 2, 6, 2, 7, 5, 6, 8, 2, 9])
#ic| u: array([2, 5, 6, 7, 8, 9])
#ic| indices: array([1, 0, 2, 4, 7, 9], dtype=int64)
#ic| indices2: array([1, 0, 2, 0, 3, 1, 2, 4, 0, 5], dtype=int64)

Keywords: Python

Added by glueater on Wed, 05 Jan 2022 14:20:22 +0200