每个元素都是数组时填充新列表 [英] Populating new list when each element is an array
问题描述
我正在尝试根据一些现有数据创建一个新的数据列表。目前,尽管我遇到了一个问题,其中我的新列表的每个元素都被另存为自己的单元素列表。我不明白为什么会这样。我的代码当前类似于:
I'm trying to create a new list of data from some existing data. Currently though I am having the problem where each element of my new list is being saved as its own single-element list. I can't see why this is. My code is currently something like:
old_data = np.reshape(old_data, (49210, 1)) #Reshape into 1D array
new_data = [None] #Create empty list to be filled
max_value = np.nanmax(old_data)
threshold = 0.75 * max_value #Create threshold to be used as condition for new list.
for x in range(len(old_data)):
if old_data[x] > threshold:
new_data.append(old_data[x])
请注意, old_data
存储为2D数组,这就是为什么我在开始时就包含了 np.reshape
命令的原因。
Please note that old_data
was stored as a 2D array, which is why I have included that np.reshape
command at the start.
如上所述,每次满足条件时,该值都会作为新元素存储在 new_data
中,但是该元素是一个float32类型的数组,其大小为( 1)。因此 new_data
最终是一个数组数组。我不确定为什么会这样。我真的很喜欢从此输出常规数组/列表,以便new_data易于处理。
As I said above, each time the condition is fulfilled the value is stored as a new element in new_data
, but the element is an array of type float32 with size (1,). So new_data
has ended up being an array of arrays. I'm not sure why this is. I would really just like a regular array/list output from this so that new_data is tractable. Any advice is appreciated.
推荐答案
我没有数据,但这可能有用:
I do not have the data but this might work:
old_data = np.reshape(old_data, (49210, 1)) #Reshape into 1D array
threshold = np.nanmax(old_data) #Create threshold to be used as condition for new
new_data = [element for element in old_data if element > threshold]
列表理解不仅速度更快而且更漂亮,而不是使用带附加的for循环。
List comprehension is both faster and much prettier to use instead of for loops with append.
如果您遇到的是数组数组,则可能需要尝试以下操作:
In case you have ended up with a array of arrays you might want to try the following instead:
old_data = np.reshape(old_data, (49210, 1)) #Reshape into 1D array
threshold = np.nanmax(old_data) #Create threshold to be used as condition for new
new_data = [element[0] for element in old_data if element[0] > threshold]
这篇关于每个元素都是数组时填充新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!