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

如何截取NumPy数组的末尾片段与开头元素并合并?

NumPy数组获取末尾与开头元素的解决方法

你遇到的问题是因为NumPy的普通切片规则:当步长为默认的1(正方向)时,要求起始索引的位置不晚于结束索引,否则会返回空数组。比如你的例子里,a[-2]对应的是数组的第4个元素(索引3),而结束索引是2,3>2,所以切片a[-2:2]取不到任何元素,返回空数组。

以下是几种可行的实现方法:

  • 拼接切片法(最常用)
    把需要的末尾部分和开头部分分别切片,再用np.concatenate或者np.r_拼接起来:

    import numpy as np
    a = np.array([1,2,3,4,5])
    # 方法1:用np.concatenate
    res = np.concatenate([a[-2:], a[:1]])
    # 方法2:用np.r_更简洁
    res = np.r_[a[-2:], a[:1]]
    print(res)  # 输出 [4 5 1]
    
  • 索引数组法
    手动指定需要提取的元素索引,或者动态生成索引数组:

    import numpy as np
    a = np.array([1,2,3,4,5])
    # 直接写索引
    indices = [3,4,0]
    res = a[indices]
    # 动态生成索引(适用于不确定数组长度的情况)
    end_indices = np.arange(len(a)-2, len(a))
    start_indices = np.arange(1)
    indices = np.concatenate([end_indices, start_indices])
    res = a[indices]
    print(res)  # 输出 [4 5 1]
    

如果需要提取的末尾和开头元素数量不同,只需要调整切片的参数(比如a[-3:]取最后3个,a[:2]取前2个)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:15:36