Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

python - 如何在NumPy中创建一个空数组/矩阵?(How do I create an empty array/matrix in NumPy?)

I can't figure out how to use an array or matrix in the way that I would normally use a list.

(我不知道如何以通常使用列表的方式使用数组或矩阵。)

I want to create an empty array (or matrix) and then add one column (or row) to it at a time.

(我想创建一个空数组(或矩阵),然后一次向其中添加一列(或行)。)

At the moment the only way I can find to do this is like:

(目前,我能找到的唯一方法是:)

mat = None
for col in columns:
    if mat is None:
        mat = col
    else:
        mat = hstack((mat, col))

Whereas if it were a list, I'd do something like this:

(而如果这是一个列表,我会做这样的事情:)

list = []
for item in data:
    list.append(item)

Is there a way to use that kind of notation for NumPy arrays or matrices?

(有没有办法对NumPy数组或矩阵使用这种表示法?)

  ask by Ben translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have the wrong mental model for using NumPy efficiently.

(您对有效使用NumPy的思维模式有误。)

NumPy arrays are stored in contiguous blocks of memory.

(NumPy数组存储在连续的内存块中。)

If you want to add rows or columns to an existing array, the entire array needs to be copied to a new block of memory, creating gaps for the new elements to be stored.

(如果要向现有阵列添加行或列,则需要将整个阵列复制到新的内存块中,从而为要存储的新元素创建间隙。)

This is very inefficient if done repeatedly to build an array.

(如果反复进行以构建数组,则效率非常低下。)

In the case of adding rows, your best bet is to create an array that is as big as your data set will eventually be, and then add data to it row-by-row:

(在添加行的情况下,最好的选择是创建一个与数据集最终大小一样大的数组,然后逐行向其中添加数据:)

>>> import numpy
>>> a = numpy.zeros(shape=(5,2))
>>> a
array([[ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.]])
>>> a[0] = [1,2]
>>> a[1] = [2,3]
>>> a
array([[ 1.,  2.],
   [ 2.,  3.],
   [ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...