gpt4 book ai didi

python - 在 Python 中协调 np.fromiter 和多维数组

转载 作者:太空狗 更新时间:2023-10-29 20:15:24 24 4
gpt4 key购买 nike

我喜欢使用 numpy 中的 np.fromiter,因为它是一种构建 np.array 对象的资源惰性方式。但是,它似乎不支持多维数组,这也很有用。

import numpy as np

def fun(i):
""" A function returning 4 values of the same type.
"""
return tuple(4*i + j for j in range(4))

# Trying to create a 2-dimensional array from it:
a = np.fromiter((fun(i) for i in range(5)), '4i', 5) # fails

# This function only seems to work for 1D array, trying then:
a = np.fromiter((fun(i) for i in range(5)),
[('', 'i'), ('', 'i'), ('', 'i'), ('', 'i')], 5) # painful

# .. `a` now looks like a 2D array but it is not:
a.transpose() # doesn't work as expected
a[0, 1] # too many indices (of course)
a[:, 1] # don't even think about it

如何让 a 成为多维数组,同时保持这种基于生成器的惰性构造?

最佳答案

就其本身而言,np.fromiter仅支持构建一维数组,因此,它期望一个可迭代对象将产生单个值而不是元组/列表/序列等。解决此限制的一种方法是使用 itertools.chain.from_iterable懒惰地将生成器表达式的输出“解包”为单个一维值序列:

import numpy as np
from itertools import chain

def fun(i):
return tuple(4*i + j for j in range(4))

a = np.fromiter(chain.from_iterable(fun(i) for i in range(5)), 'i', 5 * 4)
a.shape = 5, 4

print(repr(a))
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11],
# [12, 13, 14, 15],
# [16, 17, 18, 19]], dtype=int32)

关于python - 在 Python 中协调 np.fromiter 和多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34018470/

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