Pythonic way of zeroing numpy array axis

时间:2016-07-26 11:50:58

标签: python numpy

Bit annoyed I haven't been able to get this myself, so here goes.

Say I have a 2 dimensional numpy array

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])

I am in a situation where I want to zero a column in this array, but maintain the original array. I can do this by

b = a.copy()
b[:,1] = 0

to get

array([[1, 0, 3],
       [4, 0, 6],
       [7, 0, 9]])

or if I want to zero a series of columns, I can do

b = a.copy()
b[:,[0,3]] = 0

to get

array([[0, 2, 0],
       [0, 5, 0],
       [0, 8, 0]])

The b array will only be used one and then discarded.

Is there any more pythonic way of doing this that can be done as a one liner? I only want the zero valued b array to pass a plotting routine, after which is not needed. Essentially, I don't want to have an extra two lines before calling my plotting function - if I can do it as I call my routine it be much cleaner. For example

plotting_func(<numpy_magic_here>)

instead of

b = a.copy()
b[:,1] = 0
plotting_func(b)

only for b to never be used again

1 个答案:

答案 0 :(得分:2)

要将某些列设置为零,可以使用np.in1dnp.arange一起创建无效元素的掩码,当与输入数组相乘时,会使用{{1将无效列设置为零}}。因此,我们将有一个单行实现,如此 -

NumPy broadcasting

或者,可以使用a*~np.in1d(np.arange(a.shape[1]),cols_to_be_reset) 来选择而不是乘法,就像这样 -

np.where

请注意,这不是为了表现,而是作为一个单行。

示例运行 -

np.where(np.in1d(np.arange(a.shape[1]),cols_to_be_reset),0,a)