简体   繁体   中英

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

如果您相信字符串的来源,那么可以使用eval

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM