How to covert string to range of number (float)?

时间:2019-04-16 22:46:39

标签: python python-2.7

I have a row of string:

poor: <=0.75; intermediate: >0.75 & <=1.25; normal: >1.25 & <= 2.5; High inducibility: >2.5

I want to create a dictionary based on above string as below:

import numpy
dict = {poor: numpy.arange(0, 0.75, 0.05),
        intermediate: numpy.arange(0.75, 1.25, 0.05),
        normal: numpy.arange(1.25, 2.5, 0.05),
        High: numpy.arange(2.5, 5, 0.05)}

So, is there any good way to do so in python 2.7?

Thanks!

1 个答案:

答案 0 :(得分:0)

Use np.digitize:

import numpy as np
from pprint import pprint

bins = [0.75, 1.25, 2.5]
bin_names = np.array(['poor', 'intermediate', 'normal', 'high'])

data = np.linspace(0, 4, 10, endpoint=False)
result = bin_names[np.digitize(data, bins)]

pprint(list(zip(np.round(data, 1), result)))

Output:

[(0.0, 'poor'),
 (0.4, 'poor'),
 (0.8, 'intermediate'),
 (1.2, 'intermediate'),
 (1.6, 'normal'),
 (2.0, 'normal'),
 (2.4, 'normal'),
 (2.8, 'high'),
 (3.2, 'high'),
 (3.6, 'high')]