gpt4 book ai didi

Python "Value Error: cannot delete array elements"——为什么我会得到这个?

转载 作者:行者123 更新时间:2023-11-28 20:11:21 27 4
gpt4 key购买 nike

我无法在网上找到有关此值错误的任何信息,而且我完全不知道为什么我的代码会引发此响应。

我有一个大约有 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)}

我想要我的代码做的是允许用户选择开始和结束日期并删除不在该范围内的所有数组元素(对于所有键)。

在整个代码中放置打印语句我能够推断出它可以找到超出范围的日期,但由于某种原因,当它试图从数组中删除元素时会发生错误。

这是我的代码:

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]

请帮忙 - 也许你能看到我看不到的问题。

谢谢!

最佳答案

如果您使用 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)

关于Python "Value Error: cannot delete array elements"——为什么我会得到这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4048011/

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