简体   繁体   English

Numpy Append 数据到空数组

[英]Numpy Append Data to an empty array

I'm trying to write a code that will add 2 arrays(element by element) and store them in a 3rd array.我正在尝试编写一个代码,它将添加 2 个数组(逐个元素)并将它们存储在第三个数组中。

Basic Logic:基本逻辑:

arr3[i] = arr1[i] + arr2[i]

For this, I have created two arrays arr1 and arr2 .为此,我创建了两个 arrays arr1arr2 The result of the sum of arr1 and arr2 is getting appended in an empty array arr3 . arr1 和 arr2 之和的结果被附加到一个空数组arr3中。

code:代码:

from numpy import append, array, int8


arr1 = array([1,2,3,4,5])

arr2 = array([2,4,6,8,10])

len = max(arr1.size,arr2.size)

arr3 = array([],dtype=int8)

for i in range(len):
    append(arr3,arr1[i]+arr2[i])
    print(arr1[i]+arr2[i])
    print(arr3[i])

print(arr3)

In this code, I'm able to refer to elements of arr1 and arr2 and add them, but I'm not able to append the data to arr3.在这段代码中,我可以引用 arr1 和 arr2 的元素并添加它们,但我无法将数据 append 到 arr3。

Can anyone please help me to understand, what is the mistake in the code due to which I'm not able to store the data to arr3?谁能帮我理解,代码中的错误是什么导致我无法将数据存储到arr3?

You can simply use你可以简单地使用

arr3 = arr1 + arr2

The reason why your code doesn't work is that append doesn't mutate the array, but returns a new one.您的代码不起作用的原因是append不会改变数组,而是返回一个新数组。 You can simply modify your code like this:您可以像这样简单地修改您的代码:

for i in range(len):
    arr3 = append(arr3,arr1[i]+arr2[i])

Use arr3.append .使用arr3.append

from numpy import append, array, int8


arr1 = array([1,2,3,4,5])

arr2 = array([2,4,6,8,10])

len = max(arr1.size,arr2.size)

arr3 = []

for i in range(len):
    arr3.append(arr1[i]+arr2[i])
    print(arr1[i]+arr2[i])
    print(arr3[i])


print(arr3)

First things first第一件事

Do Not Use built-in function name as variable .不要使用内置的 function 名称作为变量

len is a built-in function in python. len是 python 中的内置 function。

@sagi's answer is right. @sagi 的回答是对的。 Writing the for loop would mean your code is not time-optimized.编写 for 循环意味着您的代码没有进行时间优化。

But if you still want to understand where your code went wrong, check array shape但是,如果您仍然想了解代码出错的地方,请检查数组形状

import numpy as np
arr3 = np.array([],dtype=int8)
print (arr3.shape)
>>> (0,) 

Maybe you can create an empty array of the same shape as arr1 or arr2 .也许您可以创建一个与arr1arr2形状相同的空数组。 Seems like for your problem they have same dimension.似乎对于您的问题,它们具有相同的尺寸。

arr3 = np.empty(arr1.shape, dtype=arr1.dtype)
arr3[:] = arr1 + arr2

If you are still persisting to use the dreaded for loop and numpy.append then use this--如果你仍然坚持使用可怕for循环和numpy.append然后使用这个——

arr3 = np.empty(arr1.shape, dtype=arr1.dtype)
for i in range(len(arr1)):
   np.append(arr3, arr1[i] + arr2[i])
print(arr3)
>>> array([ 3,  6,  9, 12, 15])

Cheers, good luck!!干杯,祝你好运!!

This could give indexing errors:这可能会产生索引错误:

max(arr1.size,arr2.size)

if the arrays differ, range over this would produce index values that are too large for the smaller array.如果 arrays 不同,则超出此range的范围会产生对于较小数组而言太大的索引值。

The straight forward way of summing the 2 arrays is对 2 arrays 求和的直接方法是

In [79]: arr1 = np.array([1,2,3,4,5])
    ...: arr2 = np.array([2,4,6,8,10])
In [80]: arr1+arr2
Out[80]: array([ 3,  6,  9, 12, 15])

It makes optimal use of the numpy array definitions, and is fastest.它充分利用了numpy数组定义,速度最快。

If you must iterate (for example because you want to learn from your mistakes), use something like (which is actually better if the inputs are lists, not arrays):如果您必须迭代(例如,因为您想从错误中学习),请使用类似的东西(如果输入是列表而不是数组,这实际上会更好):

In [86]: alist = []
    ...: for x,y in zip(arr1,arr2):
    ...:     alist.append(x+y)
    ...: 
In [87]: alist
Out[87]: [3, 6, 9, 12, 15]

or better yet as a list comprehension或者更好的是作为列表理解

In [88]: [x+y for x,y in zip(arr1,arr2)]
Out[88]: [3, 6, 9, 12, 15]

I'm using zip instead of the arr1[i] types of range indexing.我正在使用zip而不是arr1[i]类型的范围索引。 It's more concise, and less likely to produce errors.它更简洁,并且不太可能产生错误。

np.append , despite the name, is not a list append clone. np.append尽管有名称,但不是列表append克隆。 Read, if necessary reread, the np.append docs.如有必要,请阅读np.append文档。

append : ndarray
        A copy of `arr` with `values` appended to `axis`.  Note that
        `append` does not occur in-place: a new array is allocated and
        filled.  If `axis` is None, `out` is a flattened array.

This does work, but is slower:这确实有效,但速度较慢:

In [90]: arr3 = np.array([])
    ...: for x,y in zip(arr1,arr2):
    ...:     arr3 = np.append(arr3,x+y)
    ...: 
In [91]: arr3
Out[91]: array([ 3.,  6.,  9., 12., 15.])

I would like to remove np.append , since it misleads far too many beginners.我想删除np.append ,因为它误导了太多初学者。

Iteration like this is great for lists, but best avoided when working with numpy arrays.这样的迭代非常适合列表,但在使用 numpy arrays 时最好避免。 Learn to use the defined numpy operators and methods, and use elementwise iteration only as last resort.学习使用定义的 numpy 运算符和方法,并且仅将元素迭代作为最后的手段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM