我有一个键( str )和值(Value)为np.array的数据集。np.array的类型也可以是np.str_类型。
data = {"col1": np.array((1, 2, 3, 4, 5, 4, 3, 2, 1)),
"col2": np.array(list("abcdeabcd")),
"col3": np.array((10, 11, 9, 8, 7, 2, 12, 100, 1))}如何按照多个键和升序/降序进行排序,类似于使用pandas的sort_values方法:
Pandas解决方案(不需要)
df = pd.DataFrame(data)
df.sort_values(by=["col1", "col2"], ascending=[True, True])需要Numpy或基本python解决方案:
我不想使用熊猫,但理想的情况是在numpy。我知道我可以使用np.lexsort对多个列进行排序。但这并没有给我(i)做升序/降序的选择。
这是我在按col1排序,然后按升序/升序排序col2时所需要的输出:
{'col1': np.array([1, 1, 2, 2, 3, 3, 4, 4, 5]),
'col2': np.array(['a', 'd', 'b', 'c', 'b', 'c', 'a', 'd', 'e']),
'col3': np.array([10, 1, 11, 100, 12, 9, 2, 8, 7])}这是我在按col1排序,然后按升序/降序排序col2时所需要的输出:
{'col1': np.array([1, 1, 2, 2, 3, 3, 4, 4, 5]),
'col2': np.array(['d', 'a', 'c', 'b', 'c', 'b', 'd', 'a', 'e']),
'col3': np.array([1, 10, 100, 11, 9, 12, 8, 2, 7])}发布于 2021-07-22 14:23:55
您可以使用np.lexsort对列进行反排序,方法是取消排序键。请记住,不需要将实际数组传递给lexsort。对于有符号的数字数组,可以通过否定值进行反向排序。对于无符号整数,可以从最大值中减去值。字符串可以作为数字来处理,您可以基于np.unique创建一个有符号整数的查找表。
下面是数组的一个小示例:
np.random.seed(0xBEEF)
a = np.random.choice([1, 2, 3], 10)
b = np.random.choice([1.0, 2.0, 3.0], 10)
c = np.random.choice(np.array([1, 2, 3], dtype=np.uint8), 10)
d = np.random.choice(list('abc'), 10)在任何情况下,按升序排序的键都可以是数组本身。按降序排列,我们显然可以使用-a和-b。碰巧,-c也能工作:
>>> c
array([3, 1, 1, 3, 2, 2, 1, 1, 2, 3], dtype=uint8)
>>> -c
array([253, 255, 255, 253, 254, 254, 255, 255, 254, 253]这可能取决于平台表示,但在大多数流行的系统中,负数是以两种补码形式表示的,这应该工作得很好。如果您想要非常安全,可以添加一张支票,例如
if np.issubdtype(c.dtype, np.unsignedinteger):
key = np.iinfo(c.dtype).max + 1 - c当然我们有d
>>> d
array(['c', 'a', 'b', 'b', 'c', 'b', 'a', 'b', 'c', 'b'], dtype='<U1')
>>> -d
...
UFuncTypeError: ufunc 'negative' did not contain a loop with signature matching types dtype('<U1') -> dtype('<U1')在这里构造排序键的一种方法是:
lookup, key = np.unique(d, return_inverse=True)key的元素是lookup中的索引,按排序顺序排列,这意味着如果对key进行排序,那么lookup[key]的结果也将被正确排序。这意味着key.argsort()和d.argsort()是相同的,有一个额外的优势,您可以否定key。
实际上,您可以采用快捷方式编写密钥生成器,只使用此技术:
def make_key(arr, asc=True):
_, key = np.unique(arr, return_inverse=True)
if not asc:
key = np.negative(key, out=key) # Don't bother making a second array
return key因此,完整的示例可能如下所示:
def custom_lexsort(arrs, asc=True):
"""
Lexsort a collection of arrays in ascending or descending order.
Parameters
----------
arrs : sequence[array-like]
Sequence of arrays to sort.
asc : array-like[bool]
Sequence of True for ascending elements of `keys`,
False for descending. Must broadcast to `(len(arrs),)`.
"""
def make_key(a, asc):
if np.issubdtype(a.dtype, np.number):
key = a
else:
_, key = np.unique(a, return_inverse=True)
if asc:
return key
elif np.issubdtype(key.dtype, np.unsignedinteger):
return np.iinfo(key.dtype).max + 1 - key
else:
return -key
n = len(arrs)
asc = np.broadcast_to(asc, n)
keys = [make_key(*x) for x in zip(arrs, asc)]
return np.lexsort(keys[::-1])data = {"col1": np.array((1, 2, 3, 4, 5, 4, 3, 2, 1)),
"col2": np.array(list("abcdeabcd")),
"col3": np.array((10, 11, 9, 8, 7, 2, 12, 100, 1))}
idx = custom_lexsort(list(data.values()), [True, False, True])
result = {k: v[idx] for k, v in data.items()}我冒昧地颠倒了数组的顺序,因为lexsort从头到尾排序。果然:
>>> result
{'col1': array([1, 1, 2, 2, 3, 3, 4, 4, 5]),
'col2': array(['d', 'a', 'c', 'b', 'c', 'b', 'd', 'a', 'e'], dtype='<U1'),
'col3': array([ 1, 10, 100, 11, 9, 12, 8, 2, 7])}我已经包括了第三栏的排序,因为它没有害处。下面是排序数组的一个示例,其中只有前两个用于排序:
idx = custom_lexsort([data['col1'], data['col2']], [True, False])
for v in data.values():
v[:] = v[idx]https://stackoverflow.com/questions/68486204
复制相似问题