当每个元素都是数组时填充新列表

问题描述

我正在尝试从一些现有数据中创建一个新的数据列表。目前,尽管我遇到了一个问题,其中我的新列表的每个元素都另存为自己的单元素列表。我不明白为什么会这样。我的代码当前类似于:

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命令的原因。

如上所述,每次满足条件时,该值都作为新元素存储在new_data中,但是该元素是float32类型的数组,大小为(1,)。因此new_data最终是一个数组数组。我不确定为什么会这样。我真的很喜欢从此输出常规数组/列表,以便new_data易于处理。任何建议表示赞赏。

解决方法

我没有数据,但这可能有用:

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循环。

如果您遇到的是数组数组,则可能需要尝试以下操作:

old_data = np.reshape(old_data,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]
,

所以我知道,您正在使用numpy库将2D数组展平为1D数组。

您可以做的是将2D数组展平为1D数组,然后根据需要将旧列表追加到新列表中。

要将2D数组展平为1D数组-

import numpy as np 
  
ini_array1 = np.array([[1,2,3],[2,4,5],[1,3]]) 
   
# Multiplying arrays 
result = ini_array1.flatten() 
  
# printing result 
print("New resulting array: ",result) 

结果将是将旧的2D数组作为普通的1D数组或python列表,您可以将其附加到新列表中以获得最终列表。

,

谢谢@JakobVinkas和@Innomight。我已经尝试过两种解决方案,并且都有效。对于为什么最初遇到此问题,我仍然有些困惑,但是我会继续阅读我猜得到的内容。

对于以后可能遇到此问题的任何人,我已经实现了Jakob建议使用element[0]作为解决方案的建议。

我还发现this questionthis question很好地解释了这里的根本情况。