V
V
Vechnyy2021-02-16 18:50:14
Python
Vechnyy, 2021-02-16 18:50:14

How to convert an array to a new one with the following values?

How to convert an array to a new one through a for loop with the following values?

* "small" if values ​​are less than 20
* "medium" if values ​​are between [20, 30]
* "large" if values ​​are greater than 30

# создадим трехмерный массив для примера
a_random = np.random.randint(15, 37, (2, 3, 4))
print(a_random)

Answer the question

In order to leave comments, you need to log in

5 answer(s)
O
o5a, 2021-02-16
@Vechnyy

b_random = np.select([a_random < 20, a_random <= 30, a_random > 30], ["small", "medium", "large"])

W
Wataru, 2021-02-16
@wataru

print ([("small" if a < 20 else "medium") if a <=30 else "large" for a in a_random])

V
Vladimir Kuts, 2021-02-17
@fox_12

How to convert an array to a new one through a for loop with the following values

I didn't see the for loop in the marked answer.
In general, this is solved by recursion:
def mark(data):
    if isinstance(data, (int, np.int32)):
        if data < 20:return 'small'
        elif data <= 30:return 'medium'
        else:return 'large'
    elif isinstance(data, (list, np.ndarray)):
        return [mark(item) for item in data]   #  а вот и цикл for

a_random = np.random.randint(15, 37, (2, 3, 4))
print(a_random)
    
print(mark(a_random))

# [
#
# ]
# [, ]

E
Eugene Volf, 2017-10-03
@ya_yshel_rabotati_v_teleg

So: $array = array_values($array);?

Z
zorca, 2017-10-03
@zorca

array_values

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question