[Python] Why does NumPy assign different string dtypes when mixing types in np.array()?

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to understand how NumPy determines the dtype when creating an array with mixed types. I noticed that the inferred dtype for strings can vary significantly depending on the order and type of elements in the list.

    print(np.array([1.0, True, 'is']))
    # Output: array(['1.0', 'True', 'is'], dtype='<U32')

    print(np.array(['1.0', True, 'is']))
    # Output: array(['1.0', 'True', 'is'], dtype='<U5')

    print(np.array(['1.0', 'True', 'is']))
    # Output: array(['1.0', 'True', 'is'], dtype='<U4')


    I understand that NumPy upcasts everything to a common type ... usually the most general one.., and that strings tend to dominate. But why does the resulting dtype (<U32, <U5, <U4) differ so much when the content looks almost the same?

    Specifically:

    Why does np.array([1.0, True, 'is']) result in ?

    What determines the exact length in the dtype (e.g., vs )?

    Is there a consistent rule for how NumPy infers the dtype and string length in such cases?

    Continue reading...

Compartilhe esta Página