Quantity objects should accept pandas Series
See original GitHub issueWhere Astropy expects a Quantity object, it rejects as input a pandas.Series * astropy unit. I believe this is unnecessarily strict, since a numpy array * astropy unit would be permitted. Here is an example of astropy rejecting what I believe should be a valid input of pandas.Series() * u.unit:
----> 1 s1723_spec = specutils.Spectrum1D(spectral_axis = df_s1723['wave'] * u.AA, flux=df_s1723['fnu'] * u.Unit('Jansky'))
~/anaconda3/envs/astroconda/lib/python3.6/site-packages/specutils/spectra/spectrum1d.py in init(self, flux, spectral_axis, wcs, velocity_convention, rest_value, redshift, radial_velocity, bin_specification, **kwargs)
97 if flux is not None:
98 if not isinstance(flux, u.Quantity):
---> 99 raise ValueError("Flux must be a Quantity object.")
100 elif flux.isscalar:
101 flux = u.Quantity([flux])
ValueError: Flux must be a Quantity object.
The kludgy workaround is to put .values after each Series:
s1723_spec = specutils.Spectrum1D(spectral_axis = df_s1723['wave'].values * u.AA, flux=df_s1723['fnu'].values * u.Unit('Jansky'))
However, the workaround is kludgy, and I think unfair to pandas users. A Pandas.Series() will act like a numpy array when it needs to. Here, Astropy is rejecting it before it can.
Please see https://github.com/astropy/specutils/issues/740 , because I discovered the issue in the specutils.Spectrum1D class, although I believe the problem actually lies with Quantities.
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (5 by maintainers)
Top GitHub Comments
I’m actually a bit surprised it does not work, as inside
Quantity
it just tries to convert any otherwise unrecognized input tondarray
and then turn it into a Quantity. So, perhaps good to see what actually happens:So, the problem seems to be that for multiplication,
pd.Series
thinks it can handle units, even though obviously it cannot. In that sense, arguably the problem is with pandas rather than astropy; it should really returnNotImplemented
(or rely less on arbitrary multiplication to give something that it still understands – note that this really is not a trivial problem, I can definitely see the reasoning behind the approach they took…).Anyway, bottom line is that the exact request is not something we can solve in astropy: pandas just takes care of the multiplcation and we get no chance to take control. But there is a good work around for converting a
Series
to aQuantity
: one can just use the class initializer (which will work for everything else too, of course).Interestingly, what works as well (somewhat coincidentally, just because it happens not to be defined by pandas) is the in-place shift operator:
Thanks for the reply. I would be happy to assist in documenting this issue and the approach.