Python 带列表生成器的numpy fromiter 将numpy导入为np def gen_c(): c=np.one(5,dtype=int) j=0 t=10 而j
您只能使用创建一维数组(而不是二维数组),如- numpy.fromiter(iterable,dtype,count=-1) 从iterable对象创建新的一维数组 您可以做的一件事是将生成器函数转换为从Python 带列表生成器的numpy fromiter 将numpy导入为np def gen_c(): c=np.one(5,dtype=int) j=0 t=10 而j,python,arrays,numpy,generator,Python,Arrays,Numpy,Generator,您只能使用创建一维数组(而不是二维数组),如- numpy.fromiter(iterable,dtype,count=-1) 从iterable对象创建新的一维数组 您可以做的一件事是将生成器函数转换为从c中输出单个值,然后从中创建1D数组,然后将其重塑为(-1,5)。范例- import numpy as np def gen_c(): c = np.ones(5, dtype=int) j = 0 t = 10 while j < t:
c
中输出单个值,然后从中创建1D数组,然后将其重塑为(-1,5)
。范例-
import numpy as np
def gen_c():
c = np.ones(5, dtype=int)
j = 0
t = 10
while j < t:
c[0] = j
yield c.tolist()
j += 1
# What I did:
# res = np.array(list(gen_c())) <-- useless allocation of memory
# this line is what I'd like to do and it's killing me
res = np.fromiter(gen_c(), dtype=int) # dtype=list ?
将numpy导入为np
def gen_c():
c=np.one(5,dtype=int)
j=0
t=10
而j
演示-
import numpy as np
def gen_c():
c = np.ones(5, dtype=int)
j = 0
t = 10
while j < t:
c[0] = j
for i in c:
yield i
j += 1
np.fromiter(gen_c(),dtype=int).reshape((-1,5))
[5]中的:%粘贴
将numpy作为np导入
def gen_c():
c=np.one(5,dtype=int)
j=0
t=10
而j
正如文档中建议的那样,只接受一维可伸缩性。
您可以使用先展平iterable,然后np.reformate()
将其恢复原状:
In [5]: %paste
import numpy as np
def gen_c():
c = np.ones(5, dtype=int)
j = 0
t = 10
while j < t:
c[0] = j
for i in c:
yield i
j += 1
np.fromiter(gen_c(),dtype=int).reshape((-1,5))
## -- End pasted text --
Out[5]:
array([[0, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[2, 1, 1, 1, 1],
[3, 1, 1, 1, 1],
[4, 1, 1, 1, 1],
[5, 1, 1, 1, 1],
[6, 1, 1, 1, 1],
[7, 1, 1, 1, 1],
[8, 1, 1, 1, 1],
[9, 1, 1, 1, 1]])
演示:
仅在Python3.6上测试,但也应与Python2一起使用。再次感谢!你回答了我所有的两个问题:DAlways很高兴能帮忙!:-)PS:事实上,在我的情况下,这个解决方案(我不是说你的,我是说我的)并没有提高性能……是的,因为
c.tolist()
比循环c
并产生每个值要快得多
import itertools
import numpy as np
def fromiter2d(it, dtype):
# clone the iterator to get its length
it, it2 = itertools.tee(it)
length = sum(1 for _ in it2)
flattened = itertools.chain.from_iterable(it)
array_1d = np.fromiter(flattened, dtype)
array_2d = np.reshape(array_1d, (length, -1))
return array_2d
>>> iter2d = (range(i, i + 4) for i in range(0, 12, 4))
>>> from_2d_iter(iter2d, int)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])