a_sircar
a_sircar

Reputation: 15

'numpy.float64' is not iterable for scipy function centre of mass

I've been trying to calculate the centre of mass of precipitation fields from my observation data (.nc format) but I keep getting an error message: "TypeError: 'numpy.float64' object is not iterable"

I've managed to convert my netcdf file from .nc into a xarray dataset and then extract the values to give a (1, 90, 180) array that I then converted into (90, 180) for other functionalities. I then tried calculating centre of mass for the array but it keeps giving me an error message.

from scipy import ndimage

ncobsdata = Dataset('/home/data/20180380293.nc', mode = 'r')
obsdata = xr.open_dataset(xr.backends.NetCDF4DataStore(ncobsdata))
obs = obsdata.rain_total #shape = (1, 90, 180)

obsv = np.squeeze(obs) #I had to do this step to make it (90, 180)

CoM_obsv = ndimage.measurements.center_of_mass(obsv)

I expect to get the centre of mass result but I just keep getting the error message:

File "_____.py", line 10, in <module>
   CoM_obsv = ndimage.measurements.center_of_mass(obsv)
File "________/scipy/ndimage/measurements.py", line 1289, in center_of_mass
   return [tuple(v) for v in numpy.array(results).T]
TypeError: 'numpy.float64' object is not iterable

Upvotes: 1

Views: 424

Answers (1)

PeptideWitch
PeptideWitch

Reputation: 2359

So what was happening here was that both the obs and obsv variables are stored as xarray.DataArrays - this class is a wrapper around regular numpy arrays. To access the underlying np.ndarray, you will need to call the values from the object:

CoM_obsv = ndimage.measurements.center_of_mass(obsv.values)

Note that you didn't need to do this for obsv = np.squeeze(obs) #I had to do this step to make it (90, 180) because there is already a squeeze method available for xarray.DataArrays.

Upvotes: 1

Related Questions