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
3
  • 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. Commented Jul 18, 2013 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 printed representation of a NumPy object array. Commented Jul 18, 2013 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 Commented Dec 4, 2015 at 17:45

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.