How to Efficiently Rank Elements in a NumPy Array Without Double Sorting?

DDD
Release: 2024-10-27 04:35:30
Original
863 people have browsed it

How to Efficiently Rank Elements in a NumPy Array Without Double Sorting?

Efficient Array Ranking in Python/NumPy without Double Sorting

In data analysis and machine learning, ranking items within an array is a common operation. However, it's inefficient to sort the array twice to achieve this, as it increases computational complexity. Here's a more optimal approach using NumPy:

To rank items in an array without resorting twice, follow these steps:

  1. Apply argsort once to obtain the order of the array elements.
  2. Use argsort again to rank the ordering obtained in step 1.

For example:

<code class="python">import numpy as np

array = np.array([4, 2, 7, 1])

order = array.argsort()
ranks = order.argsort()

print("Original Array:", array)
print("Ordering:", order)
print("Ranks:", ranks)</code>
Copy after login

Output:

Original Array: [4 2 7 1]
Ordering: [3 1 2 0]
Ranks: [2 1 3 0]
Copy after login

As you can see, the ranks array provides the ranking for each element in the original array without requiring double sorting.

Note that, for 2D or higher dimensional arrays, it's crucial to specify the correct axis to use for sorting by providing an axis argument to argsort.

The above is the detailed content of How to Efficiently Rank Elements in a NumPy Array Without Double Sorting?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!