Growing matrices columnwise in NumPy

后端 未结 4 734
终归单人心
终归单人心 2021-02-12 13:58

In pure Python you can grow matrices column by column pretty easily:

data = []
for i in something:
    newColumn = getColumnDataAsList(i)
    data.append(newColu         


        
4条回答
  •  Happy的楠姐
    2021-02-12 14:38

    Generally it is expensive to keep reallocating the NumPy array - so your third solution is really the best performance wise.

    However I think hstack will do what you want - the cue is in the error message,

    ValueError: arrays must have same number of dimensions`

    I'm guessing that newColumn has two dimensions (rather than a 1D vector), so you need data to also have two dimensions..., for example, data = np.array([[]]) - or alternatively make newColumn a 1D vector (generally if things are 1D it is better to keep them 1D in NumPy, so broadcasting, etc. work better). in which case use np.squeeze(newColumn) and hstack or vstack should work with your original definition of the data.

提交回复
热议问题