简体   繁体   中英

Sorting Multi-Dimensional Array - Python

from numpy import *

list = array([["A", 25, 2], ["B", 25, 3], ["C", 10, 1], ["D", 50, 25]])

How do I sort this array by descending size of 2nd element divided by 3rd element. So in this case the correct arrangement would be:

["A", 25, 2], ["C", 10, 1], ["B", 25, 3], ["D", 50, 25]

import numpy as np

# Let's use a as the variable name so we don't override the list keyword
a = np.array([["A", 25, 2], ["B", 25, 3], ["C", 10, 1], ["D", 50, 25]])

# Need to convert values to int, because they are being casted as string
# in the original array (arrays only support one data type)
key_values = a[:,1].astype(int) / a[:,2].astype(int)

# Use argsort to get a sort index, then reverse the order to make it descending
index_array = np.argsort(key_values)[::-1]  # -1 reverses the order

print(a[index_array])

Output:

[['A' '25' '2']
 ['C' '10' '1']
 ['B' '25' '3']
 ['D' '50' '25']]

Can you use pandas? If so,

import numpy as np
import pandas as pd

df = pd.DataFrame(np.array([["A", 25, 2], ["B", 25, 3], ["C", 10, 1], ["D", 50, 25]]))
df[1] = pd.to_numeric(df[1])
df[2] = pd.to_numeric(df[2])
df[3] = df[1] / df[2]
sorted_list = df.sort_values(by=3, ascending=False).values[:,:3]
print(sorted_list)

array([['A', 25, 2],
       ['C', 10, 1],
       ['B', 25, 3],
       ['D', 50, 25]], dtype=object)

Note that here I'm assuming (based on how I understood the question) that you want to sort based on the value of the 2nd column divided by the 3rd column. If that's the case, the output example has the first two elements flipped (since 25/2 > 10/1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM