【Python】How to convert a numeric to a categorical (text) array? - 101 Numpy Exercises
Q:
以下のようにiris_2dの3番目のカラムをビニングしなさい
- 3より小さい --> 'small'
- 3-5 --> 'medium'
- 5以上 --> 'large'
# Input url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' iris_2d = np.genfromtxt(url, delimiter=',', dtype='object')
A:
# Input url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' iris = np.genfromtxt(url, delimiter=',', dtype='object') names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species') # Bin petallength petal_length_bin = np.digitize(iris[:, 2].astype('float'), [0, 3, 5, 10]) # Map it to respective category label_map = {1: 'small', 2: 'medium', 3: 'large', 4: np.nan} petal_length_cat = [label_map[x] for x in petal_length_bin] # View petal_length_cat[:4] <#> ['small', 'small', 'small', 'small']