# Импорт необходимых библиотек
import numpy as np
import matplotlib.pyplot as plt
import random
src = np.random.randint(15,38,(3,4))
print('Исходный массив:\n',src,'\n')
ver = '\nВариант 1 np.full() + срезы\n'
res = np.full((3,4),'medium')
res[src < 20] = 'small'
res[src > 30] = 'large'
print(ver,res)
ver = '\nВариант 2 np.select()\n'
cnd = [
(src < 20),
(src >= 20) & (src <= 30),
(src > 30)
]
res = np.select(cnd,['small','medium','large'])
print(ver,res)
ver = '\nВариант 3 np.where()\n'
# Создание списка условий
cnd = [
(src < 20),
(src >= 20) & (src <= 30),
(src > 30)
]
# Создание списка значений
values = [
'small',
'medium',
'large'
]
# Создание нового массива на основе условий
res = np.where(cnd[0], values[0], np.where(cnd[1], values[1], values[2]))
print(ver,res)
ver = '\nВариант 4 np.vectorize()\n'
def data_based_markup(src):
if src < 20:
return 'small'
elif src >= 20 and src <= 30:
return 'medium'
elif src > 30:
return 'large'
vdata_based_markup = np.vectorize(data_based_markup)
res = vdata_based_markup(src)
print(ver,res)
+ Нет комментариев
Добавить свой