python array create function
i’m have some data (есть входной массив)
x = np.array([
[-1.8, 1.12, 50.6],
[-3.2,4.8,6.8],
[2.6,14.04,16.8],
])
есть массив соответствий (МАСКА // фильтр)
cons_data = np.array([
[1,4], # применяем к -1.8 -3.2 2.6
[1,7,14], # применяем к 1.12 4.8 14.04
[1,5,6,38], # применяем к 50.6 6.8 16.8
])
need cerate def (нужно создать функцию) которая будет проверять приведенное значение из Х к целому проверять его, если есть в массиве соответствий то не менять, иначе брать случайное значение из cons_data
def test_func(x,cons_data ):
need return res
[-1.8, 1.12, 50.6] == check -1.8 =>int = -2 not [1,4] => give random 1 or 4 = 4
[-1.8, 1.12, 50.6] == check 1.12 =>int = 1 In [1,7,14] => == 1.12
[-1.8, 1.12, 50.6] check 50.6 =>int = 51 not [1,5,6,38] => give random 1 or 5 or 6 or 38 = 5
res x[0] ==> [-1.8, 1.12, 50.6] ==> [4.0, 1.12, 5.0]
full res examle
res [
[4.0, 1.12, 5.0] ,
[1.0, 7.0, 14.0] ,
[1.0, 14.04, 38.0] ,
]
Ответы (2 шт):
Автор решения: GrAnd
→ Ссылка
def test_func(x, cons_data):
res = np.array(x)
with np.nditer(res, flags=['multi_index'], op_flags=['readwrite']) as it:
for x in it:
if round(x[...].item()) not in cons_data[it.multi_index[1]]:
x[...] = random.choice(cons_data[it.multi_index[1]])
return res
Автор решения: GUIMish
→ Ссылка
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randrange
import numpy as np
x = np.array([
[-1.8, 1.12, 50.6],
[-3.2, 4.8, 6.8],
[2.6, 14.04, 16.8],
]);
cons_data = np.array([
[1, 4], # применяем к -1.8 -3.2 2.6
[1, 7, 14], # применяем к 1.12 4.8 14.04
[1, 5, 6, 38], # применяем к 50.6 6.8 16.8
]);
def test_func(x_np, cons_data_np):
res = []; xn = x_np.tolist();
cdn = cons_data_np.tolist();
for i in range(0, len(xn)):
tmp = [];
for n in range(0, len(xn[i])):
if (int(round(xn[i][n])) in cdn[n]):
tmp.append(xn[i][n]);
else:
tmp.append(cdn[n][randrange(0, len(cdn[n]))]);
res.append(tmp);
return res;
res = test_func(x, cons_data);
print(res);