You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤numpy.dstack中第三列元素小于1的行并保留整行?

Solution

First, note that your stack array is 3D with shape (1, 3, 3) (from np.dstack). The rows you want to filter are contained in the 2D array at stack[0]. Use numpy's vectorized operations for a clean, efficient solution:

import numpy as np

a = np.array((1,2,6))
b = np.array((2,3,4))
c = np.array((8,3,0))
stack = np.dstack((a,b,c))

# Extract the 2D array from the 3D stack structure
arr = stack[0]
# Create a boolean mask for rows where third column element >=1
mask = arr[:, 2] >= 1
# Filter rows using the mask
filtered_rows = arr[mask]
# Convert back to 3D array to match original structure
filtered_stack = filtered_rows[np.newaxis, :, :]

print(filtered_stack)
# Output:
# [[[1 2 8]
#   [2 3 3]]]

Why your original code failed

Your loop iterated over the 3D stack (so i was the full 2D row set), then looped through individual elements of the third column. Appending d only added the third column value, not the entire row. Even if you tried appending rows manually, loops are unnecessary here—numpy's vectorized approach is faster and more idiomatic.

If you insist on a loop-based approach (not recommended for numpy), you could adjust it like this:

new_list = []
for row in stack[0]:
    if row[2] >= 1:
        new_list.append(row)
filtered_stack = np.array(new_list)[np.newaxis, :, :]
print(filtered_stack)

内容的提问来源于stack exchange,提问作者benedetta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 08:35:28