我有以下numpy数组(具有字符串,字典和数字),并希望根据最后一列(数字)对该数组进行排序
X=[['few' {'age': 'young'} {'salary': 'low'} 0.8]
['few' {'salary': 'low'} {'age': 'young'} 0.3]
['few' {'age': 'young'} {'salary': 'medium'} 0]
...
['most' {'salary': 'medium'} {'education': 'upper'} 0.125]
['most' {'education': 'upper'} {'salary': 'high'} 0]
['most' {'salary': 'high'} {'education': 'upper'} 1]]
答案 0 :(得分:1)
这可能是使用最后一列X[-1]
作为排序key
import numpy as np
X=np.array([['few', {'age': 'young'}, {'salary': 'low'}, 0.8],
['few', {'salary': 'low'}, {'age': 'young'}, 0.3],
['few', {'age': 'young'}, {'salary': 'medium'}, 0],
['most', {'salary': 'high'}, {'education': 'upper'}, 1]])
X = np.array(sorted(X, key=lambda X: X[-1]) )
# array([['few', {'age': 'young'}, {'salary': 'medium'}, 0],
# ['few', {'salary': 'low'}, {'age': 'young'}, 0.3],
# ['few', {'age': 'young'}, {'salary': 'low'}, 0.8],
# ['most', {'salary': 'high'}, {'education': 'upper'}, 1]],
# dtype=object)
另一种选择是使用itemgetter
,其中-1
表示最后一个条目/索引
from operator import itemgetter
X = sorted(X, key=itemgetter(-1))