BFTM - 1 year ago 365

Python Question

Suppose I have a numpy array:

`data = np.array([[1,1,1],[2,2,2],[3,3,3]])`

and I have a corresponding "vector:"

`vector = np.array([1,2,3])`

How do I operate on

`data`

`sub_result = [[0,0,0], [0,0,0], [0,0,0]]`

div_result = [[1,1,1], [1,1,1], [1,1,1]]

Long story short: How do I perform an operation on each row of a 2D array with a 1D array of scalars that correspond to each row?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Here you go. You just need to use `None`

(or alternatively `np.newaxis`

) combined with broadcasting:

```
In [6]: data - vector[:,None]
Out[6]:
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
In [7]: data / vector[:,None]
Out[7]:
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**