Reputation: 1081
I have a unmpy array and want to extract some rows of the array. My array has three columns which are x, y and z coordinates:
sr_y=np.array([[10., 1., 8.], [20., 1., 8.1], [30., 1., 7.9], [10., 2., 8.],\
[20., 2., 7.9], [30., 2., 8.], [10., 1., 1.9], [20., 1., 2.],\
[10., 2., 2.1], [20., 2., 2.2], [30., 2., 1.8]])
The array is sorted one. The rows with the same values in their second column are such kind of subset. First three rows of sr_y
have the same value in their second column, so I want the last row ([30., 1., 7.9]
). Then, again rows 4, 5 and 6 make the next subset and I want the last row (the 6th). Then, from row 6 to 7, the third column changes a lot (from 8
to 1.9
). From here to end, I want to extract the first row of each subset. Rows 7 and 8 are a subset and I want row 7. From rows 9, 10 and 11, I want the first one (9th row). Briefly speaking, I want to following array:
np.array([[30., 1., 7.9], [30., 2., 8.], [10., 1., 1.9], [10., 2., 2.1]])
I tried the following code but it did not give me what I want:
exported_data=np.array([])
for i in range (len(sr_y)-1):
if sr_y[i,1] != sr_y[i+1,1] or sr_y[i-1,2]>int (sr_y[i,2]+4):
aa=sr_y[i]
exported_data=np.append (exported_data,aa)
exported_data=exported_data.reshape(-1,3)
In fact, it can not modify role of export after the big change of the third column. After that big change, I want to export the first row of each subset. In advance, Thanks for any help. I do appreciate any contribution.
Upvotes: 0
Views: 281
Reputation: 40628
You can use a flag to indicate if the big step has already occured or not.
delta = 4
before = True
for i in range(sr_y.shape[0]-1):
if before and sr_y[i][0] > sr_y[i+1][0]:
print('(last)', sr_y[i])
if sr_y[i][2] > sr_y[i+1][2] + delta:
before = False
if not before and sr_y[i][0] > sr_y[i+1][0]:
print('(first)', sr_y[i+1])
The first condition will catch last values (>
check) for all subsets before the big step (before
). The second condition handles the flag switch. While the third and last condition catches first values (>
check) for all subsets after the big step (not before
).
Note: Replace the print()
calls with the list.append()
accordingly. It's important that the conditions remain in this order. Since on the iteration where the big set occurs, it will have to catch both the last value for the previous subset and the first value from the following.
Upvotes: 1