Seb*_*ian 5 python performance numpy list append
没有if子句有没有办法做到以下几点?
我正在使用pupynere读取一组netcdf文件,并希望构建一个带有numpy附加的数组.有时输入数据是多维的(见下面的变量"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,)
Run Code Online (Sandbox Code Playgroud)
这按预期工作:
> 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]])
Run Code Online (Sandbox Code Playgroud)
但是,附加b不能如此优雅地工作:
> np.append(a,b, axis=0)
ValueError: arrays must have same number of dimensions
Run Code Online (Sandbox Code Playgroud)
附加的问题是(来自numpy手册)
为了得到正确的结果,我必须先进行投射.
> 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]])
Run Code Online (Sandbox Code Playgroud)
所以,在我的文件读取循环中,我正在使用这样的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)
Run Code Online (Sandbox Code Playgroud)
有没有办法在没有if语句的情况下附加"a"和"b"?
编辑:虽然@Sven完美地回答了原始问题(使用np.atleast_2d()),但他(和其他人)指出代码效率低下.在下面的答案中,我结合了他们的建议并替换了我的原始代码.它现在应该更有效率.谢谢.
您可以使用numpy.atleast_2d():
result = np.append(result, np.atleast_2d(i), axis=0)
Run Code Online (Sandbox Code Playgroud)
也就是说,请注意,重复使用numpy.append()是构建 NumPy 数组的一种非常低效的方法——它必须在每一步中重新分配。如果可能的话,预先分配所需的最终大小的数组,然后使用切片填充它。