Numpy memmap按列对大型矩阵进行就地排序

2024-06-12 08:41:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对第一列(N, 2)形状的矩阵进行排序,其中N>;系统内存。你知道吗

使用内存numpy,您可以执行以下操作:

x = np.array([[2, 10],[1, 20]])
sortix = x[:,0].argsort()
x = x[sortix]

但这似乎需要x[:,0].argsort()放入内存,这对于N>;系统内存的memmap不起作用(如果这个假设是错误的,请纠正我)。你知道吗

我能用numpy memmap实现这类功能吗?你知道吗

(假设heapsort用于排序,并使用简单的数字数据类型)


Tags: 内存gt功能numpy排序系统错误np
2条回答

解决方案可能很简单,将order参数用于in-placesort。当然,order需要字段名,因此必须首先添加这些字段名。你知道吗

d = x.dtype
x = x.view(dtype=[(str(i), d) for i in range(x.shape[-1])])
array([[(2, 10)],
   [(1, 20)]], dtype=[('0', '<i8'), ('1', '<i8')])

字段名是字符串,与列索引相对应。排序可以在适当的地方进行

x.sort(order='0', axis=0)

然后转换回具有原始数据类型的常规数组

x.view(d)
array([[ 1, 20],
   [ 2, 10]])

尽管您可能需要根据数据在磁盘上的存储方式来更改视图的获取方式,但这应该是可行的,请参见the docs

For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results.

@user2699漂亮地回答了这个问题。我将添加这个解决方案作为一个简化的示例,以防您不介意将数据保留为structured array,这样就消除了视图。你知道吗

import numpy as np

filename = '/tmp/test'
x = np.memmap(filename, dtype=[('index', '<f2'),('other1', '<f2'),('other2', '<f2')], mode='w+', shape=(2,))
x[0] = (2, 10, 30)
x[1] = (1, 20, 20)
print(x.shape)
print(x)
x.sort(order='index', axis=0, kind='heapsort')
print(x)

(2,)
[(2., 10., 30.) (1., 20., 20.)]
[(1., 20., 20.) (2., 10., 30.)]

数据类型格式也是documented here。你知道吗

相关问题 更多 >