Unsuccessful append to an empty NumPy array

前端 未结 6 1611
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 14:05

I am trying to fill an empty(not np.empty!) array with values using append but I am gettin error:

My code is as follows:

import numpy as np
result=np         


        
6条回答
  •  我在风中等你
    2020-12-23 14:50

    numpy.append is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:

    import numpy
    
    old = numpy.array([1, 2, 3, 4])
    new = numpy.append(old, 5)
    print old
    # [1, 2, 3, 4]
    print new
    # [1, 2, 3, 4, 5]
    new = numpy.append(new, [6, 7])
    print new
    # [1, 2, 3, 4, 5, 6, 7]
    

    I think you might be able to achieve your goal by doing something like:

    result = numpy.zeros((10,))
    result[0:2] = [1, 2]
    
    # Or
    result = numpy.zeros((10, 2))
    result[0, :] = [1, 2]
    

    Update:

    If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:

    import numpy as np
    
    a = np.array([0., 1.])
    b = np.array([2., 3.])
    
    temp = []
    while True:
        rnd = random.randint(0, 100)
        if rnd > 50:
            temp.append(a)
        else:
            temp.append(b)
        if rnd == 0:
             break
    
     result = np.array(temp)
    

    In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.

    new update

    The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b) the shapes of a and b need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.

提交回复
热议问题