1

我在使用 numpy.asarray 和我无法解释的 memoryview 对象时遇到了一些奇怪的行为。这是一个在 jupyter 笔记本中使用 cython 魔法的简短示例——我只是创建了一个函数,它需要两个结构数组缓冲区并返回它们。一个有两个 int,另一个有 long 和一个 int:

cdef struct S1:
    int iGroup
    int iOrder

cdef struct S2:
    long iGroup
    int iOrder

def test_struct(S1[:] s1, S2[:] s2):
    return s1, s2

现在我在 python 中创建两个数组来传递给这个函数:

dt1 = np.dtype([('iGroup', 'i4'), ('iOrder', 'i4')], align=True)
dt2 = np.dtype([('iGroup', 'i8'), ('iOrder', 'i4')], align=True)

a = np.zeros(10, dtype=dt1)
b = np.zeros(10, dtype=dt2)

x, y = test_struct(a,b)

print x
print y

<MemoryView of 'ndarray' object>
<MemoryView of 'ndarray' object>

两者都作为 MemoryView 对象成功返回。现在我想把它们变成一个 numpy 数组:

np.asarray(x)

array([(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0),
       (0, 0), (0, 0)], 
      dtype=[('iGroup', '<i4'), ('iOrder', '<i4')])


np.asarray(y)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-204-ca5459515bfd> in <module>()
----> 1 np.asarray(y)

/Users/rok/miniconda/lib/python2.7/site-packages/numpy/core/numeric.pyc in asarray(a, dtype, order)
    480 
    481     """
--> 482     return array(a, dtype, copy=False, order=order)
    483 
    484 def asanyarray(a, dtype=None, order=None):

TypeError: expected a readable buffer object

我在这里想念什么?为什么第二个结构不起作用?任何提示将非常感谢!

4

0 回答 0