How to build a numpy array row by row in a for loop?

前端 未结 2 1136
难免孤独
难免孤独 2021-01-19 10:45

This is basically what I am trying to do:

array = np.array()       #initialize the array. This is where the error code described below is thrown

for i in xr         


        
相关标签:
2条回答
  • 2021-01-19 11:22

    Use a list of 1D numpy arrays, or a list of lists, and then convert it to a numpy 2D array (or use more nesting and get more dimensions if you need to).

    import numpy as np
    
    a = []
    for i in range(5):
        a.append(np.array([1,2,3])) # or a.append([1,2,3])
    a = np.asarray(a) # a list of 1D arrays (or lists) becomes a 2D array
    
    print(a.shape)
    print(a)
    
    0 讨论(0)
  • 2021-01-19 11:26

    A numpy array must be created with a fixed size. You can create a small one (e.g., one row) and then append rows one at a time, but that will be inefficient. There is no way to efficiently grow a numpy array gradually to an undetermined size. You need to decide ahead of time what size you want it to be, or accept that your code will be inefficient. Depending on the format of your data, you can possibly use something like numpy.loadtxt or various functions in pandas to read it in.

    0 讨论(0)
提交回复
热议问题