Basj Basj - 1 year ago 210
Python Question

Redefine *= operator in numpy

As mentioned here and here, this doesn't work anymore in numpy 1.7+ :

import numpy
A = numpy.array([1, 2, 3, 4], dtype=numpy.int16)
B = numpy.array([0.5, 2.1, 3, 4], dtype=numpy.float64)
A *= B

A workaround is to do:

def mult(a,b):
numpy.multiply(a, b, out=a, casting="unsafe")

def add(a,b):
numpy.add(a, b, out=a, casting="unsafe")


but that's way too long to write for each matrix operation!

How can override the numpy
operator to do this by default?

Should I subclass something?

Answer Source

You can use np.set_numeric_ops to override array arithmetic methods:

import numpy as np

def unsafe_multiply(a, b, out=None):
    return np.multiply(a, b, out=out, casting="unsafe")


A = np.array([1, 2, 3, 4], dtype=np.int16)
B = np.array([0.5, 2.1, 3, 4], dtype=np.float64)
A *= B

# array([ 0,  4,  9, 16], dtype=int16)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download