convert a list of Quantity object into an array of Quantity object · Issue #183 · python-quantities/python-quantities · GitHub
Skip to content

convert a list of Quantity object into an array of Quantity object #183

Open

Description

@xiki-tempula

I wonder if it is possible to have a function to convert a list of Quantity into an array of Quantity object?

>>> import numpy as np
>>> import quantities as pq
>>> a = 1 * pq.e
>>> a
array(1.) * e
>>> b = [a, a]
>>> b
[array(1.) * e, array(1.) * e]
>>> np.array(b)
array([1., 1.])

So I wonder if there could be a function

>>> pq.array(b)
array([1., 1.]) * e

Activity

  1. twmr commented on May 22, 2021

    @twmr
    Contributor

    I'm using the following function for this use-case (the name of it could be improved, though)

    def quantitylistrescale(seq, unit=None):
        """Convert list of quantities to a rescaled quantity array
    
        Examples
        --------
    
        >>> import quantities as pq
        >>> a = 3 * pq.m; b = 2.5 * pq.mm
        >>> quantitylistrescale([a, b], 'cm')
        array([3.0e+02, 2.5e-01]) * cm
    
        If no ``unit`` is given, the elements will be rescaled to the unit of the
        first quantity.
    
        >>> quantitylistrescale([a, b])
        array([3.0e+00, 2.5e-03]) * m
    
        >>> quantitylistrescale([])
        Traceback (most recent call last):
            ...
        StopIteration
        >>> quantitylistrescale([3 * pq.m, 4 * pq.V])
        Traceback (most recent call last):
            ...
        ValueError: Unable to convert between units of "V" and "m"
    
        """
        assert all(isinstance(item, pq.Quantity) for item in seq), (
            f"{seq} contains objects which are not of type pq.Quantity")
    
        if unit is None:
            first = next(iter(seq))
            unit = first.dimensionality.string
    
        rescaled_seq = [item.rescale(unit).magnitude for item in seq]
    
        return pq.Quantity(rescaled_seq, unit)
  2. xiki-tempula commented on May 23, 2021

    @xiki-tempula
    Author

    I'm using a similar function (without type checking as I know what is in the array) but I felt that it might be good to have it in the package, like pq.array().

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions