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

如何对Numpy二维数组进行三角形区域切片?

实现二维Numpy数组的三角形区域切片

Got it, let's break down how to solve this problem step by step. First, let's clarify the structure of your target triangle: the three points (1,1), (3,1), (3,5) (0-based indices, row first, column second) form a right triangle with the right angle at (3,1). From your expected result, we can see each row's valid column range starts at column 1 and ends at 2*y -1 (where y is the current row index).

Here are two implementation approaches for different scenarios:

方法一:逐行赋值(简单直观,适合小数组)

This method is straightforward and easy to understand, perfect for quick validation of your需求:

import numpy as np

# Create the original 4x8 zero array
arr = np.zeros((4, 8), dtype=int)

# Iterate over rows covered by the triangle (row indices 1 to 3)
for y in range(1, 4):
    # Calculate the rightmost column index for current row
    x_right = 2 * y - 1
    # Assign 1 to the range [1, x_right] (slice is left-closed right-open, so +1 is needed)
    arr[y, 1 : x_right + 1] = 1

# Print the result
print(arr)

Running this code will output exactly your expected result:

[[0 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0]
 [0 1 1 1 0 0 0 0]
 [0 1 1 1 1 1 0 0]]

方法二:向量化掩码(高效无循环,适合大数组)

If you're working with large arrays, loops can be slow. Using Numpy's vectorized operations is a better choice. We'll generate grid coordinates, create a mask based on triangle conditions, then assign values in bulk:

import numpy as np

arr = np.zeros((4, 8), dtype=int)

# Generate grid coordinate matrices, indexing='ij' ensures row-first order
y_coords, x_coords = np.meshgrid(np.arange(4), np.arange(8), indexing='ij')

# Build the mask: conditions for points inside the triangle
mask = (y_coords >= 1) &       # Rows are between 1 and 3
       (y_coords <= 3) &       #
       (x_coords >= 1) &       # Columns start from 1
       (x_coords <= 2*y_coords - 1)  # Columns don't exceed the hypotenuse boundary

# Assign 1 to all positions covered by the mask
arr[mask] = 1

print(arr)

This approach avoids loops entirely, leveraging Numpy's broadcasting for batch operations, which is much more efficient for large-scale data.

Key Logic Explanation

The hypotenuse equation is derived from the two points (1,1) and (3,5): the slope is (5-1)/(3-1)=2, so the line equation is x = 2*(y-1) + 1 = 2y -1. This gives the maximum column index for each row y, ensuring we exactly cover the target triangle area.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:44:05