3

I have a numpy structured array. The final column needs to contain the result of a simple math equation based on the other values in the row. Problem is I get the following error when trying to calculate the square root portion of the equation:

TypeError: only length-1 arrays can be converted to Python scalars

Limitation is that I cannot iterate the array to add the values one at a time.

Here's an example to show the error:

import numpy as np
import math

data = np.random.randint(-100, 100, (1, 6, 4))

data[:,3] = math.sqrt((0-data[:,0])**2 + (0-data[:,1])**2 + (0-data[:,2])**2)
Carl
  • 1,346
  • 15
  • 35

1 Answers1

6

You simply need to use np.sqrt instead of math.sqrt (the latter only works on single values).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436