Numpy append:自动转换错误维度的数组 [英] Numpy append: Automatically cast an array of the wrong dimension

查看:29
本文介绍了Numpy append:自动转换错误维度的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在没有 if 子句的情况下执行以下操作?

is there a way to do the following without an if clause?

我正在用 pupynere 读取一组 netcdf 文件,并想用 numpy append 构建一个数组.有时输入数据是多维的(参见下面的变量a"),有时是一维的(b"),但第一维中的元素数量总是相同的(下面示例中的9").

I'm reading a set of netcdf files with pupynere and want to build an array with numpy append. Sometimes the input data is multi-dimensional (see variable "a" below), sometimes one dimensional ("b"), but the number of elements in the first dimension is always the same ("9" in the example below).

> import numpy as np
> a = np.arange(27).reshape(3,9)
> b = np.arange(9)
> a.shape
(3, 9)
> b.shape
(9,)

这按预期工作:

> np.append(a,a, axis=0)
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8],
   [ 9, 10, 11, 12, 13, 14, 15, 16, 17],
   [18, 19, 20, 21, 22, 23, 24, 25, 26],
   [ 0,  1,  2,  3,  4,  5,  6,  7,  8],
   [ 9, 10, 11, 12, 13, 14, 15, 16, 17],
   [18, 19, 20, 21, 22, 23, 24, 25, 26]])

但是,附加 b 并不那么优雅:

but, appending b does not work so elegantly:

> np.append(a,b, axis=0)
ValueError: arrays must have same number of dimensions

append 的问题是(来自 numpy 手册)

The problem with append is (from the numpy manual)

"当指定轴时,值必须具有正确的形状."

我必须先施放才能获得正确的结果.

I'd have to cast first in order to get the right result.

> np.append(a,b.reshape(1,9), axis=0)
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8],
   [ 9, 10, 11, 12, 13, 14, 15, 16, 17],
   [18, 19, 20, 21, 22, 23, 24, 25, 26],
   [ 0,  1,  2,  3,  4,  5,  6,  7,  8]])

所以,在我的文件读取循环中,我目前正在使用这样的 if 子句:

So, in my file reading loop, I'm currently using an if clause like this:

for i in [a, b]:
    if np.size(i.shape) == 2:
        result = np.append(result, i, axis=0)
    else:
        result = np.append(result, i.reshape(1,9), axis=0)

有没有办法在没有 if 语句的情况下附加a"和b"?

Is there a way to append "a" and "b" without the if statement?

虽然@Sven 完美地回答了原始问题(使用 np.atleast_2d()),但他(和其他人)指出代码效率低下.在下面的答案中,我结合了他们的建议并替换了我的原始代码.现在应该效率更高了.谢谢.

While @Sven answered the original question perfectly (using np.atleast_2d()), he (and others) pointed out that the code is inefficient. In an answer below, I combined their suggestions and replaces my original code. It should be much more efficient now. Thanks.

推荐答案

你可以使用numpy.atleast_2d():

result = np.append(result, np.atleast_2d(i), axis=0)

也就是说,请注意重复使用 numpy.append() 是构建 NumPy 数组的一种非常低效的方式——它必须在每一步中重新分配.如果可能,请使用所需的最终大小预先分配数组,然后使用切片填充它.

That said, note that the repeated use of numpy.append() is a very inefficient way to build a NumPy array -- it has to be reallocated in every step. If at all possible, preallocate the array with the desired final size and populate it afterwards using slicing.

这篇关于Numpy append:自动转换错误维度的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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