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

查看:35
本文介绍了如何在 NumPy 中创建一个空数组/矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何像通常使用列表那样使用数组或矩阵.我想创建一个空数组(或矩阵),然后一次添加一列(或一行).

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

mat = 无对于列中的 col:如果垫是无:垫子 = 列别的:mat = hstack((mat, col))

如果它是一个列表,我会这样做:

list = []对于数据中的项目:list.append(item)

有没有办法对 NumPy 数组或矩阵使用这种符号?>

解决方案

您对有效使用 NumPy 的心智模型有误.NumPy 数组存储在连续的内存块中.如果要向现有数组添加行或列,则需要将整个数组复制到新的内存块,从而为要存储的新元素创建间隙.如果重复构建数组,这将非常低效.

在添加行的情况下,最好的办法是创建一个与数据集最终一样大的数组,然后逐行分配数据:

<预><代码>>>>导入 numpy>>>a = numpy.zeros(shape=(5,2))>>>一种数组([[ 0., 0.],[0., 0.],[0., 0.],[0., 0.],[ 0., 0.]])>>>[0] = [1,2]>>>a[1] = [2,3]>>>一种数组([[ 1., 2.],[2., 3.],[0., 0.],[0., 0.],[ 0., 0.]])

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?

解决方案

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 assign 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天全站免登陆