Skip to content
Advertisement

How to add noise to row/column selection in python

I want to select a specific row/column of a matrix i have, the twist however is that i want an added noise in the selection of the chosen row.

Example

I have a matrix m of size 100x100. I now want to select row 40 i.e. m[40,:].

What is actually wanted however is not an array with all values of row 40, but an array along the same axis with a small noise in the row selection. I.e. random values of row 38,39,40,41,42

[[1,2,3,4],
[5,6,7,8],
[9,1,2,3],
[4,5,6,7]]

noisy_selection = m[2,:]

i.e. noise_selection: [4,7,1,6]

Advertisement

Answer

Assuming this 10×10 input and getting column 3 ± 1:

# setting up example
np.random.seed(0)
a = np.arange(100).reshape(10, 10, order='F')

# target column
col = 3

# noise (+ -1/0/1)
rand = np.random.randint(-1, 2, a.shape[0])
# example:
# array([2, 3, 2, 3, 3, 4, 2, 4, 2, 2])

out = a[np.arange(a.shape[0]), col+rand]
# array([20, 31, 22, 33, 34, 45, 26, 47, 28, 29])

used input:

array([[ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90],
       [ 1, 11, 21, 31, 41, 51, 61, 71, 81, 91],
       [ 2, 12, 22, 32, 42, 52, 62, 72, 82, 92],
       [ 3, 13, 23, 33, 43, 53, 63, 73, 83, 93],
       [ 4, 14, 24, 34, 44, 54, 64, 74, 84, 94],
       [ 5, 15, 25, 35, 45, 55, 65, 75, 85, 95],
       [ 6, 16, 26, 36, 46, 56, 66, 76, 86, 96],
       [ 7, 17, 27, 37, 47, 57, 67, 77, 87, 97],
       [ 8, 18, 28, 38, 48, 58, 68, 78, 88, 98],
       [ 9, 19, 29, 39, 49, 59, 69, 79, 89, 99]])
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement