Numpy Array Manipulation
Numpy includes several functions for array manipulation, which can be roughly categorized into the following:
-Add and Delete 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 to the copy do not affect the original array |
ravel | Return a flattened array |
numpy.reshape
The numpy.reshape
function allows modifying the shape without changing the data, with the following format:
numpy.reshape(arr, newshape, order='C')
arr
: The array to be reshapednewshape
: Integer or array of integers, the new shape should be compatible with the original shapeorder
: 'C' -- by row, 'F' -- by column, 'A' -- original order, 'k' -- order of elements 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)
Output result:
Original array:
[0 1 2 3 4 5 6 7]
Modified array:
[[0 1]
[2 3]
[4 5]
[6 7]]
numpy.ndarray.flat
Example
import numpy as np
a = np.arange(9).reshape(3, 3)
print('Original array:')
for row in a:
print(row)
# Process each element in the array using the flat attribute, which is an array element iterator:
print('Iterated array:')
for element in a.flat:
print(element)
Output result:
Original array:
[0 1 2]
[3 4 5]
[6 7 8]
Iterated array:
0
1
2
3
4
5
6
7
8
numpy.ndarray.flatten
numpy.ndarray.flatten
returns a copy of the array; modifications to the copy do not affect the original array, with the following format:
ndarray.flatten(order='C')
Parameter description:
order
: 'C' -- by row, 'F' -- by column, 'A' -- original order, 'K' -- order of elements in memory
Example
import numpy as np
a = np.arange(8).reshape(2, 4)
print('Original array:')
print(a)
print('\n')
# Default by row
print('Flattened array:')
print(a.flatten())
print('\n')
print('Flattened array in F-style order:')
print(a.flatten(order='F'))
Output result:
Original array:
[[0 1 2 3]
[4 5 6 7]]
Flattened array:
[0 1 2 3 4 5 6 7]
Flattened array in F-style order:
[0 4 1 5 2 6 3 7]
numpy.ravel
numpy.ravel()
flattens the array elements, typically in "C-style" order, and returns an array view (similar to a C/C++ reference), which means modifications affect the original array.
The function accepts two parameters:
numpy.ravel(a, order='C')
Parameter description:
order
: 'C' -- by row, 'F' -- by column, 'A' -- original order, 'K' -- order of elements in memory
Example
import numpy as np
a = np.arange(8).reshape(2, 4)
print('Original array:')
print(a)
print('\n')
print('After calling ravel function:')
print(a.ravel())
print('\n')
Output result:
Original array:
[[0 1 2 3]
[4 5 6 7]]
After calling ravel function:
[0 1 2 3 4 5 6 7]
print('After calling the ravel function in F-style order:')
print(a.ravel(order='F'))
Output result is as follows:
Original array:
[[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]
Array Flip
Function | Description |
---|---|
transpose | Swap the dimensions of the array |
ndarray.T | Same as self.transpose() |
rollaxis | Roll the specified axis backward |
swapaxes | Swap the two axes of the array |
numpy.transpose
The numpy.transpose function is used to swap the dimensions of the array, with the following format:
numpy.transpose(arr, axes)
Parameter description:
arr
: Array to be operated onaxes
: List of integers corresponding to dimensions, typically all dimensions are swapped.
Example
import numpy as np
a = np.arange(12).reshape(3,4)
print('Original array:')
print(a)
print('\n')
print('Swapped array:')
print(np.transpose(a))
Output result is as follows:
Original array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Swapped 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)
print('Original array:')
print(a)
print('\n')
print('Transposed array:')
print(a.T)
Output result is as follows:
Original array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Transposed array:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
numpy.rollaxis
The numpy.rollaxis function rolls the specified axis backward to a specified position, with the following format:
numpy.rollaxis(arr, axis, start)
Parameter description:
arr
: Arrayaxis
: The axis to roll backward, the relative positions of the other axes do not changestart
: Default is zero, indicating complete rolling. Rolls to a specific position.
Example
import numpy as np
# Create a 3-dimensional ndarray
a = np.arange(8).reshape(2,2,2)
print('Original array:')
print(a)
print('Get a value from the array:')
print(np.where(a==6))
print(a[1,1,0]) # This is 6
print('\n')
# Roll axis 2 to axis 0 (width to depth)
print('Calling rollaxis function:')
b = np.rollaxis(a,2,0)
print(b)
# Check the coordinates of element a[1,1,0], which is 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('Calling rollaxis function:')
c = np.rollaxis(a,2,1)
print(c)
# Check the coordinates of element a[1,1,0], which is 6, becomes [1, 0, 1]
# The last 0 and the 1 before it swap positions
print(np.where(c==6))
print('\n')
Output result 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
Calling rollaxis function:
[[[0 2]
[4 6]]
[[1 3]
[5 7]]]
(array([0]), array([1]), array([1]))
Calling 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 the array, with the following format:
numpy.swapaxes(arr, axis1, axis2)
arr
: Input arrayaxis1
: Integer corresponding to the first axisaxis2
: Integer corresponding to the second axis
Example
import numpy as np
# Create a three-dimensional ndarray
a = np.arange(8).reshape(2, 2, 2)
print('Original array:')
print(a)
print('\n')
# Now swap axis 0 (depth) with axis 2 (width)
print('Array after calling swapaxes function:')
print(np.swapaxes(a, 2, 0))
Output result is as follows:
Original array:
[[[0 1]
[2 3]]
[[4 5]
[6 7]]]
Array after calling swapaxes function:
[[[0 4]
[2 6]]
[[1 5]
[3 7]]]
Modifying Array Dimensions
Dimension | Description |
---|---|
broadcast | Produces an object that mimics broadcasting |
broadcast_to | Broadcasts an array to a new shape |
expand_dims | Expands the shape of an array |
squeeze | Removes single-dimensional entries from the shape of an array |
numpy.broadcast
numpy.broadcast is used to mimic the broadcasting object, which returns an object that encapsulates the result of broadcasting one array to another.
This function takes two arrays as input parameters, as shown in the example:
Example
import numpy as np
x = np.array([[1], [2], [3]])
y = np.array([4, 5, 6])
# Broadcast x to y
b = np.broadcast(x, y)
# It has an iterator attribute, a tuple of iterators based on its components
print('Broadcasting x to y:')
r, c = b.iters
# Python3.x uses next(context), Python2.x uses 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 using broadcast to add x and y:')
print(c.shape)
print('\n')
c.flat = [u + v for (u, v) in b]
print('Calling flat function:')
print(c)
print('\n')
# Achieves the same result as NumPy's built-in broadcasting support
print('Sum of x and y:')
print(x + y)
Output result is as follows:
Broadcasting x to y:
1 4
1 5
Shape of the broadcast object:
(3, 3)
Manually using broadcast to add x and y:
(3, 3)
Calling flat function:
[[5. 6. 7.]
[6. 7. 8.]
[7. 8. 9.]]
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 typically not contiguous. If the new shape does not conform to NumPy's broadcasting rules, this 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 broadcast_to function:')
print(np.broadcast_to(a, (4, 4)))
Output result is as follows:
Original array:
[[0 1 2 3]]
After calling 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 the specified position. The function format is as follows:
numpy.expand_dims(arr, axis)
Parameter description:
arr
: Input arrayaxis
: 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')
print('After calling expand_dims function:')
print(np.expand_dims(x, axis=0))
Output result is as follows:
Array x:
[[1 2]
[3 4]]
After calling expand_dims function:
[[[1 2]
[3 4]]]
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 axis at position 1
y = np.expand_dims(x, axis=1)
print('Array y after inserting 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)
Output:
Array x:
[[1 2]
[3 4]]
Array y:
[[[1 2]
[3 4]]]
Shapes of arrays x and y:
(2, 2) (1, 2, 2)
Array y after inserting axis at position 1:
[[[1 2]]
[[3 4]]]
x.ndim and y.ndim:
2 3
x.shape and y.shape:
(2, 2) (2, 1, 2)
numpy.squeeze
The numpy.squeeze function removes single-dimensional entries from the shape of an array. The function format is as follows:
numpy.squeeze(arr, axis)
Parameters:
arr
: Input arrayaxis
: An integer or tuple of integers 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('Shapes of arrays x and y:')
print(x.shape, y.shape)
Output:
Array x:
[[[0 1 2]
[3 4 5]
[6 7 8]]]
Array y:
[[0 1 2]
[3 4 5]
[6 7 8]]
Shapes of arrays x and 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-wise) |
vstack | Stack arrays in 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)
Parameters:
a1, a2, ...
: Arrays of the same typeaxis
: The axis along which 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')
# Arrays have the same dimensions
print('Concatenate along axis 0:')
print(np.concatenate((a, b)))
print('\n')
print('Concatenate along axis 1:')
print(np.concatenate((a, b), axis=1))
Output:
First array:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Concatenate along axis 0:
[[1 2]
[3 4]
[5 6]
[7 8]]
Concatenate 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)
Parameters:
arrays
: Sequence of arrays with the same shapeaxis
: The axis in the result 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 along axis 0:')
print(np.stack((a, b), 0))
Output:
First array:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Stack along axis 0:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
This is a Chinese to English translation, please provide the English translation for this text. Do not provide any explanations or text apart from the translation.
Chinese: print ('\n')
print ('Stack two arrays along axis 1:')
print (np.stack((a,b),1))
Output result is as follows:
First array:
[[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 variant of the numpy.stack function, which generates arrays by stacking horizontally.
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')
Output result is as follows:
First array:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Horizontal stacking:
[[1 2 5 6]
[3 4 7 8]]
numpy.vstack
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)
Output result is as follows:
First array:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Vertical stacking:
[[1 2]
[3 4]
[5 6]
[7 8]]
Splitting Arrays
Function | Array and Operation |
---|---|
split | Split an array into multiple subarrays |
hsplit | Split an array into multiple subarrays horizontally (column-wise) |
vsplit | Split an array into multiple subarrays vertically (row-wise) |
numpy.split
The numpy.split function splits an array into subarrays along a specific axis, with the following format:
numpy.split(ary, indices_or_sections, axis)
Parameter description:
ary
: The array to be splitindices_or_sections
: If an integer, it splits the array into equal parts; if an array, it splits at the specified positions (left-open, right-closed)axis
: Sets the direction for splitting. Default is 0, horizontal splitting, i.e., along the horizontal direction. When set to 1, it splits vertically, i.e., along 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 equal-sized subarrays:')
b = np.split(a,3)
print (b)
print ('\n')
print ('Split the array at the positions indicated in a one-dimensional array:')
b = np.split(a,[4,7])
print (b)
Output result is as follows:
First array:
[0 1 2 3 4 5 6 7 8]
Split the array into three equal-sized subarrays:
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
Split the array at the positions indicated in a one-dimensional array:
[array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8])]
When axis is 0, it splits horizontally, and when axis is 1, it splits vertically:
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 horizontally:')
c = np.split(a,2,1)
print(c)
print('\n')
print('Split horizontally:')
d= np.hsplit(a,2)
print(d)
Output result is as follows:
First array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
Default split (axis 0):
[array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])]
Split horizontally:
[array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]]), array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])]
Split horizontally:
[array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]]), array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])]
Horizontal split: [array([[ 0, 1], [ 4, 5], [ 8, 9], [12, 13]]), array([[ 2, 3], [ 6, 7], [10, 11], [14, 15]])]
Horizontal split: [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 arrays of the same shape 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))
Output:
Original 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, using the same method as 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)
Output:
First array: [[ 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]])]
---
## Adding and Removing Array Elements
| Function | Description |
| --- | --- |
| resize | Returns a new array with the specified shape |
| append | Adds values to the end of an array |
| insert | Inserts values along the specified axis before the given indices |
| delete | Deletes sub-arrays along an axis and returns a new array |
| unique | Finds unique elements in an array |
### numpy.resize
The numpy.resize function returns a new array with the specified size.
If the new array is larger than the original array, it contains copies of the elements from the original array.
numpy.resize(arr, shape)
Parameters:
-`arr` : Array to be resized
-`shape` : New shape of the 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 is repeated in b because the size is increased
print ('Resize the second array:') b = np.resize(a,(3,3)) print (b)
Output:
First array: [[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)
Resize the second array: [[1 2 3] [4 5 6] [1 2 3]]
### numpy.append
The numpy.append function adds values to the end of an array. Appending allocates the entire array and copies the original array to the new array. Additionally, the dimensions of the input arrays must match, or a ValueError will be raised.
English:
Horizontal split:
[array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]]), array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])]
Horizontal split:
[array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]]), array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])]
The `append` function always returns a one-dimensional array.
numpy.append(arr, values, axis=None)
Parameter Description:
- `arr`: Input array
- `values`: Values to be appended to `arr`. It must have the same shape as `arr` (except for the axis being appended)
- `axis`: Defaults to None. When axis is undefined, it appends horizontally, and the return is always a one-dimensional array! When axis is defined, it can be 0 or 1. When axis is defined as 0 or 1 (the number of columns must be the same). When axis is 1, the array is appended 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 ('Appending elements to the array:') print (np.append(a, [7,8,9])) print ('\n')
print ('Appending elements along axis 0:') print (np.append(a, [[7,8,9]], axis = 0)) print ('\n')
print ('Appending elements along axis 1:') print (np.append(a, [[5,5,5],[7,8,9]], axis = 1))
Output:
First array: [[1 2 3] [4 5 6]]
Appending elements to the array: [1 2 3 4 5 6 7 8 9]
Appending elements along axis 0: [[1 2 3] [4 5 6] [7 8 9]]
Appending elements along axis 1: [[1 2 3 5 5 5] [4 5 6 7 8 9]]
### numpy.insert
The `numpy.insert` function inserts values along the given axis before the given indices in the input array.
If the type of values to be inserted is different, it will be converted. The insertion is not in-place, and a new array is returned. Additionally, if the axis is not provided, the input array will be flattened.
numpy.insert(arr, obj, values, axis)
Parameter Description:
- `arr`: Input array
- `obj`: Index before which the values are to be inserted
- `values`: Values to be inserted
- `axis`: The axis along which to insert the values. If not provided, the input array will be flattened
## Example
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print ('First array:') print (a) print ('\n')
print ('Axis parameter not passed. The input array is flattened before insertion.') print (np.insert(a,3,[11,12])) print ('\n')
print ('Axis parameter passed. The value array is broadcasted to match the input array.')
print ('Broadcasting along axis 0:') print (np.insert(a,1,[11],axis = 0)) print ('\n')
print ('Broadcasting along axis 1:') print (np.insert(a,1,11,axis = 1))
Output:
First array: [[1 2] [3 4] [5 6]]
Axis parameter not passed. The input array is flattened before insertion. [ 1 2 3 11 12 4 5 6]
Axis parameter passed. The value array is broadcasted to match the input array. Broadcasting along axis 0: [[ 1 2] [11 11] [ 3 4] [ 5 6]]
Broadcasting 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 subarray removed from the input array. Like the `insert()` function, if the axis parameter is not provided, the input array will be flattened.
numpy.delete(arr, obj, axis)
Parameter Description:
- `arr`: Input array
- `obj`: Can be a slice, an integer, or an array of integers, indicating the subarray to be removed from the input array
- `axis`: The axis along which to delete the given subarray. If not provided, the input array will be flattened
## Example
import numpy as np
a = np.arange(12).reshape(3,4)
print ('First array:') print (a) print ('\n')
print ('Axis parameter not passed. The input array is flattened before deletion.') print (np.delete(a,5)) print ('\n')
print ('Deleting the second column:') print (np.delete(a,1,axis = 1)) print ('\n')
print ('Slicing with alternative values removed from the array:') a = np.array([1,2,3,4,5,6,7,8,9,10]) print (np.delete(a, np.s_[::2]))
Output:
First array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]]
Axis parameter not passed. The input array is flattened before deletion. [ 0 1 2 3 4 6 7 8 9 10 11]
Deleting the second column: [[ 0 2 3] [ 4 6 7] [ 8 10 11]]
Slicing with alternative values removed from the array: [ 2 4 6 8 10]
Output result:
First array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]]
Axis parameter not passed. The input array is flattened before insertion. [ 0 1 2 3 4 6 7 8 9 10 11]
Deleting the second column: [[ 0 2 3] [ 4 6 7] [ 8 10 11]]
Slice containing alternate values that have been removed 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 not a single-dimensional array it will be flattened
- `return_index`: If `true`, return the positions (indices) of the new list elements in the original list, stored as a list
- `return_inverse`: If `true`, return the positions (indices) of the original list elements in the new list, stored as a list
- `return_counts`: If `true`, return the number of occurrences of each unique element 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 ('Unique values of the first array:') u = np.unique(a) print (u) print ('\n')
print ('Indices of the unique array:') u, indices = np.unique(a, return_index = True) print (indices) print ('\n')
print ('We can see each and every index value associated with its corresponding element of the original array:') print (a) print ('\n')
print ('Indices of the unique array:') u, indices = np.unique(a, return_inverse = True) print (u) print ('\n')
print ('Indices are:') print (indices) print ('\n')
print ('Reconstruct the original array using indices:') print (u[indices]) print ('\n')
print ('Return the counts of the unique elements:') u, counts = np.unique(a, return_counts = True) print (u) print (counts)
Output result:
First array: [5 2 6 2 7 5 6 8 2 9]
Unique values of the first array: [2 5 6 7 8 9]
Indices of the unique array: [1 0 2 4 7 9]
We can see each and every index value associated with its corresponding element of the original array: [5 2 6 2 7 5 6 8 2 9]
Indices of the unique array: [2 5 6 7 8 9]
Indices are: [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 counts of the unique elements: [2 5 6 7 8 9] [3 2 2 1 1 1] ```