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

Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
seeker
  • 1
  • 2
    Possible duplicate of [Numpy slicing from variable](https://stackoverflow.com/questions/12616821/numpy-slicing-from-variable) – Georgy Jul 26 '19 at 10:16
  • 1
    Related: [Using string as array indices in NumPy](https://stackoverflow.com/questions/47351711/using-string-as-array-indices-in-numpy-python) and [Using a string to define Numpy array slice](https://stackoverflow.com/questions/43089907/using-a-string-to-define-numpy-array-slice) – Georgy Jul 26 '19 at 10:21

2 Answers2

2

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

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

tstanisl
  • 13,520
  • 2
  • 25
  • 40
  • instead of `%s` may use f string as `eval(f'data[{",".join(string1)}]')` or format method as `eval('data[{}]'.format(",".join(string1)))` – ydhhat Oct 27 '21 at 14:16
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.

max xilian
  • 463
  • 2
  • 11