Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, how can i get part of string from an element of array [duplicate]

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]
like image 629
0.B. Avatar asked Jan 18 '26 09:01

0.B.


2 Answers

import numpy
a = numpy.array(['apples', 'foobar', 'cowboy'])    
v = list(a)
b = [val[:3] for val in v]
print(b)
>>> ['app', 'foo', 'cow']
like image 195
Scott Skiles Avatar answered Jan 20 '26 02:01

Scott Skiles


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']
like image 29
Andres Salgado Avatar answered Jan 20 '26 01:01

Andres Salgado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!