假设我有一个矩阵数组表。
uvv = np.array([[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]])
我将专注于具有全零值的行,例如row 2
,然后,我想在row 2
的某个列中random 1 two or three times
,但该列在其他行中不得出现1。根据uvv表,我可以在1,2,3,7,8,9,10,11,12,14,16,18
列的row 2
中随机1。
这是我在row 2
的2, 14, 18
列中添加随机1时的目标示例:
tem = np.array([[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]])
谢谢.
3条答案
按热度按时间q9rjltbz1#
您可以使用布尔掩码来查找行和可用列:
输出量:
zpjtge222#
解决方案:
解释作为注解包含在整个代码中。
wribegjk3#
不是 NumPy Maven,这里有一个解决方案(当然还有其他更快,更优雅的解决方案)。
使用的功能:
输出: