Python Forum

Full Version: Type coercion with Numpy arrays
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I understand all data in a Numpy array must be of one type. What decides what type that is, though? If I have

array([[3, 5, 7, 9, "10"]])
then why do they all become string as opposed to the final element becoming float?

Thanks!
Did you look at the documentation, specifically about the dtype parameter?
array is a builtin function that is implemented in C; So, to answer your question you should dive into C-implementation of NumPy... However, that behavior is understandable. In case of different data types of elements, NumPy chooses such data type that is more general than others, e.g.
np.array([1,2,3])  # -> dtype will be int64
np.array([1,2,3.0]) # dtype will be float64
np.array([1,2,'3']) # dtype will be string
class A:
  ...
a = A()
np.array(1, 2, a)  # dtype will be np.object