I have an array. At each step, I want to choose four rows of the array and then if row0 =0, row1=-1, row2=-3, and row3=-4
, then delete that column. And then, move through that 4 rows array with a sliding window size. If after deleting the columns, the number of column are less than or equal to window size, then move to the next 4-rows. Here is the array that I have:
x = np.array([
[6, 10, 5, 0, 0, 4, 5],
[1, 2, 3, -1, 1, 3, 2],
[13, 0, 5, -3, -3, 1, 2],
[1, 4, 5, -4, -4, 5, 6],
[0, 0, 0, 0, 0, 1, 2],
[-1, -1, -1, -1, -1, 3, 4],
[-3, -3 ,-3, -3, 5, 6, 7],
[-4, -4 , 4, 3, 6, 7, 8],
[0, 0 ,0, 0, 0, 1, 2],
[-1, -1, -1, -1, -1, 3, 4],
[-3, -3 ,-3, -3, 5, 6,7],
[-4, -4 ,-4, -4, 6, 7, 8]
])
Explain: in the first 4 rows, column 4 has the condition. Then, we delete this column. Then we choose the first sliding window with size 4*3
and move to the right. For the second 4 rows, the columns 1, 2 has the condition and then we choose the sliding window from column 3. The third 4-rows, column 1,2,3,4 have the condition, then we don't consider this 4 rows at all.
For calculating Y, we choose the first row after the sliding window.
and here is the function which I wrote for calculate the X_new
and Y. This function can calculate the value, but it can not delete that column:
def myf(array, w):
t, z = [], []
for i in range(3):
for cols in range(array.shape[1]-w):
Xtmp = array[4*i:4*i 4, cols:w cols]
t.append(Xtmp)
ztmp = array[4*i, w cols]
z.append(ztmp)
t = np.asarray(t)
z = np.asarray(z)
return t, z
X_new, Y_new = myf(x , 3)
Here is the outputs which I want:
X_new = array([[[ 6, 10, 5],
[ 1, 2, 3],
[13, 0, 5],
[ 1, 4, 5]],
[[10, 5, 0],
[ 2, 3, 1],
[ 0, 5, -3],
[ 4, 5, -4]],
[[ 5, 0, 4],
[ 3, 1, 3],
[ 5, -3, 1],
[ 5, -4, 5]],
[[ 0, 0, 0],
[-1, -1, -1],
[-3, -3, 5],
[ 4, 3, 6]],
[[ 0, 0, 1],
[-1, -1, 3],
[-3, 5, 6],
[ 3, 6, 7]]])
Y_new = array([0, 4, 5, 1, 2])
CodePudding user response:
You need to define a dictionary before you move to the second loop. In the second loop, you should read the data from dictionary. Here is:
def myf(array, w):
t, z = [], []
dic = {}
for i in range(3):
Xf = array[4*i:4*i 4, :]
dic[i] = Xf[:,~((Xf[0]==0)&(Xf[1]==-1)&(Xf[2]==-3)&(Xf[3]==-4))]
for cols in range(dic[i].shape[1]-w):
Xtmp = dic[i][:, cols:w cols]
t.append(Xtmp)
ztmp = dic[i][0, w cols]
z.append(ztmp)
t = np.asarray(t)
z = np.asarray(z)
return t, z
X_new, Y_new = myf(x , 3)
Here is X_new:
array([[[ 6, 10, 5],
[ 1, 2, 3],
[13, 0, 5],
[ 1, 4, 5]],
[[10, 5, 0],
[ 2, 3, 1],
[ 0, 5, -3],
[ 4, 5, -4]],
[[ 5, 0, 4],
[ 3, 1, 3],
[ 5, -3, 1],
[ 5, -4, 5]],
[[ 0, 0, 0],
[-1, -1, -1],
[-3, -3, 5],
[ 4, 3, 6]],
[[ 0, 0, 1],
[-1, -1, 3],
[-3, 5, 6],
[ 3, 6, 7]]])