我想在NumPy数组中存储时间间隔(使用它的特定算术)。如果我使用我自己的Interval类,它可以工作,但是我的课很差,我的Python知识有限。我知道pyInterval这是非常完整的。它涵盖了我的问题。唯一不起作用的是将PyInterval对象存储在NumPy数组中。为什么NumPy将对象转换为浮动对象?
class Interval(object):
def __init__(self, lower, upper = None):
if upper is None:
self.upper = self.lower = lower
elif lower <= upper:
self.lower = lower
self.upper = upper
else:
raise ValueError(f"Lower is bigger than upper! {lower},{upper}")
def __repr__(self):
return "Interval " + str((self.lower,self.upper))
def __mul__(self,another):
values = (self.lower * another.lower,
self.upper * another.upper,
self.lower * another.upper,
self.upper * another.lower)
return Interval(min(values), max(values))
import numpy as np
from interval import interval
i = np.array([Interval(2,3), Interval(-3,6)], dtype=object) # My class
ix = np.array([interval([2,3]), interval([-3,6])], dtype=object) # pyInterval
这些结果
In [30]: i
Out[30]: array([Interval (2, 3), Interval (-3, 6)], dtype=object)
In [31]: ix
Out[31]:
array([[[2.0, 3.0]],
[[-3.0, 6.0]]], dtype=object)
从pyInterval的间隔已经铸成花车的名单列表。它不会是一个问题,如果他们保持区间算术......
In [33]: i[0] * i[1]
Out[33]: Interval (-9, 18)
In [34]: ix[0] * ix[1]
Out[34]: array([[-6.0, 18.0]], dtype=object)
Out[33]
是希望输出。使用pyInterval的输出不正确。显然,使用原始pyInterval它就像一个魅力
In [35]: interval([2,3]) * interval([-3,6])
Out[35]: interval([-9.0, 18.0])
Here是pyInterval源代码。我不明白为什么使用这个对象NumPy不能像我期望的那样工作。
快速的猜测是,它继承了元组,因而是一个迭代器。 'np.array'尝试从可迭代元素中构建数组。你可以间接地创建一个像列表或元组这样的迭代对象数组。 – hpaulj