How can I 'zip sort' parallel numpy arrays?

Learn, how to 'zip sort' parallel numpy arrays in Python?
Submitted by Pranit Sharma, on January 19, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose we have two parallel lists and we want to sort them by the order of the elements in the first.

We need to sort them using NumPy arrays without unpacking them into conventional Python lists.

'zip sort' parallel numpy arrays

For this purpose, we first need to find a permutation that sorts the array. We can use argsort for this.

Now we will apply the same permutation on the other array and store the result in B.

Let us understand with the help of an example,

Python code to 'zip sort' parallel numpy arrays

# Import numpy
import numpy as np

# Creating an array
arr = np.array([2, 3, 1])

# Display original array
print("Original Array:\n",arr,"\n")

# Sorting array
res = np.random.shuffle(arr)

# Applying same permutation 
# on the other array
B = np.array([4, 6, 7])

# Getting result
res = B[res]

# Display result
print("Result:\n",res)

Output

Example: How can I 'zip sort' parallel numpy arrays?

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.