将元素插入到numpy数组的开头和结尾 [英] Insert elements to beginning and end of numpy array

查看:1432
本文介绍了将元素插入到numpy数组的开头和结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组:

import numpy as np
a = np.array([2, 56, 4, 8, 564])

,我想添加两个元素:一个在数组的开头88,一个在结尾的77.

and I want to add two elements: one at the beginning of the array, 88, and one at the end, 77.

我可以这样:

a = np.insert(np.append(a, [77]), 0, 88)

,这样a最终看起来像这样:

so that a ends up looking like:

array([ 88,   2,  56,   4,   8, 564,  77])

问题:这样做的正确方法是什么?我觉得将np.append嵌套在np.insert中很可能不是执行此操作的pythonic方法.

The question: what is the correct way of doing this? I feel like nesting a np.append in a np.insert is quite likely not the pythonic way to do this.

推荐答案

另一种方法是使用

Another way to do that would be to use numpy.concatenate . Example -

np.concatenate([[88],a,[77]])

演示-

In [62]: a = np.array([2, 56, 4, 8, 564])

In [64]: np.concatenate([[88],a,[77]])
Out[64]: array([ 88,   2,  56,   4,   8, 564,  77])

这篇关于将元素插入到numpy数组的开头和结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆