-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Description
While working on #929, I realised it would be very handy to have a way to change the unit of a quantity into a compatible one, and recalculate the values it has in-place. There are probably multiple ways to do this (@wkerzendorf suggested to(...,inplace=True), following PANDAS; one could also think of .to(..., out=one-self), following numpy ufuncs), but for an initial trial, I simply allowed assignment to .unit, which will convert to the requested unit if possible:
def get_unit(self):
return self._unit
def set_unit(self, new_unit):
self_values = self.__array__()
self_values *= self.unit.to(new_unit)
self._unit = Unit(new_unit)
unit = property(get_unit, set_unit)
(Here, I have to get the array view to ensure not to get the overloaded multiply.)
With this,
import astropy.units as u; import numpy as np
a = np.arange(0.,100.,10)*u.deg
a.unit = u.rad
print(a)
yields
[ 0. 0.02777778 0.05555556 0.08333333 0.11111111
0.13888889 0.16666667 0.19444444 0.22222222 0.25 ] cycle
As indicated above, I'm not wedded to a particular implementation (though I'm happy to turn this into a PR), but I think we do need the functionality (or is it there already? @iguananaut, @astrofrog?)