将numpy数组转换为C连续顺序的最便宜方法? [英] Cheapest way to get a numpy array into C-contiguous order?

查看:345
本文介绍了将numpy数组转换为C连续顺序的最便宜方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码生成一个C连续的numpy数组:

The following produces a C-contiguous numpy array:

import numpy

a = numpy.ones((1024,1024,5))

现在,如果我将其切片,结果可能不再相同.例如:

Now if I slice it, the result may not longer be the same. For example:

bn = a[:, :, n]

,其中n从0到4. 我的问题是我需要bn是C连续的,并且需要对a的许多实例进行此操作.我只需要每个bn一次,并且想避免这样做

with n from 0 to 4. My problem is that I need bn to be C-contiguous, and I need to do this for many instances of a. I just need each bn once, and want to avoid doing

bn  = bn.copy(order='C')

我也不想这样重写代码

a = numpy.ones((5,1024,1024))

是否有比复制副本更快,更便宜的获取方式?

Is there a faster, cheaper way to get bn than doing the copy?

背景:

我想使用

import hashlib

hashlib.sha1(a[:, :, n]).hexdigest()

不幸的是,这会抛出ValueError,抱怨订单.因此,如果还有另一种获取我想要的哈希的快速方法,我也将使用它.

Unfortunately, this will throw a ValueError, complaining about the order. So if there is another fast way to get the hash I want, I'd also use it.

推荐答案

按现状,将切片bn强制转换为C连续顺序的任何尝试都将创建一个副本.

As things stand, any attempt to coerce the slice bn to C contiguous order is going to create a copy.

如果您不想更改开始的形状(并且不需要C顺序的a本身),则一种可能的解决方案是以Fortran顺序的数组a开始:

If you don't want to change the shapes you're starting with (and don't need a itself in C order), one possible solution is to start with the array a in Fortran order:

>>> a = numpy.ones((1024, 1024, 5), order='f')

这些切片也是F连续的:

The slices are also then F-contiguous:

>>> bn = a[:, :, 0]
>>> bn.flags
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : False
  ...

这意味着切片bn的转置将处于C顺序,并且转置不会创建副本:

This means that the transpose of the slice bn will be in C order and transposing does not create a copy:

>>> bn.T.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  ...

然后您可以对切片进行哈希处理:

And you can then hash the slice:

>>> hashlib.sha1(bn.T).hexdigest()
'01dfa447dafe16b9a2972ce05c79410e6a96840e'

这篇关于将numpy数组转换为C连续顺序的最便宜方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆