我有一個像這樣的二維 numpy 陣列:
[[4 5 2]
[5 5 1]
[5 4 5]
[5 3 4]
[5 4 4]
[4 3 2]]
我想通過在陣列中找到這樣的序列來排序/聚類這個陣列row[0]>=row[1]>=row[2],row[0]>=row[2]>row[1]...所以陣列的行是有序的。
我嘗試使用代碼:lexdf = df[np.lexsort((df[:,2], df[:,1],df[:,0]))][::-1],但這不是我想要的。lexsort 的輸出:
[[5 5 1]
[5 4 5]
[5 4 4]
[5 3 4]
[4 5 2]
[4 3 2]]
我想要的輸出:
[[5 5 1]
[5 4 4]
[4 3 2]
[5 4 5]
[5 3 4]
[4 5 2]]
或將其分為三部分:
[[5 5 1]
[5 4 4]
[4 3 2]]
[[5 4 5]
[5 3 4]]
[[4 5 2]]
而且我想將此應用于具有更多列的陣列,因此最好不要迭代。有什么想法可以產生這種輸出嗎?
uj5u.com熱心網友回復:
我不知道如何在 numpy 中做到這一點,除了可能有一些奇怪的 function 黑客numpy.split。
這是一種使用 python 串列獲取組的方法:
from itertools import groupby, pairwise
def f(sublist):
return [x <= y for x,y in pairwise(sublist)]
# NOTE: itertools.pairwise requires python>=3.10
# For python<=3.9, use one of those alternatives:
# * more_itertools.pairwise(sublist)
# * zip(sublist, sublist[1:])
a = [[4, 5, 2],
[5, 5, 1],
[5, 4, 5],
[5, 3, 4],
[5, 4, 4],
[4, 3, 2]]
b = [list(g) for _,g in groupby(sorted(a, key=f), key=f)]
print(b)
# [[[4, 3, 2]],
# [[5, 4, 5], [5, 3, 4], [5, 4, 4]],
# [[4, 5, 2], [5, 5, 1]]]
注意:groupby sorted 的組合實際上有點低效,因為sorted需要 n log(n) 時間。線性替代方法是使用串列字典進行分組。請參閱模塊中的實體函式itertoolz.groupbytoolz。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/347365.html
上一篇:確定給定點是否會創建一個島嶼
