Python "值错误:无法删除数组元素" -- 我为什么会遇到这个?
我在网上找不到关于这个值错误的任何信息,现在完全不知道为什么我的代码会出现这个问题。
我有一个很大的字典,大约有50个键。每个键对应的值是一个二维数组,里面有很多元素,格式是 [日期时间对象, 其他信息]
。举个例子,样子可能是这样的:
{'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)}
我希望我的代码能够让用户选择一个开始和结束日期,然后删除所有不在这个范围内的数组元素(对于所有的键来说)。
我在代码中加了很多打印语句,发现它能找到那些超出范围的日期,但不知为什么,当它尝试从数组中删除元素时,就会出现错误。
这是我的代码:
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]
请帮帮我,也许你能看到我看不到的问题。
谢谢!
2 个回答
3
NumPy数组的大小是固定的,所以建议使用列表。
6
如果你在使用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)
只是为了确保里面仍然有日期时间:
>>> b = a[(a[:,0] > start)&(a[:,0] < end)]
>>> b[0,0]
datetime.datetime(2010, 10, 26, 11, 5, 30, 613066)