StackOverflow

### Answer rating: 215

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`

along each row to either subtract or divide so the result is:

```
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?

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]])
```

Learning Correct Cryptography by Example. The interconnected world of the current era has drastically changed everything, including banking, entertainment, and even statecraft. Despite difference...

23/09/2020

Automate the Boring Stuff with Python PDF, 2nd Edition: Practical Programming for Total Beginners Illustrated Edition. The second edition of this Python bestseller (over 100,000 copies sold in prin...

22/08/2021

Python: - The Bible - 3 Manuscripts in 1 book:

- Python Programming For Beginners
- Python Programming For Intermediates
- Python Programming for Advanced

12/08/2021

Big data is, admittedly, an overhyped buzzword used by software and hardware companies to boost their sales. Behind the hype, however, there is a real and extremely important technology trend with imp...

10/07/2020

X
# Submit new EBook