For example, I have an array with string elements and I only want the first 3 characters:
>>> import numpy
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
what can i do to obtain ['app', 'foo', 'cow']
I tried the following but it doesn't work
>>> b = a[:],[0,2]
import numpy
a = numpy.array(['apples', 'foobar', 'cowboy'])
v = list(a)
b = [val[:3] for val in v]
print(b)
>>> ['app', 'foo', 'cow']
Try using map like so:
import numpy
a = numpy.array(['apples', 'foobar', 'cowboy'])
b = map(lambda string: string[:3], a)
print(b) # ['app', 'foo', 'cow']
One good thing about using this method is that if you want to do more complicated things to each element in the numpy array, you can just define a more sophisticated, one-argument function that takes in an element from that array and then spits out the desired data like so:
import numpy
def some_complex_func(element):
"""
Do some complicated things to element here.
"""
# In this case, only return the first three characters of each string
return element[:3]
a = numpy.array(['apples', 'foobar', 'cowboy'])
b = map(some_complex_func, a)
print(b) # ['app', 'foo', 'cow']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With