mike
mike

Reputation: 23821

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?

Upvotes: 3

Views: 2583

Answers (2)

rocksportrocker
rocksportrocker

Reputation: 7419

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

x[:, numpy.newaxis] * y

It is very readable and efficient.

Upvotes: 4

Joe Kington
Joe Kington

Reputation: 284750

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.

Upvotes: 5

Related Questions