Thomas
Thomas

Reputation: 33

Using string as array indices in NumPy

I'm handling large numerical arrays in python through a GUI. I'd like to expose the slicing capabilities to a textbox in a GUI, so I can easily choose part of the array that should be used for the calculation at hand.

Simple example of what I'd like to do:

arr = array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

a = "2:4" # example string from GUI Textbox
b = "[3, 4, 5]" # example string from GUI Textbox


print arr[a] # not valid code -> what should be written here to make it work?
print arr[b] # not valid code -> what should be written here to make it work?

should output:

[20, 30]
[30, 40, 50]

I found out about the slice function, but I'd need to parse my string manually and create a slice. Is there a simpler way?

Upvotes: 3

Views: 6729

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53029

Maybe since you are only expecting a very limited character set it is acceptable using eval this once:

if not all(c in "1234567890-[],: " for c in b): # maybe also limit the length of b?
    # tell user you couldn't parse and exit this branch
slice_ = eval(f'np.s_[{b}]')
# slice_ can now be applied to your array: arr[slice_]

Upvotes: 2

Kishore Devaraj
Kishore Devaraj

Reputation: 156

Try this i think it works, assuming that you will get min and max in your string.

import re
a = "2:4"
min = int(min(re.findall(r'(\d)',a)))
max = int(max(re.findall(r'(\d)',a)))
print arr[min:max]

Upvotes: 0

Related Questions