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 : data - vector[:,None] Out: array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) In : data / vector[:,None] Out: 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...
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...
Python: - The Bible - 3 Manuscripts in 1 book:
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...