3

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
strpeter
  • 2,562
  • 3
  • 27
  • 48
user2596490
  • 31
  • 1
  • 1
  • 2
  • 1
    `Flux140` looks more like a list of string than a numpy array. Elements are strings and, for proper python syntax, they are missing the coma between elements. – user2304916 Jul 18 '13 at 16:44
  • 2
    It's definitely not a list of strings. If it was a list of strings, `*` would've been list repetition. That looks like the `print`ed representation of a NumPy object array. – user2357112 Jul 18 '13 at 16:46
  • Are you sure you are using a numpy array? It looks like your submitting a list, and instead it should be a numpy array. you can use the `type` argument to determine if its truly a numpy array – LeavesBreathe Dec 04 '15 at 17:45

2 Answers2

9

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
askewchan
  • 45,161
  • 17
  • 118
  • 134
1

That's an array of strings. You want an array of numbers. Parse the input with float or something before making the array. (What to do about those 'null's depends on your application.)

user2357112
  • 260,549
  • 28
  • 431
  • 505