Skip to content

astype converts numpy array values to 0.0 for structured dtype #7058

Closed

Description

@mpconte

import numpy as np

dtype = np.dtype([('Point', 'f', (3,))])
ones = np.ones(1, dtype=dtype) --> array([([1.0, 1.0, 1.0],)], dtype=[('Point', '<f4', (3,))])
flattened_dtype = np.dtype([('x', 'f'), ('y', 'f'), ('z', 'f')])
flat_ones = ones.astype(flattened_dtype) --> array([(0.0, 0.0, 0.0)], dtype=[('x', '<f4'), ('y', '<f4'), ('z', '<f4')])

numpy version 1.9.2

Activity

  1. charris commented on Jan 18, 2016

    @charris
    Member

    Also in 1.11.

  2. ahaldane commented on Jan 18, 2016

    @ahaldane
    Member

    I will check when I get home, but I suspect this is another version of the long-standing bug which could be fixed by #6053. Specifically, I think this is example 'v3' in the example there: When numpy does not find a matching field-name on the lhs, it simply assigns 0 to the rhs field.

  3. ahaldane commented on Jan 18, 2016

    @ahaldane
    Member

    I'd also add, @mpconte's example is in some sense the current desired behavior: Assignment between two structures arrays currently works by matching up field names between the lhs and rhs. If a field name on the rhs is not present in the lhs, that field gets assigned 0. This is not documented anywhere, but there are comments in the code suggesting it is intentional.

    If you want a real mind-bender, replaced flattened_dtype in your example by

    flattened_dtype = np.dtype([('x', 'f'), ('Point', 'f'), ('z', 'f')])
    
  4. charris commented on Jan 18, 2016

    @charris
    Member

    That makes sense.

  5. mpconte commented on Jan 19, 2016

    @mpconte
    Author

    Thanks for the insight.
    I also just discovered that using view instead of astype acutally gives me the result I'd expect, regardless of field names, thanks.

  6. added 3 commits that reference this issue on Jun 17, 2016
    2ef0103
  7. 6 remaining items

  8. added a commit that references this issue on Oct 23, 2017
    ae582a8
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