如何调整Numpy数组的大小,以添加/替换由数组每行中的值确定的组合行



所以我有一个程序,它在某个时刻创建随机数组,并且我执行了一个操作,即添加行,同时根据行中的值替换其他行。其中一个随机阵列看起来像这样,但请记住,它的大小可能会随机变化,从3x3到10x10:

0 2 0 1
1 0 0 1
1 0 2 1
2 0 1 2

对于至少有一个值等于2的每一行,我需要删除/替换该行并添加更多行。添加的行数将取决于0和1的可能组合数,其中数字数等于每行中计数的2s数。每个添加的行将在2s所在的位置引入这些组合中的一个。我正在寻找的结果将是这样的:

0 1 0 1 # First combination to replace 0 2 0 1
0 0 0 1 # Second combination to replace 0 2 0 1 (Only 2 combinations, only one 2)
1 0 0 1 # Stays the same
1 0 1 1 # First combination to replace 1 0 2 1 
1 0 0 1 # Second combination to replace 1 0 2 1 (Only 2 combinations, only one 2)
0 0 1 0 # First combination to replace 2 0 1 2
0 0 1 1 # Second combination to replace 2 0 1 2
1 0 1 1 # Third combination to replace 2 0 1 2
1 0 1 0 # Fourth combination to replace 2 0 1 2 (4 combinations, there are two 2s)

如果你知道一种麻木的方式来实现这一点,我将不胜感激。

您可以尝试以下操作。创建示例数组:

import numpy as np
np.random.seed(5)
a = np.random.randint(0, 3, (4, 4))
print(a)

这给出:

[[2 1 2 2]
[0 1 0 0]
[2 0 2 0]
[0 1 1 0]]

计算输出数组:

ts = (a == 2).sum(axis=1)
r = np.hstack([np.array(np.meshgrid(*[[0, 1]] * t)).reshape(t, -1).T.ravel() for t in ts if t])
out = np.repeat(a, 2**ts, axis=0)
out[out == 2] = r
print(out)

结果:

[[0 1 0 0]
[0 1 0 1]
[1 1 0 0]
[1 1 0 1]
[0 1 1 0]
[0 1 1 1]
[1 1 1 0]
[1 1 1 1]
[0 1 0 0]
[0 0 0 0]
[1 0 0 0]
[0 0 1 0]
[1 0 1 0]
[0 1 1 0]]

不是最漂亮的代码,但它能完成任务。您可以清理itertools调用,但这可以让您了解它是如何工作的。

import numpy as np
import itertools
X = np.array([[0, 2, 0, 1],
[1, 0, 0, 1],
[1, 0, 2, 1],
[2, 0, 1, 2]])

def add(X_,Y):
if Y.size == 0:
Y = X_
else:
Y = np.vstack((Y, X_))
return(Y)
Y = np.array([])
for i in range(len(X)):
if 2 not in X[i,:]:
Y = add(X[i,:], Y)
else:
a = np.where(X[i,:]==2)[0]
n = [[i for i in itertools.chain([1, 0])] for _ in range(len(a))]
m = list(itertools.product(*n))
for j in range(len(m)):            
M = 1 * X[i,:]
u = list(m[j])
for k in range(len(a)):
M[a[k]] = u[k]
Y = add(M, Y)
print(Y)
#[[0 1 0 1]
# [0 0 0 1]
# [1 0 0 1]
# [1 0 1 1]
# [1 0 0 1]
# [1 0 1 1]
# [1 0 1 0]
# [0 0 1 1]
# [0 0 1 0]]

最新更新