首页 > 解决方案 > 当每个元素都是数组时填充新列表

问题描述

我正在尝试从一些现有数据中创建一个新的数据列表。目前,虽然我遇到了新列表中的每个元素都被保存为自己的单元素列表的问题。我不明白这是为什么。我的代码目前是这样的:

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它存储为二维数组,这就是我np.reshape在开始时包含该命令的原因。

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

标签: pythonlistloopsconditional-statements

解决方案


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

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]

列表推导式使用起来比使用 append 的 for 循环更快、更漂亮。

如果您最终得到了一个数组数组,您可能想尝试以下方法:

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]

推荐阅读