【发布时间】:2011-09-21 19:16:48
【问题描述】:
这样可以更好地理解事物。这不是我需要解决的实际问题。 cstringIO 对象应该在行上模拟字符串、文件以及迭代器。它是否也模拟缓冲区?在任何情况下,理想情况下应该能够如下构造一个 numpy 数组
import numpy as np
import cstringIO
c = cStringIO.StringIO('\x01\x00\x00\x00\x01\x00\x00\x00')
#Trying the iterartor abstraction
b = np.fromiter(c,int)
# The above fails with: ValueError: setting an array element with a sequence.
#Trying the file abstraction
b = np.fromfile(c,int)
# The above fails with: IOError: first argument must be an open file
#Trying the sequence abstraction
b = np.array(c, int)
# The above fails with: TypeError: long() argument must be a string or a number
#Trying the string abstraction
b = np.fromstring(c)
#The above fails with: TypeError: argument 1 must be string or read-only buffer
b = np.fromstring(c.getvalue(), int) # does work
我的问题是它为什么会这样。
出现的实际问题如下:我有一个生成元组的迭代器。我有兴趣从元组的一个组件中创建一个 numpy 数组,尽可能少地复制和复制。我的第一个切入点是继续将产生的元组的有趣组件写入 StringIO 对象,然后将其内存缓冲区用于数组。我当然可以使用getvalue(),但会创建并返回一个副本。什么是避免额外复制的好方法。
【问题讨论】:
-
这个projects.scipy.org/numpy/ticket/1634似乎有一张罚单不知道这是否意味着这被认为是一个错误。我仍然想知道如何避免复制。
-
案例 1 的故障症状已更改:ValueError: invalid literal for long() with base 10: '\x01'