How to multiply a numpy array by a scalar

user2596490 picture user2596490 · Jul 18, 2013 · Viewed 46.4k times · Source

I have a numpy array and I'm trying to multiply it by a scalar but it keeps throwing an error:

TypeError: unsupported operand type(s) for *: 'numpy.ndarray' and 'int'

My code is:

Flux140 = ['0.958900', 'null', '0.534400']
n = Flux140*3

Answer

askewchan picture askewchan · Jul 18, 2013

The problem is that your array's dtype is a string, and numpy doesn't know how you want to multiply a string by an integer. If it were a list, you'd be repeating the list three times, but an array instead gives you an error.

Try converting your array's dtype from string to float using the astype method. In your case, you'll have trouble with your 'null' values, so you must first convert 'null' to something else:

Flux140[Flux140 == 'null'] = '-1'

Then you can make the type float:

Flux140 = Flux140.astype(float)

If you want your 'null' to be something else, you can change that first:

Flux140[Flux140 == -1] = np.nan

Now you can multiply:

tripled = Flux140 * 3