seeker
seeker

Reputation: 1

Using string in array slicing in NumPy

How can a string be used to get the relevant part of NumPy array?

data = np.random.random([120,120,120])
string1 = ('1:10','20:30')
data[ 1:10,20:30]
data[string1]

I'm getting this error :

IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

Upvotes: 0

Views: 220

Answers (2)

tstanisl
tstanisl

Reputation: 14107

If you are trust the source of strings then you can use eval:

eval('data[%s]' % ','.join(string1))

Upvotes: 2

max xilian
max xilian

Reputation: 613

You can't directly do this with a string. However, you can convert the strings to ints.

I am not really a pro with regular expression, but in this test case

import re
res = re.search("([^:]+):([^:]+)",string1[0]) 
data[int(res[1]):int(res[2])] 

worked.

Upvotes: 0

Related Questions