How to create a numpy array of lists?

前端 未结 6 2095
攒了一身酷
攒了一身酷 2020-12-01 12:02

I want to create a numpy array in which each element must be a list, so later I can append new elements to each.

I have looked on google and here on stack overflow a

6条回答
  •  时光取名叫无心
    2020-12-01 12:26

    Just found this, I've never answered a question before, but here is a pretty simple solution:

    If you want a vector of length n, use:

    A = np.array([[]]*n + [[1]])[:-1]
    

    This returns:

    array([list([]), list([]), ... , list([])], dtype=object)
    

    If instead you want an n by m array, use:

    A = np.array([[]]*n*m + [[1]])[:-1]
    B = A.reshape((n,m))
    

    For higher rank arrays, you can use a similar method by creating a long vector and reshaping it. This may not be the most efficient way, but it worked for me.

提交回复
热议问题