1

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)
1
  • 1
    new_array = [i for i in in_array if i[0] in in_list] Commented Jun 21, 2019 at 0:57

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.