简体   繁体   English

Numpy:将1d数组(行)添加到Numpy Python中的空2d数组

[英]Numpy : Add a 1d array (row) to an empty 2d array in Numpy Python

I don't know the number of rows and columns of a 2d array ( a ) I need in advance: 我不知道我事先需要的2d数组( a )的行数和列数:

a = np.empty( (0,0), dtype=np.uint8 )
a.ndim
2

I managed to convert each line I read from a file to an 1d array of bytes called line 我设法将从文件中读取的每一行都转换为称为line一维字节数组

I want to add/append each line to a , so I tried : 我想添加/追加每行a ,所以我尝试:

np.vstack( (a,line) )

but I get : ValueError: all the input arrays must have same number of dimensions 但我得到: ValueError: all the input arrays must have same number of dimensions

And if I call a=np.append(a,line) , the number of dimensions becomes 1 如果我调用a=np.append(a,line) ,则维数变为1

Can you help ? 你能帮我吗 ?

Numpy arrays cannot be appended to. 不能将Numpy数组附加到后面。 The easiest way for you to do what you are trying to achieve would be to use a list and call np.asarray() on it. 您要做的最简单的方法是使用列表并在其上调用np.asarray()

a = []
# Build list from file
a = np.asarray(a)

You're on the right track with np.vstack . 您在使用np.vstack的方向正确。 The only requirement is that the arrays being stacked must have the same number of columns. 唯一的要求是,要堆叠的阵列必须具有相同数量的列。 Take a look at this: 看看这个:

array = None # initialise array to None first

for ...: # now inside the loop
    line = ... # read line from somewhere and get something like [201, 81, 237, 230]

    if array is None:
        array = line
    else: 
        array = np.vstack((array, line))

In terms of performance, this is actually a little more wasteful than just creating an array at the end out of a list. 就性能而言,这实际上比仅在列表末尾创建数组要浪费更多。 This is the problem with numpy arrays - they're immutable in terms of dimensions. 这是numpy数组的问题-在尺寸方面它们是不可变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM