How to identify numpy types in python?

前端 未结 6 768
生来不讨喜
生来不讨喜 2020-12-23 09:02

How can one reliably determine if an object has a numpy type?

I realize that this question goes against the philosophy of duck typing, but idea is to make sure a fun

6条回答
  •  一向
    一向 (楼主)
    2020-12-23 09:36

    Old question but I came up with a definitive answer with an example. Can't hurt to keep questions fresh as I had this same problem and didn't find a clear answer. The key is to make sure you have numpy imported, and then run the isinstance bool. While this may seem simple, if you are doing some computations across different data types, this small check can serve as a quick test before your start some numpy vectorized operation.

    ##################
    # important part!
    ##################
    
    import numpy as np
    
    ####################
    # toy array for demo
    ####################
    
    arr = np.asarray(range(1,100,2))
    
    ########################
    # The instance check
    ######################## 
    
    isinstance(arr,np.ndarray)
    

提交回复
热议问题