0
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]

4
  • Is "array -> list -> sorted list -> new array" approach "allowed"? Commented Aug 27, 2020 at 22:10
  • 1
    just a note, do not use list (or "reserved words" in general) as variable name Commented Aug 27, 2020 at 22:12
  • Generate a vector with the computed values, sort the vector with numpy.argsort, then pass the returned index array and the original list to take_along_axis. numpy.org/doc/stable/reference/generated/… Commented Aug 27, 2020 at 22:15
  • 1
    using numpy.array, all elements are of the same type, string in this case. Are you sure numpy.array is what you want/need in this case? Commented Aug 27, 2020 at 22:16

2 Answers 2

1
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']]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks. what if i wanted to convert my original array to the output?
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.