Using string as array indices in NumPy

此生再无相见时 提交于 2019-12-13 03:38:11

问题


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?


回答1:


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_]



回答2:


No, you can not do it like this.

You have to implement a function to parse data from GUI, do some security checks and get value/values from array.




回答3:


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]


来源:https://stackoverflow.com/questions/47351711/using-string-as-array-indices-in-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!