tony selcuk
tony selcuk

Reputation: 687

Filtering array strings with Numpy

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

Upvotes: 0

Views: 1002

Answers (2)

Victor Schröder
Victor Schröder

Reputation: 7727

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')

Upvotes: 0

Henry Ecker
Henry Ecker

Reputation: 35636

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.

Upvotes: 1

Related Questions