代码之家  ›  专栏  ›  技术社区  ›  David Parks

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

  •  0
  • David Parks  · 技术社区  · 5 年前

    我想对形状矩阵进行排序 (N, 2) 在第一列中 N &燃气轮机&燃气轮机;系统内存。

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

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

    x[:,0].argsort() 适合内存,这对memmap不起作用

    我可以用numpy memmap实现这种排序吗?

    0 回复  |  直到 5 年前
        1
  •  2
  •   user2699    5 年前

    解决方案可能很简单,使用order参数将 sort . 当然 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

        2
  •  0
  •   David Parks    5 年前

    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 .