Python Forum
Type coercion with Numpy arrays
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Type coercion with Numpy arrays
#1
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!
Reply
#2
Did you look at the documentation, specifically about the dtype parameter?
Reply
#3
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 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  problem adding two numpy arrays djf123 2 2,051 Aug-09-2022, 08:31 PM
Last Post: deanhystad
  how to join by stack multiple types in numpy arrays caro 1 1,110 Jun-20-2022, 05:02 PM
Last Post: deanhystad
  numpy.dot() result different with classic computation for large-size arrays geekgeek 5 1,831 Jan-25-2022, 09:45 PM
Last Post: Gribouillis
  Two numpy arrays Sandra2312 1 1,777 Jan-18-2021, 06:10 PM
Last Post: paul18fr
  numpy in1d with two simple arrays claw91 3 2,527 Sep-21-2020, 12:43 PM
Last Post: scidam
  filling and printing numpy arrays of str pjfarley3 4 3,209 Jun-07-2020, 09:09 PM
Last Post: pjfarley3
  Type hinting - return type based on parameter micseydel 2 2,428 Jan-14-2020, 01:20 AM
Last Post: micseydel
  How to concatenate nested numpy arrays? python_newbie09 2 4,733 Apr-16-2019, 07:00 PM
Last Post: python_newbie09
  Variant type object arrays anbra 3 4,939 Jul-29-2018, 09:25 PM
Last Post: anbra

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020