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

如何在Python NumPy中编写函数裁剪二维数组外围元素?

实现NumPy数组的首尾行列剔除

问题描述

假设我有如下NumPy数组:

import numpy as np
x = np.array([
    [0, 1, 2, 3, 4],
    [5, 6, 7, 8, 9],
    [10, 11, 12, 13, 14],
    [15, 16, 17, 18, 19]
])

需要实现fun_strip(x)函数,调用后返回:

[[ 6  7  8]
 [11 12 13]]

解决方案

利用NumPy的切片特性即可快速实现,核心是剔除原数组的首尾行和首尾列:

import numpy as np

def fun_strip(x):
    # 行取索引1到3(左闭右开,对应原数组第2、3行),列取索引1到4(对应原数组第2-4列)
    return x[1:3, 1:4]

验证效果

调用函数测试:

x = np.array([
    [0, 1, 2, 3, 4],
    [5, 6, 7, 8, 9],
    [10, 11, 12, 13, 14],
    [15, 16, 17, 18, 19]
])
print(fun_strip(x))

输出结果:

[[ 6  7  8]
 [11 12 13]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:35:22