georgehere
georgehere

Reputation: 630

filtering numpy array indexes Python

In the code below all_data values are the indexes of equals. filtered_set and filtered_set2 are filtered alldata values. I want to write a program where it prints out the filtered versions filtered_set/2 indexes only for the equals values. How would I be able to do that and get the expected output below? The predefined arrays all_data, equals, filtered_set, filtered_set2 cannot be changed.

Code:

import numpy as np 

equals = np.array([17, 256, 3, 4, 
                    5, 6, 734, 8, 92, 10, 
                    1121, 12, 1332, 1445, 1135])


all_data= np.array([1019131, 1019385, 1019431, 1160014, 
                    1160026, 1160031, 1160056, 1160231, 1161079, 1163452, 
                    1163471, 1163849, 1163911, 1196406, 1196442])


filtered_set = np.array([1019131, 1019431, 1160026, 1160056, 1161079, 1163471,
 1163911, 1196442, 1196761, 1198446, 1220084, 1221135, 
 1226974, 1271089, 1271361])

filtered_set2 = np.array([1019385, 1160014, 1160031, 1160231, 1163452, 1163849,
 1196406, 1196643, 1196849, 1220071, 1220643, 1225280,
 1271054, 1271249, 1279476])

set1 =[]
set2 =[]

def differences(filter_vals, store_sets):
    for count, (d,y) in enumerate(zip(all_data,filter_vals)):
        if d == y:
            v = equals[count]
            store_sets.extend(v)
    print(store_sets)

differences(filtered_set, set1)
differences(filtered_set2, set2)

Error Output:

TypeError: 'numpy.int64' object is not iterable

Expected Output:

set1 =[17, 3, 5, 734, 92, 1121, 1332, 1135]
sets2 = [256, 4, 6, 8, 10, 12, 1445]

Upvotes: 1

Views: 66

Answers (1)

Hetal Thaker
Hetal Thaker

Reputation: 717

Using list comprehension it can be done as :

set1 = [equals[i] for i in range(len(all_data)) if all_data[i] in filtered_set]
set2 = [equals[i] for i in range(len(all_data)) if all_data[i] in filtered_set2]
print(set1)
print(set2)

Upvotes: 1

Related Questions