Kostas Belivanis
Kostas Belivanis

Reputation: 407

Filter Multi-Dimensional Array

I have an array (lists) which is NxK. However, I want to "filter" is after inputting some constraints based on values in Columns 4 and 6. This is the code I have so far.

minmag = 5
maxmag = 7

mindist = 25
maxdist = 64

filter = np.zeros((1, 7), dtype='object')
add = np.zeros((1, 7), dtype='object')
k = 0

for i in range(0,len(lists)):
    if lists[i, 4]>= minmag and lists [i, 4] <= maxmag and lists [i, 6]>=mindist and  lists [i, 6]<= maxdist:
        if k == 0:
            for x in range(0,16):
                filter[0, x] = lists[i, x]
            k = 1
        else:
            for x in range(0, 16):
                add[0, x] = lists[i, x]
            filter = np.append(filter, add, axis=0)

It works, however it is not so neat. Just wondering if anyone has a better solution.

Upvotes: 2

Views: 1841

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49805

Simplifying the most repetitive parts:

if k==0:
    for x in xrange(1,8):
        lists[i,x] = filter[0,x]
    k = 1
else:
    for x in xrange(1,8):
        lists[i,x] = add[0,x]
    filter = np.append(filter, add, axis=0)

You could also combine your nested ifs into a single one with the 4 conditions combined with ands.

I also believe (not seeing how lists is defined, I'm not sure) you can replace the outer loop with

for row in lists:

and then use row[x] in place of lists[i,x]

Upvotes: 1

Related Questions