我想根据逻辑比较将numpy数组分成三个不同的数组。我想分割的numpy数组叫做x
。它的外形看起来如下,但它的条目有所不同:(针对Saullo卡斯特罗的评论我包括一个稍微不同的数组x)高效选择numpy数组的分段
array([[ 0.46006547, 0.5580928 , 0.70164242, 0.84519205, 1.4 ],
[ 0.00912908, 0.00912908, 0.05 , 0.05 , 0.05 ]])
此阵的这值单调沿柱增加。我还有另外两个阵列叫lowest_gridpoints
和highest_gridpoints
。这些阵列的条目也有所不同,但形状总是相同的以下内容:
array([ 0.633, 0.01 ]), array([ 1.325, 0.99 ])
选择过程我想申请如下:
- 含有值比任何值的情况下的所有列
lowest_gridpoints
应从x
中删除并构成阵列temp1
。 - 包含高于
highest_gridpoints
中任何值的值的所有列应从x
中删除并构成阵列temp2
。 - 包含在
temp1
或temp2
中的所有列x
构成阵列x_new
。
我写的以下代码实现了该任务。
if np.any(x[:,-1] > highest_gridpoints) or np.any(x[:,0] < lowest_gridpoints):
for idx, sample, in enumerate(x.T):
if np.any(sample > highest_gridpoints):
max_idx = idx
break
elif np.any(sample < lowest_gridpoints):
min_idx = idx
temp1, temp2 = np.array([[],[]]), np.array([[],[]])
if 'min_idx' in locals():
temp1 = x[:,0:min_idx+1]
if 'max_idx' in locals():
temp2 = x[:,max_idx:]
if 'min_idx' in locals() or 'max_idx' in locals():
if 'min_idx' not in locals():
min_idx = -1
if 'max_idx' not in locals():
max_idx = x.shape[1]
x_new = x[:,min_idx+1:max_idx]
但是,我怀疑这个代码是非常低效的,因为大量使用循环。另外,我认为语法臃肿。
有人有一个代码的想法,实现上述任务更有效或看起来简洁吗?
您的示例返回'[]'我...这将是不错的,可用于比较不同的输入... – 2014-10-20 10:27:33
@SaulloCastro:谢谢你的评论。我稍微修改了数组x。你有关于如何修改我的代码的想法吗? – fabian 2014-10-20 14:30:16
你是否期望temp1和temp2是互斥的,或者它可能发生的情况是一个列的值低于'lowest_gridpoints'中的值而另一个值高于'highest_gridpoints'中的值?另外,你的意思是沿着行单调增长吗? – greschd 2014-10-20 16:50:08