在numpy数组上应用条件并删除高维元素

时间:2019-08-22 06:48:32

标签: python numpy

我有一个形状为N,3、2的Numpy数组。我将每个形状为3、2的元素称为一个组合(因此有N个组合)。我想对每个组合内的值应用“测试”。如果不满足条件,我想删除不满足条件的组合。

假设我有这个数组:

array[[[1, 1],
       [2, 2],
       [3, 3]],

      [[2, 1],
       [2, 2],
       [2, 3]],

      [[3, 1],
       [3, 2],
       [3, 3]]]

我想检查左侧的所有值是否都大于1。目前,我正在执行以下操作: myArr = myArr [myArr [:,:,0]> 1]

运行此命令,它将仅删除[1,1]元素,而不删除整个组合(即[[1,1],[2,2],[3,3]])。

我该如何实现?如果可能,是否没有for循环? (我有很多组合)

当前,我的代码如下:

#X is the left value and Y the right value, each combination having 3 elements like [X, Y] I used Xt or Yt with t=1 to 3 in my comments later.

Limit = 2
b = np.array([[[1, 1], [2, 2], [3, 3]],
              [[2, 1], [2, 2], [2, 3]],
              [[3, 1], [3, 2], [3, 3]],
              [[4, 3], [4, 2], [3, 1]]])
#All X > 0
b = b[b[:, :, 0] > 0].reshape(-1, 3, 2)

#X1 + Y1 <= X2
b = b[b[:, 0, 0] + b[:, 0, 1] <= b[:, 1, 0]].reshape(-1, 3, 2)

#X2 + Y2 <= X3
b = b[b[:, 1, 0] + b[:, 1, 1] <= b[:, 2, 0]].reshape(-1, 3, 2)

#X2 / X1
b = b[b[:, 1, 0] / b[:, 0, 0] <= Limit].reshape(-1, 3, 2)

#Y2 / Y1
b = b[b[:, 1, 1] / b[:, 0, 1] <= Limit].reshape(-1, 3, 2)

#X3 / X2
b = b[b[:, 2, 0] / b[:, 1, 0] <= Limit].reshape(-1, 3, 2)

#Y3 / Y2
b = b[b[:, 2, 1] / b[:, 1, 1] <= Limit].reshape(-1, 3, 2)

#X1 / X2
b = b[b[:, 0, 0] / b[:, 1, 0] <= Limit].reshape(-1, 3, 2)

#Y1 / Y2
b = b[b[:, 0, 1] / b[:, 1, 1] <= Limit].reshape(-1, 3, 2)

#X2 / X3
b = b[b[:, 1, 0] / b[:, 2, 0] <= Limit].reshape(-1, 3, 2)

#Y2 / Y3
b = b[b[:, 1, 1] / b[:, 2, 1] <= Limit].reshape(-1, 3, 2)

#Comb 1 != Comb 2
b = b[(b[:, 0, 0] != b[:, 1, 0]) & (b[:, 0, 1] != b[:, 1, 1])].reshape(-1, 3, 2)

#Comb 2 != Comb 3
b = b[(b[:, 1, 0] != b[:, 2, 0]) & (b[:, 1, 1] != b[:, 2, 1])].reshape(-1, 3, 2)

1 个答案:

答案 0 :(得分:0)

尝试一下:

> (a_date <- as.Date("15-07-17", "%d-%m-%y"))
[1] "2017-07-15"
> (beginning_date_week <- as.Date(cut(a_date, "week")))
[1] "2017-07-10"
> (beginning_date_month <- as.Date(cut(a_date, "month")))
[1] "2017-07-01"
> (beginning_date_quarter <- as.Date(cut(a_date, "quarter")))
[1] "2017-07-01"
> (beginning_date_year <- as.Date(cut(a_date, "year")))
[1] "2017-01-01"
import numpy as np
from numpy import array

arr = array([[[1, 1],
              [2, 2],
              [3, 3]],
             [[2, 1],
              [2, 2],
              [2, 3]],
             [[3, 1],
              [3, 2],
              [3, 3]]])


bool_array = arr > 1

indices = np.all(bool_array[:,:,0],axis = 1)

new_arr = arr[indices]