我可以防止numpy.array将元素转换为numpy数组吗? [英] Can I prevent numpy.array from casting the elements as numpy arrays?
问题描述
我正在尝试将以下内容转换为间隔对象的2x2 numpy数组:
I am using trying to convert the following to a 2x2 numpy array of interval objects:
from interval import interval # from the "pyinterval" package
import numpy as np
np.array([
[interval([1.0, 2.0]), interval([1.0, 2.0])],
[interval([1.0, 2.0]), interval([1.0, 2.0])]
])
不幸的是,此操作将间隔强制转换为numpy数组,并给了我2x2x1x2矩阵.我有什么办法可以防止这种情况发生在numpy数组或矩阵上?
Unfortunately, this operation casts the intervals as numpy arrays, and gives me a 2x2x1x2 matrix. Is there any way I can prevent this from happening with numpy arrays or matrices?
我能够通过首先填充一个空数组来获得所需的结果,其中jac是间隔列表的列表:
I was able to get the desired result by populating an empty array first, where jac is a list of lists of intervals:
arr = np.empty(shape=(2,2), dtype=interval)
for i in range(len(arr)):
for j in range(len(arr)):
arr[i][j] = jac[i][j]
话虽如此,我怀疑还有一种更优雅的方法可以实现这一目标.有没有更多的"pythonic"方式来做到这一点?
That being said, I suspect there's a more elegant way to achieve this. Is there a more "pythonic" way to do this?
推荐答案
即使np.array
用dtype=object
调用,似乎numpy也会将Sequence
之类的任何内容强制转换为新维度.您可以通过使用dtype=object
直接创建一个空数组,然后手动填充它来解决此问题.
It seems like numpy will coerce anything Sequence
-like into a new dimension, even if np.array
is called with dtype=object
. You can work around this by directly making an empty array with dtype=object
and then filling it manually.
interval_list = get_intervals()
interval_array = np.ndarray(len(interval_list), dtype=object)
for i, interv in enumerate(interval_list):
interval_array[i] = interv
这篇关于我可以防止numpy.array将元素转换为numpy数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!