Skip to content

Quantity issue with np.ma.std and np.ma.var #10792

Closed

Description

@larrybradley

Just ran across this puzzling behavior with np.ma.std and np.ma.var with Quantity inputs:

>>> import numpy as np
>>> import astropy.units as u
>>> a = np.arange(5.) << u.km
>>> np.std(a)
1.4142136 km
>>> np.ma.std(a)  # returns wrong unit!
1.4142136 km(1/2)

>>> np.var(a)
2.0 km2
>>> np.ma.var(a)  # returns wrong unit!
2.0 km

np.ma.mean works fine:

>>> np.mean(a)
2 km
>>> np.ma.mean(a)
2 km

Is this an upstream bug in numpy?
@mhvk

Activity

  1. mhvk commented on Oct 2, 2020

    @mhvk
    Contributor

    @larrybradley - Quantity has never really interacted well with masked arrays, sadly. The problem is that both override standard numpy behaviour, and the way they do it interferes with each other. So, I fear "upstream fix required" is the right answer.... That said, it may be worth checking what exactly goes wrong in your examples, since it may be fixable (my guess is that np.ma.var is the culprit, and np.ma.std just a consequence of taking a square room after, but I haven't actually looked...)

  2. mhvk commented on Apr 12, 2021

    @mhvk
    Contributor

    Going to call this fixed by #11127 even if that really means one has to use our own Masked class.

  3. larrybradley commented on Aug 5, 2021

    @larrybradley
    MemberAuthor

    @mhvk The Masked class is great! Any chance this will make its way to numpy? 😃

    It might be good to mention somewhere in the Masked documentation that Masked objects shouldn't be used with np.ma functions:

    >>> a = Masked(np.arange(3) << u.km, [True, False, False])
    >>> np.ma.mean(a)
    <MaskedQuantity ——— km>
    
    >>> np.ma.var(a)
    ...
    UnitConversionError: '' (dimensionless) and 'km' (length) are not convertible
  4. mhvk commented on Aug 5, 2021

    @mhvk
    Contributor

    I've been meaning to at least let numpy know about this, but I think the chance that it will get in is tiny...

    But, yes, you are right it should be documented that one should not use the np.ma functions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions