【发布时间】:2015-02-12 00:20:02
【问题描述】:
我有一个 3-D 数组(下图,z),例如及时表示一连串二维数组(下图为a1 和a2)。我想为所有这些二维数组沿它们的轴选择一些值(两个参考轴上的条件(x 和y 下面),然后对结果执行一些操作(例如,平均值、总和......)一连串“较小的”二维数组。
下面的代码提出了几种方法来做到这一点。我发现solution1 非常不优雅,但它似乎比solution2 执行得更快。为什么会这样,有没有更好的方法(更简洁、更高效(速度和内存))来做到这一点?
关于Step2,哪一个是最好的选择,还有其他更有效的方法吗?为什么计算C2不起作用?谢谢!
【灵感来源:Get mean of 2D slice of a 3D array in numpy】
import numpy
import time
# Control parameters (to be modified to make different tests)
xx=1000
yy=6000
# Some 2D arrays, z is a 3D array containing a succesion of such arrays (2 here)
a1=numpy.arange(xx*yy).reshape((yy, xx))
a2=numpy.linspace(0,100, num=xx*yy).reshape((yy, xx))
z=numpy.array((a1, a2))
# Axes x and y along which conditioning for the 2D arrays is made
x=numpy.arange(xx)
y=numpy.arange(yy)
# Condition is on x and y, to be applied on a1 and a2 simultaneously
xmin, xmax = xx*0.4, xx*0.8
ymin, ymax = yy*0.2, yy*0.5
xcond = numpy.logical_and(x>=xmin, x<=xmax)
ycond = numpy.logical_and(y>=ymin, y<=ymax)
def solution1():
xcond2D = numpy.tile(xcond, (yy, 1))
ycond2D = numpy.tile(ycond[numpy.newaxis].transpose(), (1, xx))
xymask = numpy.logical_not(numpy.logical_and(xcond2D, ycond2D))
xymaskzdim = numpy.tile(xymask, (z.shape[0], 1, 1))
return numpy.ma.MaskedArray(z, xymaskzdim)
def solution2():
return z[:,:,xcond][:,ycond, :]
start=time.clock()
z1=solution1()
end=time.clock()
print "Solution1: %s sec" % (end-start)
start=time.clock()
z2=solution2()
end=time.clock()
print "Solution2: %s sec" % (end-start)
# Step 2
# Now compute some calculation on the resulting z1 or z2
print "A1: ", z2.reshape(z2.shape[0], z2.shape[1]*z2.shape[2]).mean(axis=1)
print "A2: ", z1.reshape(z1.shape[0], z1.shape[1]*z1.shape[2]).mean(axis=1)
print "B1: ", z2.mean(axis=2).mean(axis=1)
print "B2: ", z1.mean(axis=2).mean(axis=1)
print "Numpy version: ", numpy.version.version
print "C1: ", z2.mean(axis=(1, 2))
print "C2: ", z1.mean(axis=(1, 2))
输出:
Solution1: 0.0568935728474 sec
Solution2: 0.157177904729 sec
A1: [ 2.10060000e+06 3.50100058e+01]
A2: [2100600.0 35.01000583500077]
B1: [ 2.10060000e+06 3.50100058e+01]
B2: [2100600.0 35.010005835000975]
Numpy version: 1.7.1
C1: [ 2.10060000e+06 3.50100058e+01]
C2:
TypeError: tuple indices must be integers, not tuple
【问题讨论】:
标签: python numpy multidimensional-array