0

To improve the execution time, I replaced a comprehension list with a condition in with np.where(). It works fine where the value matches but i want to have a condition where the value is in the string not equal:

import numpy as np
currencies = np.array(["USD","NZL","EUR","KWR"])
currencie = [x for x in list(currencies) if x in "USDKLR EUR"]
#returns ["USD","EUR"]
#What works:
currencie = currencies[np.where(currencies == "EUR")]
#returns ["EUR"]

What I want is the in condition but using np.where or numpy function, no list treatement.

currencie = currencies[np.where(currencies in "USDKLR EUR")]
alphaBetaGamma
  • 653
  • 6
  • 19
  • I've updated my question. Sorry for the confusion. – alphaBetaGamma Sep 03 '21 at 11:24
  • 1
    `where` is only as good as its condition argument. It isn't an iterator. It just finds the True elements. While numpy has a set of string functions, they use string methods and aren't any faster than list comprehension. – hpaulj Sep 03 '21 at 14:39

1 Answers1

2

Question has basically already been asked here.

Solution would be:

In [6]: currencie = currencies[ 
   ...:     np.where( 
   ...:         np.core.defchararray.find( 
   ...:             "USDKLR EUR", currencies 
   ...:         ) != -1 
   ...:     ) 
   ...: ]                            

In [7]: currencie                                                                                                             
Out[7]: array(['USD', 'EUR'], dtype='<U3')

For explanation see the linked question.

faemmi
  • 201
  • 1
  • 4