0

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

2

2 Answers 2

2

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

instead of %s may use f string as eval(f'data[{",".join(string1)}]') or format method as eval('data[{}]'.format(",".join(string1)))
0

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.

1 Comment

Why use regex if you can just split by :? e.g. list(map(int,"29:32".split(":")))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.