我在网上找不到关于这个值错误的任何东西,我完全不知道为什么我的代码会引起这个响应。
我有一本大约有50个关键字的大字典。与每个键相关联的值是表单[datetime object, some other info]
的许多元素的二维数组。示例将如下所示:
{'some_random_key': array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 14.1],
[datetime(2010, 10, 26, 11, 5, 38, 613066), 17.2]],
dtype=object),
'some_other_key': array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 'true'],
[datetime(2010, 10, 26, 11, 5, 38, 613066), 'false']],
dtype=object)}
我希望我的代码所做的是允许用户选择开始和结束日期,并删除不在该范围内的所有数组元素(对于所有键)。
在整个代码中放置print语句,我可以推断出它可以找到超出范围的日期,但是由于某些原因,当它试图从数组中删除元素时,就会出现错误。
下面是我的代码:
def selectDateRange(dictionary, start, stop):
#Make a clone dictionary to delete values from
theClone = dict(dictionary)
starting = datetime.strptime(start, '%d-%m-%Y') #put in datetime format
ending = datetime.strptime(stop+' '+ '23:59', '%d-%m-%Y %H:%M') #put in datetime format
#Get a list of all the keys in the dictionary
listOfKeys = theClone.keys()
#Go through each key in the list
for key in listOfKeys:
print key
#The value associate with each key is an array
innerAry = theClone[key]
#Loop through the array and . . .
for j, value in enumerate(reversed(innerAry)):
if (value[0] <= starting) or (value[0] >= ending):
#. . . delete anything that is not in the specified dateRange
del innerAry[j]
return theClone
这是我得到的错误消息:
ValueError: cannot delete array elements
它出现在下面这行:del innerAry[j]
请帮帮忙--也许你有眼力看到我看不到的问题。
谢谢!
发布于 2010-11-12 11:16:12
如果使用numpy数组,则将它们用作数组而不是列表
numpy对整个数组进行元素级比较,然后可以用它来选择相关的子数组。这也消除了对内部循环的需要。
>>> a = np.array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 14.1],
[datetime(2010, 10, 26, 11, 5, 30, 613066), 17.2],
[datetime(2010, 10, 26, 11, 5, 31, 613066), 17.2],
[datetime(2010, 10, 26, 11, 5, 32, 613066), 17.2],
[datetime(2010, 10, 26, 11, 5, 33, 613066), 17.2],
[datetime(2010, 10, 26, 11, 5, 38, 613066), 17.2]],
dtype=object)
>>> start = datetime(2010, 10, 26, 11, 5, 28, 157405)
>>> end = datetime(2010, 10, 26, 11, 5, 33, 613066)
>>> (a[:,0] > start)&(a[:,0] < end)
array([False, True, True, True, False, False], dtype=bool)
>>> a[(a[:,0] > start)&(a[:,0] < end)]
array([[2010-10-26 11:05:30.613066, 17.2],
[2010-10-26 11:05:31.613066, 17.2],
[2010-10-26 11:05:32.613066, 17.2]], dtype=object)
只是为了确保我们还有datetimes在里面:
>>> b = a[(a[:,0] > start)&(a[:,0] < end)]
>>> b[0,0]
datetime.datetime(2010, 10, 26, 11, 5, 30, 613066)
发布于 2010-10-29 07:45:58
NumPy数组的大小是固定的。请改用列表。
https://stackoverflow.com/questions/4048011
复制相似问题