Python Replace Elements in Array At Certain Range

Python replace elements in array at certain range

You can use array[0:10] = [1] * 10, you just need to make an array of the size of the slice you are replacing.

Replacing certain elements of an array based on a given index

you can do it with list comprehension, which will save you some code lines and make it more interpretable, though it won't improve the runtime, as it uses loops under the hood. Also note that by incorparating a varying length lists, you'll loose any runtime improvements of the NumPy library, as to do so it is being cast to dtype=object

Arr1 = np.array([9,7,3,1], dtype=object)

Arr2 = np.array([[14,6], [1], [13,2]], dtype=object)

Arr3 = np.array([0,2])

result = np.array([[Arr1[i]] if not np.sum(Arr3 == i) else Arr2[i] for i in np.arange(Arr1.size)], dtype=object)

result
OUTPUT: array([list([14, 6]), list([7]), list([13, 2]), list([1])], dtype=object)

Cheers

Replace elements of array with their average

Slice and concatenate arrays

   np.concatenate([a[:i], a[i:j].mean().reshape(1,), a[j:]])

Example

a = np.array(list(range(20)))
i = 5
j = 10

np.concatenate([a[:i], a[i:j].mean().reshape(1,), a[j:]])

array([ 0., 1., 2., 3., 4., 7., 10., 11., 12., 13., 14., 15., 16.,
17., 18., 19.])

Replace all elements of Python NumPy Array that are greater than some value

I think both the fastest and most concise way to do this is to use NumPy's built-in Fancy indexing. If you have an ndarray named arr, you can replace all elements >255 with a value x as follows:

arr[arr > 255] = x

I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.

In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit A[A > 0.5] = 5
100 loops, best of 3: 7.59 ms per loop

Replace tensor elements that are out of a certain range

It can be done with native TF operations.

import tensorflow as tf

a = tf.Variable([[0, 2, 1, 7, 5, 6]])
>> <tf.Variable 'Variable:0' shape=(1, 6) dtype=int32, numpy=array([[0, 2, 1, 7, 5, 6]])>

Using tf.where:

# Replace the elements that are < 1 or > 6 with -1.
a = tf.where(tf.less(a, 1), -1, a)
a = tf.where(tf.greater(a, 6), -1, a)
a
>> <tf.Tensor: shape=(1, 6), dtype=int32, numpy=array([[-1, 2, 1, -1, 5, 6]])>

Or in single line, following the same logic:

a = tf.where(tf.logical_or(tf.less(a, 1), tf.greater(a, 6)), -1, a)
a
>> <tf.Tensor: shape=(1, 6), dtype=int32, numpy=array([[-1, 2, 1, -1, 5, 6]])>

Python replace elements = key in 2D array

You can use list-comprehension:

lst = [[0, 0], [1, 0]]

lst = [[2 if val == 0 else val for val in subl] for subl in lst]
print(lst)

Prints:

[[2, 2], [1, 2]]

Replace all elements of Python NumPy Array that are EQUAL to some values

Try np.isin:

array[np.isin(array, some_values)] = 0


Related Topics



Leave a reply



Submit