2 回答
TA贡献1825条经验 获得超6个赞
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])
输出:
[['A' '25' '2']
['C' '10' '1']
['B' '25' '3']
['D' '50' '25']]
TA贡献1906条经验 获得超10个赞
你能用熊猫吗?如果是这样,
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)
请注意,这里我假设(基于我对问题的理解)您想要根据第二列除以第三列的值进行排序。如果是这种情况,输出示例的前两个元素将被翻转(因为 25/2 > 10/1)。
添加回答
举报