gpt4 book ai didi

python - Numpy C-Api 将顺序从列更改为行

转载 作者:行者123 更新时间:2023-11-30 17:04:27 25 4
gpt4 key购买 nike

将 numpy 数组传递给 c 扩展时更改其顺序的最佳方法是什么?对于接口(interface),我使用 cython 和 numpy 的 PyArray_DATA

假设我有 x = np.empty((2000,10)) 并且我想将该数组传递给 C,使得 x[2000] 对应于Python 中的 x[0,1]x[1]x[1,0]。我该怎么做?

到目前为止,我尝试了 np.copy(oder='C')np.transpose()np.reshape((- 1))np.flatten

最佳答案

您似乎对“列”和“行”这两个术语感到困惑。 行优先order='c'列优先order='f'。这是一个显示aht的示例

shape = (2000, 10)
buffer = "".join("{:5d}".format(i) for i in range(np.prod(shape)))
x = np.ndarray(shape, 'S5', order='f', buffer=buffer)
print x[0, 1]
# ' 2000'
print x.flags
# C_CONTIGUOUS : False
# F_CONTIGUOUS : True
# OWNDATA : False
# WRITEABLE : False
# ALIGNED : False
# UPDATEIFCOPY : False
x = np.ndarray((2000, 10), 'S5', order='c', buffer=buffer)
print x[0, 1]
# ' 1'
print x.flags
# C_CONTIGUOUS : True
# F_CONTIGUOUS : False
# OWNDATA : False
# WRITEABLE : False
# ALIGNED : False
# UPDATEIFCOPY : False

有几种方法可以在 numpy 中强制进行内存布局,以下是一些:

# When you create the array:
x = np.empty((2000, 10), order='f')

# Check the order and copy if needed:
x = np.asfortranarray(x)

# Force a copy:
x_fortran = x.copy(order='f')

请注意,所有这 3 个方法都会生成一个“相同”的 numpy 数组,即对于所有 Python 代码来说都相同:

print np.all(x.copy('c') == x.copy('f'))
# True

关于python - Numpy C-Api 将顺序从列更改为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com