如何在数组的随机索引中添加元素?

时间:2017-05-03 07:46:22

标签: python arrays numpy random

我已经生成了一个4乘4的数组。然后我生成了长度为8的1和0的1D数组,例如[0 1 0 1 0 1 1 0]。然后,我生成了一个种子,用于创建随机索引的样本。生成的索引数等于消息中的元素数。现在,我希望在生成的索引中添加消息元素,这些元素表示4乘4数组中索引的位置。在4乘4矩阵的索引中添加消息的元素之后。我希望显示新的4乘4阵列矩阵和添加的元素。

import numpy as np  
import random  
from PIL import Image 
import matplotlib.pyplot as plt 

#array  
cover = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])

max_len = (4 * 4)  #number of elements in cover since we have a 4 by 4 array


#Generating Message
msg = np.random.randint(2, size=8)  
len_msg = len(msg)

#Generating a seed which will be used to locate where the msg will be added in the matrix
seed = 4  
print "The chosen seed is %d" % (seed)  
random.seed(seed)

#Generate Indices to be used to add in matrix
indices = random.sample(range(len_msg, max_len),len_msg)  

1 个答案:

答案 0 :(得分:2)

如果我正确理解了这个问题,我认为这就是你要找的。

import numpy as np

cover = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])

max_len = cover.size

msg = np.random.randint(2, size=8)  

np.random.seed(4)
indices = np.random.choice(range(max_len), msg.size, replace=False)

cover.ravel()[indices] += msg