简体   繁体   中英

2D ndarray: row-wise operations

I have 2D numpy array, with example shape:

>>> a.shape
(48, 160)

and I want to do simple operation between elements or each row, like a[0] - a[1] but for every row against all other rows.

I know how to do it simply by using for loop and iterating rows, but I was wondering if there is some numpy slicing specific instruction, that can do this without using for loops

You can use broadcasting magic to do this.

import numpy as np
a = np.arange(12).reshape((4, 3))
b = np.arange(15).reshape((5, 3))
diff = a[np.newaxis, :, :] - b[:, np.newaxis, :]
diff.shape
# (5, 4, 3)

This is a good broadcasting tutorial. In this case I make a (1, 4, 3) and b (5, 1, 3) and I get a result that's (5, 4, 3), the difference of every row pair in a and b.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM