📜  numpy isinstance - Python (1)

📅  最后修改于: 2023-12-03 15:03:18.535000             🧑  作者: Mango

Numpy isinstance() in Python

isinstance() is a built-in Python function that checks if an object is an instance of a particular class or any subclass of that class. In the case of NumPy, we can use isinstance() to check if an array or a scalar is a NumPy array or not.

Syntax
isinstance(object, classinfo)
Parameters
  • object: The object that you want to check the class of.
  • classinfo: A class or a tuple of classes that you want to check the object against.
Returns

isinstance() returns True if the object is an instance of the given class or any subclass of that class. Otherwise, it returns False.

Example 1: Checking if a NumPy array is a NumPy array
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

if isinstance(arr, np.ndarray):
    print("This is a NumPy array")
else:
    print("This is not a NumPy array")

Output:

This is a NumPy array

In this example, we import NumPy and create an array called arr. We then check if arr is an instance of the np.ndarray class using isinstance(). Since arr is a NumPy array, the output will be "This is a NumPy array".

Example 2: Checking if a scalar is a NumPy array
import numpy as np

x = 10

if isinstance(x, np.ndarray):
    print("This is a NumPy array")
else:
    print("This is not a NumPy array")

Output:

This is not a NumPy array

In this example, we create a scalar called x. We then check if x is an instance of the np.ndarray class using isinstance(). Since x is not a NumPy array, the output will be "This is not a NumPy array".

Example 3: Checking if an object is either a NumPy array or a list
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
list1 = [1, 2, 3, 4, 5]

if isinstance(arr, (np.ndarray, list)):
    print("This is either a NumPy array or a list")
else:
    print("This is not a NumPy array or a list")
    
if isinstance(list1, (np.ndarray, list)):
    print("This is either a NumPy array or a list")
else:
    print("This is not a NumPy array or a list")

Output:

This is either a NumPy array or a list
This is either a NumPy array or a list

In this example, we create a NumPy array called arr and a list called list1. We then check if each object is either a NumPy array or a list using isinstance() with a tuple of classes as the second argument. Since arr and list1 are either NumPy arrays or lists, the output will be "This is either a NumPy array or a list" for both objects.