3

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

3 Answers 3

1
import numpy
a = numpy.array(['apples', 'foobar', 'cowboy'])    
v = list(a)
b = [val[:3] for val in v]
print(b)
>>> ['app', 'foo', 'cow']
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Try this:

b = [a[i][:3] for i in range(len(a))]
print(b)

Output:

['app','foo','cow']

1 Comment

@0.B. Thanks for your accept, now you have more than 15 reputation so you can upvote if you want

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.