Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Question

Post Reopened by hpaulj arrays Users with the arrays badge or a synonym can single-handedly close questions as duplicates and reopen them as needed.
Post Closed as "Duplicate" by Kasravnd, Community Bot
edited tags
Link
Kasravnd
  • 107.7k
  • 19
  • 167
  • 195
Source Link

Python ndarray with elements of different types

I wanted to create an array to hold mixed types - string and int.

The following code did not work as desired - all elements got typed as String.

>>> a=numpy.array(["Str",1,2,3,4])
>>> print a
['Str' '1' '2' '3' '4']
>>> print type(a[0]),type(a[1])
<type 'numpy.string_'> <type 'numpy.string_'>

All elements of the array were typed as 'numpy.string_'

But, oddly enough, if I pass one of the elements as "None", the types turn out as desired:

>>> a=numpy.array(["Str",None,2,3,4])
>>> print a
['Str' None 2 3 4]
>>> print type(a[0]),type(a[1]),type(a[2])
<type 'str'> <type 'NoneType'> <type 'int'>

Thus, including a "None" element provides me with a workaround, but I am wondering why this should be the case. Even if I don't pass one of the elements as None, shouldn't the elements be typed as they are passed?

lang-py

AltStyle によって変換されたページ (->オリジナル) /