Skip to content
Advertisement

Multiply by the factor the number of times that the position appears in the array (Python)

I’m trying to get a “pythonic” way or using a library (anything except “for” loops) for doing this.

my_array = np.array([2,4,6])
my_array[[0,2,0]] = my_array[[0,2,0]] * 2

Expected result:

[8,4,12]

However, I get:

[4,4,12]

This doesn’t work for me as I need to multiply twice the factor (2) for the position 0 if, through the index, the 0 position repeats n amount of times.

“For” loops can’t be used as there are billions of data points

Advertisement

Answer

You could try:

>>> num_occurrences_list = [0,2,0]
>>> factor = 2
>>> my_array * np.power(factor, np.bincount(num_occurrences_list))
array([ 8,  4, 12])

But I am not sure if it provides any advantage over using for loops explicitly.

Here, np.bincount provides an array where each index contains the number of occurrences of it in your list. np.power with base 2 specifies how many times you want to multiply by 2. Finally, you perform the actual multiplication with the computed weights for each element of the array.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement