汇总numpy数组的选定行的简便方法

时间:2019-04-21 09:26:42

标签: python numpy

我有一个2D numpy数组L,我想将其转换为另一个具有相同形状的numpy数组,以便将每一行替换为其他所有行。我已经在下面演示了这一点。

我的问题是这样做是否更简洁/优雅(最好使用更高级的numpy语法/工具)。

L = np.array([[ 0,  1,  2],
              [ 3,  4,  5],
              [ 6,  7,  8],
              [ 9, 10, 11]])

store = []
for i in range(L.shape[0]):
    store.append(np.sum(L,axis=0) - L[i])
output = np.stack(store)    

哪个给我正确的输出:

array([[18, 21, 24],
       [15, 18, 21],
       [12, 15, 18],
       [ 9, 12, 15]])

1 个答案:

答案 0 :(得分:2)

只需从列求和中减去public static void main(String[] args) { int score = 0; int correct = 0; int done = 0; Scanner scan = new Scanner(System.in); boolean repeatValue = false; int num1 = 0; // put values outside while in order to re-use them when we need to repeat the same question int num2 = 0; while (true) { try { // if the user input was incorrect (repeatValue = true), use old the previous values for num1 and num2 num1 = repeatValue ? num1 : (int) (Math.random() * 20); num2 = repeatValue ? num2 : (int) ((Math.random() * 20) + 1); System.out.printf("%d %% %d = ?\n", num1, num2); repeatValue = false; // restore flag state if (scan.hasNext("q")) break; if (scan.nextInt() == (num1 % num2)) { score += 20; done += 1; correct += 1; System.out.println( "Correct answer,current score :" + score + ",performance: " + correct + "/" + done); } else { done += 1; System.out.println( "Incorrect answer, Current score:" + score + ", performance: " + correct + "/" + done); } } catch (InputMismatchException e) { System.out.println("invalid input"); scan.next(); repeatValue = true; // flag set to use the same values as before } } System.out.println("Finish"); } ,从而在向量化解决方案的过程中也利用broadcasting-

L