如何创建在numpy的空数组/矩阵? [英] How do I create an empty array/matrix in NumPy?

查看:2473
本文介绍了如何创建在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)

有没有使用那种符号来 numpy的数组或矩阵的方式?

推荐答案

您必须高效使用numpy的错误心理模型。 numpy的数组存储在存储器的连续块。如果你想行或列添加到现有阵列,整个阵列需要被复制到一个新的内存块,形成间隔为存储在新的元素。如果做多次向创建数组这是非常低效的。

You have the wrong mental model for using NumPy efficiently. NumPy arrays are stored in contiguous blocks of memory. 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.]])

这篇关于如何创建在numpy的空数组/矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆