[英]How to add an element at the index using numpy in python
I am new to python, Here I have an numpy array
.我是 python 新手,这里我有一个
numpy array
。 Now, In this ,现在,在这个,
I am trying to add an element in the index in the array .我正在尝试在数组的索引中添加一个元素。
for x in index:
output_result[x:x] = [300]
But it is not getting added, index is the position.但它没有被添加,索引是位置。 where I want to add that element.
我想添加那个元素的地方。 So, can any one help mw eith this ?
那么,任何人都可以帮助我们吗?
are you maybe looking for something like this:你可能正在寻找这样的东西:
import numpy as np
a = np.zeros(10) # create numpy array with ten zeros
a = np.where(a == 0, 300, a) # substitute 300 where there are zeros in array - **i assume this is what you need**
print(a) # print generated array
print(type(a)) # print data type to show a numpy array was generated
or do you want to "append" a new element?还是要“附加”一个新元素?
With a Python list, you can insert a value with:使用 Python 列表,您可以插入一个值:
In [104]: alist = [0,1,2,3]
In [105]: alist[1:1]=[300]
In [106]: alist
Out[106]: [0, 300, 1, 2, 3]
But this does not work with ndarray
.但这不适用于
ndarray
。 The array size is fixed.数组大小是固定的。 The best you can do is create a new array, with original values and the new one(s).
您能做的最好的事情是创建一个新数组,其中包含原始值和新值。
np.insert
is a function that can do that. np.insert
是一个可以做到这一点的函数。 Since the operation is not particularly efficient, it's best to do a whole set of inserts at once, rather than do it iteratively.由于操作不是特别有效,最好一次执行一整套插入,而不是迭代执行。
In [108]: np.insert(np.arange(4),1,300)
Out[108]: array([ 0, 300, 1, 2, 3])
In [109]: np.insert(np.arange(4),[1,2],[300,400])
Out[109]: array([ 0, 300, 1, 400, 2, 3])
(Even with a list, iterative insertion can be tricky, since each insertion changes the size of the list. The insertion point has to take that into account (unless you iterate from the end).) (即使使用列表,迭代插入也可能很棘手,因为每次插入都会改变列表的大小。插入点必须考虑到这一点(除非您从末尾开始迭代)。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.