简体   繁体   中英

Comparing list elements with a column in numpy array

I have a python list as follows.

list=['M', 'R', 'W']

and a numpy array as follows.

array=[['M',360.0, 360.0],['R', 135.9, 360.0],['W', 101.4, -125.4], ['Y', 115.8, -160.4]]

I want to compare each element in this list with the first column of array and then create a new_array with the elements matched. So the typical output would be as follows.

new_array=[['M',360.0, 360.0],['R', 135.9, 360.0],['W', 101.4, -125.4]]

I tried the following code.

new_array=np.empty((4,3)) 

for i in range (0,len(list)):
           if list[i]==array[i; 0:1]
                new_array=np.append(new_array, (array[i,1:4].reshape(4,3)), axis=0)

Do this list comprehension:

list=['M', 'R', 'W']
array=[['M',360.0, 360.0],['R', 135.9, 360.0],['W', 101.4, -125.4], ['Y', 115.8, -160.4]]

new_array = [x for x in array if x[0] in list]
print(new_array)

Is that really a numpy array, or just a 'array' by name?

In [238]: np.array([['M',360.0, 360.0],['R', 135.9, 360.0],['W', 101.4, -125.4], ['Y', 115.8, -160.4]
     ...: ])                                                                                         
Out[238]: 
array([['M', '360.0', '360.0'],
       ['R', '135.9', '360.0'],
       ['W', '101.4', '-125.4'],
       ['Y', '115.8', '-160.4']], dtype='<U6')

but let's not pretend, and make a list:

In [239]: alist = [['M',360.0, 360.0],['R', 135.9, 360.0],['W', 101.4, -125.4], ['Y', 115.8, -160.4]]
     ...:                                                                                            
In [240]: alist                                                                                      
Out[240]: 
[['M', 360.0, 360.0],
 ['R', 135.9, 360.0],
 ['W', 101.4, -125.4],
 ['Y', 115.8, -160.4]]
In [241]: list1 = ['M','R','W']

A list comprehension does the job nicely:

In [243]: [item for item in alist if item[0] in list1]                                               
Out[243]: [['M', 360.0, 360.0], ['R', 135.9, 360.0], ['W', 101.4, -125.4]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM