NumPy array sorting
Sort arrays
Sort arrays means sorting elements in a specific order. The order can be numerical size, alphabetical order, ascending or descending order, etc.
NumPy'sndarray
The object provides a name calledsort()
function used to sort arrays.
Example:
import numpy as np arr = ([3, 2, 0, 1]) print((arr))
Output:
[0 1 2 3]
Notice:
sort()
The method will return a copy of the array, and the original array will not be modified. You can sort other data types such as string arrays, boolean arrays, etc.
Sort two-dimensional arrays
For two-dimensional arrays,sort()
The method will sort each row.
Example:
import numpy as np arr = ([[3, 2, 4], [5, 0, 1]]) print((arr))
Output:
[[0 1 2]
[3 4 5]]
practise
Use NumPy to sort the following arrays correctly:
arr = ([3, 2, 0, 1]) x = ( # Please fill in the code here) print(x)
answer:
x = (arr)
NumPy array filtering
Filter arrays
Filtering an array refers to selecting some elements from an existing array and creating a new array.
In NumPy, you can use a list of boolean indexes to filter arrays. A boolean index list is a boolean list corresponding to an array index.
If the value at the index isTrue
, then the element will be included in the filtered array; ifFalse
, it will be excluded.
Example:
import numpy as np arr = ([41, 42, 43, 44]) x = [True, False, True, False] newarr = arr[x] print(newarr)
Output:
[41 43]
explain:
New arraynewarr
Only includearr
Elements with indexes of 0 and 2, becausex
The value at the corresponding index isTrue
。
Create filtered array
Normally, we need to create filtered arrays based on conditions.
Example:
Return only elements greater than 42:
import numpy as np arr = ([41, 42, 43, 44]) filter_arr = arr > 42 newarr = arr[filter_arr] print(filter_arr) print(newarr)
Output:
[False True True True]
[43 44]
Return only even elements:
import numpy as np arr = ([1, 2, 3, 4, 5, 6, 7]) filter_arr = arr % 2 == 0 newarr = arr[filter_arr] print(filter_arr) print(newarr)
Output:
[False True False True False True False]
[2 4 6]
Create filters directly from arrays
NumPy provides a cleaner way to create filtered arrays, i.e. use arrays directly in conditions:
Example:
Return only elements greater than 42:
import numpy as np arr = ([41, 42, 43, 44]) newarr = arr[arr > 42] print(newarr)
Output:
[43 44]
Return only even elements:
import numpy as np arr = ([1, 2, 3, 4, 5, 6, 7]) newarr = arr[arr % 2 == 0] print(newarr)
Output:
[2 4 6]
practise
Using the direct filtering method of NumPy, filter out all elements with even squares from the following array:
import numpy as np arr = np.
Random numbers in NumPy
What are random numbers?
Random numbers refer to data whose values cannot be predicted by deterministic methods. Generally speaking, random numbers refer to numbers that are evenly distributed within a certain range.
In a computer, it is impossible to generate true random numbers due to the determinism of the program. Therefore, pseudo-random numbers are usually used instead of random numbers. Pseudo-random numbers are generated by algorithms, but they look like random numbers.
Random number generation in NumPy
NumPy providesrandom
The module is used to generate random numbers. This module provides a variety of methods to generate random numbers of different types and distributions.
Generate random integers
randint(low, high, size)
: Generate random integers within the specified range.low
: The lower limit, default is 0.high
: upper limit, excluding upper limit itself.size
: Output the shape of the array.
Example:
import numpy as np # Generate 10 random integers between 0 and 100x = (0, 101, size=10) print(x)
Generate random floating point numbers
rand(size)
: Generates a random floating point number between 0 and 1.size
: Output the shape of the array.
Example:
import numpy as np # Generate 5 random floating point numbersx = (5) print(x)
Generate random numbers from array
choice(a, size, replace)
: From the arraya
Randomly select elements in .a
: Source array.size
: Output the shape of the array.replace
: Whether to allow repeated selection of elements, the default isFalse
。
Example:
import numpy as np # Randomly select 3 elements from array [1, 2, 3, 4, 5]x = ([1, 2, 3, 4, 5], size=3) print(x)
Generate random numbers of the specified distribution
NumPy also provides other methods to generate random numbers for a specific distribution, such as normal distribution, uniform distribution, exponential distribution, etc.
randn(size)
: Generate random numbers that obey standard normal distribution.randm(size)
: Generate random integers that obey uniform distribution.beta(a, b, size)
: Generate random numbers that obey the Beta distribution.gamma(shape, scale, size)
: Generate random numbers that obey Gamma distribution.poisson(lam, size)
: Generate random integers that obey Poisson distribution.
For example, generate 10 random numbers that obey the standard normal distribution:
import numpy as np x = (10) print(x)
practise
- use
randint
The method generates an array of 20 random integers between 100 and 200. - use
rand
The method generates an array of 15 random floating point numbers between 0 and 1. - From an array
[1, 3, 5, 7, 9]
10 elements are randomly selected and repeated. - Generate 5 random numbers that obey the standard normal distribution.
Solution
import numpy as np # 1. Generate a random array of integers using the randint methodrandom_ints = (100, 201, size=20) print(random_ints) # 2. Generate a random floating point array using the rand methodrandom_floats = (15) print(random_floats) # 3. Randomly select elements from the arrayrandom_elements = ([1, 3, 5, 7, 9], size=10, replace=True) print(random_elements) # 4. Generate random numbers that obey standard normal distributionsnormal_randoms = (5) print(normal_randoms)
at last
The above is the detailed explanation of NumPy array sorting, filtering and random number generation. For more information about NumPy array sorting filtering and generation, please pay attention to my other related articles!