0% found this document useful (0 votes)
7 views3 pages

NumPy Array Sorting Techniques

The document provides a series of exercises related to sorting and searching using NumPy, including sorting arrays along different axes, creating structured arrays, and partitioning arrays. It includes sample outputs for various operations such as sorting by height and class, obtaining sorted indices, and sorting complex numbers. Each exercise is designed to demonstrate specific functionalities of the NumPy library.

Uploaded by

statusguru4u
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

NumPy Array Sorting Techniques

The document provides a series of exercises related to sorting and searching using NumPy, including sorting arrays along different axes, creating structured arrays, and partitioning arrays. It includes sample outputs for various operations such as sorting by height and class, obtaining sorted indices, and sorting complex numbers. Each exercise is designed to demonstrate specific functionalities of the NumPy library.

Uploaded by

statusguru4u
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NUMPY SORTING & SEARCHING

1. Write a NumPy program to sort a given array of shape 2 along the first
axis, last axis and on flattened array.
Expected Output:
Original array:
[[10 40]
[30 20]]
Sort the array along the first axis:
[[10 20]
[30 40]]
Sort the array along the last axis:
[[10 40]
[20 30]]
Sort the flattened array:
[10 20 30 40]

2. Write a NumPy program to create a structured array from given


student name, height, class and their data types. Now sort the array on
height.
Sample Output:
Original array:
[(b'James', 5, 48.5 ) (b'Nail', 6, 52.5 ) (b'Paul', 5, 42.1 )
(b'Pit', 5, 40.11)]
Sort by height
[(b'Pit', 5, 40.11) (b'Paul', 5, 42.1 ) (b'James', 5, 48.5 )
(b'Nail', 6, 52.5 )]

3. Write a NumPy program to create a structured array from given


student name, height, class and their data types. Now sort by class, then
height if class are equal.
Expected Output:
Original array:
[(b'James', 5, 48.5 ) (b'Nail', 6, 52.5 ) (b'Paul', 5, 42.1 ) (b'Pit', 5, 40.11)]
Sort by age, then height if class are equal:
[(b'Pit', 5, 40.11) (b'Paul', 5, 42.1 ) (b'James', 5, 48.5 ) (b'Nail', 6, 52.5 )]

Data Science 8802551718/9990951718 NumPy Sorting & Searching


NUMPY SORTING & SEARCHING

4. Write a NumPy program to sort the student id with increasing height of


the students from given students id and height. Print the integer indices
that describes the sort order by multiple columns and the sorted data.
Expected Output:
Sorted indices:
[4 0 5 3 6 1 2]
Sorted data:
1682 38.0
1023 40.0
5241 40.0
1671 41.0
4532 42.0
5202 42.0
6230 45.0

5. Write a NumPy program to get the indices of the sorted elements of a


given array.
Expected Output:
Original array:
[1023 5202 6230 1671 1682 5241 4532]
Indices of the sorted elements of a given array:
[0 3 4 6 1 5 2]

6. Write a NumPy program to sort a given complex array using the real
part first, then the imaginary part.
Note: "busday" default of Monday through Friday being valid days.
Sample Output:
Original array:
[(1+2j), (3-1j), (3-2j), (4-3j), (3+5j)]
Sorted a given complex array using the real part first, then the imaginary
part.
[1.+2.j 3.-2.j 3.-1.j 3.+5.j 4.-3.j]

7. Write a NumPy program to partition a given array in a specified


position and move all the smaller elements values to the left of the
Data Science 8802551718/9990951718 NumPy Sorting & Searching
NUMPY SORTING & SEARCHING

partition, and the remaining values to the right, in arbitrary order (based
on random choice).
Sample output:
Original array:
[ 70 50 20 30 -11 60 50 40]
After partitioning on 4 the position:
[-11 30 20 40 50 50 60 70]

8. Write a NumPy program to sort the specified number of elements


from beginning of a given array.
Sample output:
Original array:
[0.39536213 0.11779404 0.32612381 0.16327394 0.98837963
0.25510787 0.01398678 0.15188239 0.12057667 0.67278699]
Sorted first 5 elements:
[0.01398678 0.11779404 0.12057667 0.15188239 0.16327394
0.25510787 0.39536213 0.98837963 0.32612381 0.67278699]

Data Science 8802551718/9990951718 NumPy Sorting & Searching

Common questions

Powered by AI

Using NumPy to sort a specified number of elements from the start of an array involves selecting the portion of the array you want to sort and applying the sort function to that slice. For instance, given an array [0.39536213, 0.11779404, 0.32612381, 0.16327394, 0.98837963, 0.25510787, 0.01398678, 0.15188239, 0.12057667, 0.67278699], sorting the first 5 elements results in [0.01398678, 0.11779404, 0.12057667, 0.15188239, 0.16327394] for the initial segment, maintaining the unsorted order for the remainder .

A major challenge in sorting structured arrays by multiple keys in NumPy includes managing tied values—ensuring the secondary key appropriately resolves ties. The solution involves specifying a lexicographical order using a sequence of keys, sorted in priority as needed. The sort function must be provided with a list of column names that act as keys, ordered both initially and in tie-breaking arrangements. This approach demands careful planning of key priority and proper array structure definition to successfully accomplish the task .

NumPy provides the argsort function to return the indices that would sort an array. This function returns an array of indices that sort the input array. For instance, given an array [1023, 5202, 6230, 1671, 1682, 5241, 4532], the sorted indices would be [0, 3, 4, 6, 1, 5, 2], reflecting the order in which these positions would arrange the array into a sorted sequence .

In NumPy, choosing an axis for sorting determines the direction along which elements sort, effectively altering the structure interaction. For instance, consider an array [[10, 40], [30, 20]]. Sorting along axis 0 (vertical) results in each column being sorted independently, yielding [[10, 20], [30, 40]], illustrating a columnar data arrangement. Axis 1 (horizontal) sorts each row, resulting in [[10, 40], [20, 30]], which may be necessary for simplifying row-based calculations or observation-level analyses. This distinction allows for tailored data manipulation approaches aligned with analysis goals .

NumPy allows array partitioning using the partition function, which rearranges elements so that all values smaller than a particular value appear before all larger values, without necessarily sorting the whole array. For example, with the array [70, 50, 20, 30, -11, 60, 50, 40], partitioning around the index 4 results in [-11, 30, 20, 40, 50, 50, 60, 70], placing values smaller than the 4th value (50) to the left, larger ones to the right, in arbitrary order .

To sort a complex array using NumPy by both the real and imaginary parts, you can first sort by the real parts and then by the imaginary parts. NumPy allows for this by passing a key to the sort function, where you specify an array of tuples containing both the real and imaginary parts for comparison. For example, given an array [(1+2j), (3-1j), (3-2j), (4-3j), (3+5j)], the sorted result would be [1.+2.j, 3.-2.j, 3.-1.j, 3.+5.j, 4.-3.j].

Sorting complex arrays by real and imaginary parts has significance in fields requiring complex number manipulations, such as signal processing, electrical engineering, and quantum mechanics. By organizing data in this way, computational tasks like filtering or fast Fourier transforms (FFTs) benefit from simplified operations on parts of the data that share real or imaginary characteristics. For instance, in signal processing, one might sort complex frequency coefficients to align frequencies by magnitude—real part—while handling phase shifts—imaginary part—more predictably .

Partitioning in NumPy helps in efficiently dividing data into different segments based on specified criteria, facilitating focused analyses or separate processing. It is particularly useful in scenarios such as optimizing quicksort algorithms, where partitioning accelerates sorting by reducing sub-array scopes. In data science, partitioning can help in clustering, decision tree modeling, or anomaly detection by segmenting datasets into sub-arrays of interest, allowing analysts to concentrate on particular subsets for exploratory analysis or testing hypotheses .

To sort a structured NumPy array by height and then by class for identical heights, you need to first define the structure of the array with fields such as name, class, and height. Then use the sort function specifying the fields on which you want to sort. In this case, sort first by 'height', and then by 'class' for those with identical 'height'. For example, an array [(b'James', 5, 48.5), (b'Nail', 6, 52.5), (b'Paul', 5, 42.1), (b'Pit', 5, 40.11)] sorted by class then height would be [(b'Pit', 5, 40.11), (b'Paul', 5, 42.1), (b'James', 5, 48.5), (b'Nail', 6, 52.5)].

Sorting an array along different axes alters the approach in how the elements are re-ordered. When sorting along axis 0, the sort is performed column-wise, affecting each sub-array independently. Axis 1 results in row-wise sorting. A flattened array sort disregards the multi-dimensional structure. For example, a 2D array [[10 40], [30 20]] sorted along axis 0 gives [[10 20], [30 40]], along axis 1 gives [[10 40], [20 30]], and as a flattened array gives [10 20 30 40]. This functionality is useful for organizing data for analysis or visual representation according to different dimensions .

You might also like