簡體   English   中英

多維數組排序 - Python

[英]Sorting Multi-Dimensional Array - 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]

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

你能用熊貓嗎? 如果是這樣的話,

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)

請注意,這里我假設(基於我對問題的理解)您想要根據第 2 列的值除以第 3 列的值進行排序。 如果是這種情況,輸出示例將翻轉前兩個元素(因為 25/2 > 10/1)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM