Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape for array multiplication/division in python

I'm encountering an annoying shape mismatch issue when I'm working with arrays that are the same length, but one is only width one. For example:

import numpy as np
x = np.ones(80)
y = np.ones([80, 100])
x*y 

ValueError: shape mismatch: objects cannot be broadcast to a single shape

The simple solution is y*x.reshape(x.shape[0],1). However, I often end up subsetting one column of an array, and then having to designate this reshape. Is there a way to avoid this?

like image 528
mike Avatar asked Feb 17 '26 01:02

mike


2 Answers

Two somewhat easy ways are:

(x * y.T).T

or

x.reshape((-1,1)) * y

Numpy's broadcasting is a very powerful feature, and will do exactly what you want automatically, but it expects the last axis (or axes) of the arrays to have the same shape, not the first axes. Thus, you need to transpose y for it to work.

The second option is the same as what you're doing, but -1 is treated as a placeholder for the array's size, which reduces some typing.

like image 71
Joe Kington Avatar answered Feb 19 '26 14:02

Joe Kington


The favored method is to use a "newaxis", that is

x[:, numpy.newaxis] * y

It is very readable and efficient.

like image 33
rocksportrocker Avatar answered Feb 19 '26 14:02

rocksportrocker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!