【发布时间】:2026-01-26 17:35:01
【问题描述】:
有没有办法在没有 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手册)
"When axis is specified, values must have the correct shape."
为了得到正确的结果,我必须先投射。
> 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()),但他(和其他人)指出代码效率低下。在下面的答案中,我结合了他们的建议并替换了我的原始代码。现在应该更有效率了。谢谢。
【问题讨论】:
标签: python list performance numpy append