0

How could I write a numpy function where it only filters out the array strings that ends with 'USD'. How would I be able to execute this filter without a for loop.

import numpy as np
Array= ['BTCUSD', 'ETHUSD', 'David', 'georGe', 'XRPUSD', 'USDAUD', 'ETHUSDC' ]

Expected Output

['BTCUSD', 'ETHUSD',  'XRPUSD']
1
  • numpy doesn't have fast string methods, so beware of trying to replace list/string methods with numpy. Commented Apr 28, 2021 at 19:44

2 Answers 2

1

Using numpy char.endswith

import numpy as np

a = np.array(['BTCUSD', 'ETHUSD', 'David', 'georGe', 'XRPUSD', 'USDAUD', 'ETHUSDC'])
print(a[np.char.endswith(a, 'USD')])

Output:

['BTCUSD' 'ETHUSD' 'XRPUSD']

For a return type of list instead of np.ndarray a comprehension can be used:

import numpy as np

lst = np.array(['BTCUSD', 'ETHUSD', 'David', 'georGe', 'XRPUSD', 'USDAUD', 'ETHUSDC'])
print([elem for elem in lst if elem.endswith('USD')])

Output:

['BTCUSD', 'ETHUSD', 'XRPUSD']

*The comprehension approach can be used on Python lists as well as np arrays.

Sign up to request clarification or add additional context in comments.

2 Comments

My experience is that np.char functions have about the same speed as list comprehensions. They still use python string methods.
I tried doing a[np.char.endswith(a, 'USD', 'USDT')] however doesnt really work
0

About three years later, the accepted answer is now deprecated. The np.char family of functions only operated on fixed length string data and was superseded by the new np.string functions.

The old functions from np.char and the ones in numpy.char.chararray are planned to be removed in a future release of NumPy.

When using NumPy from version 2.0 or newer, the functions from np.string should be preferred. See: https://numpy.org/doc/stable/reference/routines.char.html#module-numpy.char

Currently, the accepted way of doing what was requested by the OP would be using the np.string.endswith:

>>> import numpy as np
>>> a = np.array(['BTCUSD', 'ETHUSD', 'David', 'georGe', 'XRPUSD', 'USDAUD', 'ETHUSDC'])
>>> a[np.strings.endswith(a, 'USD')]
array(['BTCUSD', 'ETHUSD', 'XRPUSD'], dtype='<U7')

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.