python - 当每个元素都是数组时填充新列表
问题描述
我正在尝试从一些现有数据中创建一个新的数据列表。目前,虽然我遇到了新列表中的每个元素都被保存为自己的单元素列表的问题。我不明白这是为什么。我的代码目前是这样的:
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 易于处理。任何建议表示赞赏。
解决方案
我没有数据,但这可能有效:
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]
推荐阅读
- spring-boot - java.lang.IllegalStateException:提交响应后无法转发问题迁移到 SpringBoot 2
- swift - 滑块值不会更新值,除非它被移动
- python - 无法在特定路径中安装 python 并获得 No module named docker
- angular - 组件中多个输入的 NgbTypeahead
- apache - Apache mod_rewrite 删除 .html 扩展名不起作用
- typescript - 用不同类型的属性分配对象的属性
- java - Netty 3 中的 channelOpen 和 channelClosed 上游事件中是否存在一对一的映射?
- python - Generic algorithm for element wise operation between hundreds of lists
- kubernetes - 在同一台服务器上运行 Kubernetes 主节点和节点(在 Kubernetes 主节点上调度 pod)
- java - 我无法将我的 Android 应用程序连接到 MongoDB