Pythonic way to create a numpy array from a list of numpy arrays

后端 未结 6 1075
执笔经年
执笔经年 2020-12-13 06:24

I generate a list of one dimensional numpy arrays in a loop and later convert this list to a 2d numpy array. I would\'ve preallocated a 2d numpy array if i knew the number o

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 06:55

    I'll add my own version of ~unutbu's answer. Similar to numpy_all_the way, but you dynamically resize if you have an index error. I thought it would have been a little faster for small data sets, but it's a little slower - the bounds checking slows things down too much.

    initial_guess = 1000
    
    def my_numpy_all_the_way(k):
        arr=np.empty((initial_guess,M))
        for x,row in enumerate(make_test_data(k)):
            try:
                arr[x]=row
            except IndexError:
                arr.resize((arr.shape[0]*2, arr.shape[1]))
                arr[x]=row
        arr.resize((k,M))
        return arr
    

提交回复
热议问题