有没有不使用if语句来完成以下操作的方法?
我正在使用pupynere读取一组netcdf文件,并希望使用numpy append构建一个数组。有时输入数据是多维的(如下面的变量“a”),有时是一维的(“b”),但第一维中元素的数量始终相同(在下面的示例中为“9”)。
> 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 并不那么优雅:
> np.append(a,b, axis=0)
ValueError: arrays must have same number of dimensions
从numpy手册得知,append存在的问题是:
为了获得正确的结果,我需要先进行强制转换。
> 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语句:
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"?
编辑:虽然@Sven完美地回答了原始问题(使用np.atleast_2d()
),但他(以及其他人)指出代码效率低下。在下面的答案中,我结合了他们的建议并替换了我的原始代码。现在应该更有效率了。谢谢。
numpy.vstack()
是你最好的猜测。 - Sven Marnach