Python 将元素插入到 numpy 数组的开头和结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32828922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert elements to beginning and end of numpy array
提问by Gabriel
I have a numpy
array:
我有一个numpy
数组:
import numpy as np
a = np.array([2, 56, 4, 8, 564])
and I want to add two elements: one at the beginning of the array, 88
, and one at the end, 77
.
我想添加两个元素:一个在数组的开头,88
,一个在结尾,77
。
I can do this with:
我可以这样做:
a = np.insert(np.append(a, [77]), 0, 88)
so that a
ends up looking like:
所以a
最终看起来像:
array([ 88, 2, 56, 4, 8, 564, 77])
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.
问题:这样做的正确方法是什么?我觉得np.append
在 a 中嵌套 anp.insert
很可能不是执行此操作的 Pythonic 方式。
采纳答案by Anand S Kumar
Another way to do that would be to use numpy.concatenate
. Example -
另一种方法是使用numpy.concatenate
. 例子 -
np.concatenate([[88],a,[77]])
Demo -
演示 -
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])
回答by Divakar
回答by J. Corson
what about:
关于什么:
a = np.hstack([88, a, 77])
回答by Kasramvd
You can pass the list of indices to np.insert
:
您可以将索引列表传递给np.insert
:
>>> np.insert(a,[0,5],[88,77])
array([ 88, 2, 56, 4, 8, 564, 77])
Or if you don't know the length of your array you can use array.size
to specify the end of array :
或者,如果您不知道数组的长度,则可以使用它array.size
来指定数组的结尾:
>>> np.insert(a,[0,a.size],[88,77])
array([ 88, 2, 56, 4, 8, 564, 77])