Search code examples
pythonarraysnumpyfilter

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

Solution

  • 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.