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

如何替换n维NumPy数组中指定轴索引位置的元素

Replace Elements at Specific Axis & Index in NumPy Arrays

If you need to replace all elements at a specific index along a given axis in an n-dimensional NumPy array, NumPy's flexible indexing system makes this straightforward. Here's how to do it, using your 3D array example as a reference:

Step 1: Understand the Indexing Approach

We can construct an index tuple that targets the exact position we want:

  • For every axis except the one we're targeting, use : (or slice(None)) to select all elements.
  • For the target axis, specify the index we want to replace.

Step 2: Example Implementation

Let's walk through your sample scenario:

First, create the initial 3D array of ones:

import numpy as np

a = np.ones((2, 2, 2))
print("Original array:")
print(a)

Output:

Original array:
array([[[1., 1.],
        [1., 1.]],

       [[1., 1.],
        [1., 1.]]])

Now, replace all elements at axis=1, index=0 with 0:

# Build the index tuple: target axis 1 at index 0, others select all
indices = tuple([slice(None) if i != 1 else 0 for i in range(a.ndim)])
a[indices] = 0

print("\nModified array:")
print(a)

Output:

Modified array:
array([[[0., 0.],
        [1., 1.]],

       [[0., 0.],
        [1., 1.]]])

Step 3: Reusable Function

To make this easier to use across different arrays, wrap the logic in a function:

def replace_axis_elements(arr, axis, index, value):
    # Create index tuple targeting the specified axis and index
    indices = tuple([slice(None) if i != axis else index for i in range(arr.ndim)])
    arr[indices] = value
    return arr

You can use it like this:

a = np.ones((2, 2, 2))
modified_a = replace_axis_elements(a, axis=1, index=0, value=0)
print(modified_a)

This approach works for any n-dimensional array—just adjust the axis, index, and value parameters as needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:16:27