numpy memmap就地按列排序大型矩阵

时间:2019-03-13 20:38:27

标签: python numpy python-3.6 memmap

我想在(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进行排序,并使用简单的数值数据类型)

2 个答案:

答案 0 :(得分:1)

使用就地sort的order参数,解决方案可能很简单。当然,void display() { // [...] // install program glUseProgram(diffuse_prog_obj); // set light positions and colors glUniform3f(loc_l_pos[0], Light1x, Light1y, Light1z); glUniform3f(loc_l_pos[1], Light2x, Light2y, Light2z); glUniform3f(loc_l_col[0], Light1r, Light1g, Light1b); glUniform3f(loc_l_col[1], Light2r, Light2g, Light2b); // set object color glColor3f(1, 1, 0.5); //Draw the squares, select column for (int i = 0; i <= 9; i++) { //Select row for (int j = 0; j <= 9; j++) { glBegin(GL_POLYGON); std::cout << R[i][j] << " " << G[i][j] << " " << B[i][j] << endl; glNormal3f(Nx[i][j], Ny[i][j], Nz[i][j]); glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]); glNormal3f(Nx[i][j+1], Ny[i][j+1], Nz[i][j+1]); glVertex3f(surfaceX[i][j+1], surfaceY[i][j+1], surfaceZ[i][j+1]); glNormal3f(Nx[i+1][j+1], Ny[i+1][j+1], Nz[i+1][j+1]); glVertex3f(surfaceX[i+1][j+1], surfaceY[i+1][j+1], surfaceZ[i+1][j+1]); glNormal3f(Nx[i+1][j], Ny[i+1][j], Nz[i+1][j]); glVertex3f(surfaceX[i+1][j], surfaceY[i+1][j], surfaceZ[i+1][j]); glEnd(); } } // invalidate installed program glUseProgram(0); // [...] } 需要字段名称,因此必须首先添加这些字段名称。

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)

这应该起作用,尽管您可能需要根据数据在磁盘上的存储方式来更改视图的显示方式,请参见the docs

  

对于a.view(some_dtype),如果some_dtype每个条目的字节数与上一个dtype不同(例如,将常规数组转换为结构化数组),则不能仅根据a的表面外观(由print(a)显示)。这也完全取决于a在内存中的存储方式。因此,如果a是C顺序的,fortran顺序的,定义为切片或转置的等等,则视图可能会给出不同的结果。

答案 1 :(得分:0)

@ 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.)]

dtype格式也为documented here