猿问

多维数组排序 - Python

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

如何按第二个元素除以第三个元素的降序大小对该数组进行排序。所以在这种情况下,正确的安排是:

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


神不在的星期二
浏览 208回答 2
2回答

胡子哥哥

import numpy as np# Let's use a as the variable name so we don't override the list keyworda = 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 descendingindex_array = np.argsort(key_values)[::-1]  # -1 reverses the orderprint(a[index_array])输出:[['A' '25' '2'] ['C' '10' '1'] ['B' '25' '3'] ['D' '50' '25']]

隔江千里

你能用熊猫吗?如果是这样,import numpy as npimport pandas as pddf = 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)。
随时随地看视频慕课网APP

相关分类

Python
我要回答