INTERNET

# 12 NumPy Operations for Beginners NumPy, which stands for Numerical Python, is a Python library primarily used for working with arrays and to perform a wide variety of mathematical operations on them. It's the core library for scientific computing in Python. NumPy is often used with other Python libraries related to data science such as SciPy, Pandas, and Matplotlib.

In this article, you'll learn how to perform 12 basic operations using NumPy.

## Using These NumPy Examples

You can run the examples in this article by entering the code directly into the python interpreter. Launch it in interactive mode, from the command line, to do so.

You can also access a Python Notebook file containing the complete source code from this GitHub repository.

## 1. How to Import NumPy as np and Print the Version Number

You need to use the import keyword to import any library in Python. NumPy is typically imported under the np alias. With this approach, you can refer to the NumPy package as np instead of numpy.

``import numpy as npprint(np.__version__)``

Output:

``1.20.1``

## 2. How to Create a NumPy ndarray Object

The array object in NumPy is called ndarray. You can create the NumPy ndarray object using the array() method. The array() method accepts a list, tuple, or an array-like object.

### Using a Tuple to Create a NumPy Array

``arrObj = np.array((23, 32, 65, 85))arrObj``

Output:

``array([23, 32, 65, 85])``

### Using a List to Create a NumPy Array

``arrObj = np.array([43, 23, 75, 15])arrObj``

Output:

``array([43, 23, 75, 15])``

## 3. How to Create 0D, 1D, 2D, 3D, and N-Dimensional NumPy Arrays

### 0D Arrays

Each element of an array is a 0D array.

``arrObj = np.array(21)arrObj``

Output:

``array(21)``

### 1D Arrays

Arrays that have 0D arrays as their elements are called 1D arrays.

``arrObj = np.array([43, 23, 75, 15])arrObj``

Output:

``array([43, 23, 75, 15])``

### 2D Arrays

Arrays that have 1D arrays as their elements are called 2D arrays.

``arrObj = np.array([[12, 43, 21], [67, 32, 98]])arrObj``

Output:

``array([[12, 43, 21],       [67, 32, 98]])``

### 3D Arrays

Arrays that have 2D arrays (matrices) as their elements are called 3D arrays.

``arrObj = np.array([[[23, 45, 22], [45, 76, 23]], [[67, 23, 56], [12, 76, 63]]])arrObj``

Output:

``array([[[23, 45, 22],        [45, 76, 23]],        [[67, 23, 56],        [12, 76, 63]]])``

### n-Dimensional Arrays

You can create an array of any dimension using the ndmin argument.

``arrObj = np.array([23, 22, 65, 44], ndmin=5)arrObj``

Output:

``array([[[[[23, 22, 65, 44]]]]])``

## 4. How to Check the Dimensions of an Array

You can find the dimensions of an array using the ndim attribute.

``arrObj1 = np.array(21)arrObj2 = np.array([43, 23, 75, 15])arrObj3 = np.array([[12, 43, 21], [67, 32, 98]])arrObj4 = np.array([[[23, 45, 22], [45, 76, 23]], [[67, 23, 56], [12, 76, 63]]])print(arrObj1.ndim)print(arrObj2.ndim)print(arrObj3.ndim)print(arrObj4.ndim)``

Output:

``0123``

## 5. How to Access the Elements of 1D, 2D, and 3D Arrays

You can access an array element using its index number. For 2D and 3D arrays, you need to use comma-separated integers representing the index of each dimension.

``arrObj1 = np.array([43, 23, 75, 15])arrObj2 = np.array([[12, 43, 21], [67, 32, 98]])arrObj3 = np.array([[[23, 45, 22], [45, 76, 23]], [[67, 23, 56], [12, 76, 63]]])print(arrObj1)print(arrObj2[0, 2])print(arrObj3[0, 1, 2])``

Output:

``752123``

Note: NumPy arrays also support negative indexing.

## 6. How to Check the Data Type of the NumPy Array Object

You can check the data type of the NumPy array object using the dtype property.

``arrObj1 = np.array([1, 2, 3, 4])arrObj2 = np.array([1.3, 6.8, 3.5, 9.2])arrObj3 = np.array(['Welcome', 'to', 'MUO'])print(arrObj1.dtype)print(arrObj2.dtype)print(arrObj3.dtype)``

Output:

``int32float64<U7``

Note:

NumPy uses the following characters to represent the built-in data types:

• i — integer (signed)
• b — boolean
• O — object
• S — string
• u — unsigned integer
• f — float
• c — complex float
• m — timedelta
• M — datetime
• U — unicode string
• V — raw data (void)

## 7. How to Change the Data Type of a NumPy Array

You can change the data type of a NumPy array using the astype(data_type) method. This method accepts the data type as a parameter and creates a new copy of the array. You can specify the data type using characters like 'b' for boolean, 'i' for integer, 'f' for float, etc.

### Converting an Integer Array to a Float Array

``arrObj = np.array([43, 23, 75, 15])floatArr = arrObj.astype('f')floatArr``

Output:

``array([43., 23., 75., 15.], dtype=float32)``

### Converting a Float Array to an Integer Array

``arrObj = np.array([1.3, 6.8, 3.5, 9.2])intArr = arrObj.astype('i')intArr``

Output:

``array([1, 6, 3, 9], dtype=int32)``

## 8. How to Copy a NumPy Array Into Another Array

You can copy a NumPy array into another array using the np.copy() function. This function returns an array copy of the given object.

``oldArr = np.array([43, 23, 75, 15])newArr = np.copy(oldArr)newArr``

Output:

``array([43, 23, 75, 15])``

## 9. How to Find the Shape of a NumPy Array

The shape of an array refers to the number of elements in each dimension. You can find the shape of an array using the shape attribute. It returns a tuple whose elements give the lengths of the corresponding array dimensions.

``arrObj = np.array([[12, 43, 21], [67, 32, 98]])arrObj.shape``

Output:

``(2, 3)``

## 10. How to Reshape a NumPy Array

Reshaping an array means changing its shape. Note that you cannot reshape an array to an arbitrary shape. The number of elements required for reshaping must be the same in both shapes.

``arrObj = np.array([43, 23, 75, 15, 34, 45])reshapedArr = arrObj.reshape(2, 3)reshapedArr``

Output:

``array([[43, 23, 75],      [15, 34, 45]])``

In the above example, a 1D array is reshaped to a 2D array.

## 11. How to Flatten a NumPy Array

Flattening an array means converting a multidimensional array into a 1D array. You can flatten an array using reshape(-1).

``arrObj = np.array([[12, 43, 21], [67, 32, 98]])flattenedArr = arrObj.reshape(-1)flattenedArr``

Output:

``array([12, 43, 21, 67, 32, 98])``

Note: You can also flatten an array using other methods like numpy.ndarray.flatten() and numpy.ravel().

## 12. How to Sort a NumPy Array

You can sort a NumPy array using the numpy.sort() function.

### Sorting 1D Array of Integers

``arrObj = np.array([43, 23, 75, 15])np.sort(arrObj)``

Output:

``array([15, 23, 43, 75])``

### Sorting 1D Array of Strings

``arrObj = np.array(["Python", "JavaScript", "Solidity", "Golang"])np.sort(arrObj)``

Output:

``array(['Golang', 'JavaScript', 'Python', 'Solidity'], dtype='<U10')``

### Sorting 2D Array of Integers

``arrObj = np.array([[12, 43, 21], [67, 32, 98]])np.sort(arrObj)``

Output:

``array([[12, 21, 43], [32, 67, 98]])``

## Make Your Code Robust Using Built-In Methods and Functions

Python is one of the most popular programming languages. It's used in various domains like web development, scientific and numeric applications, software development, and game development. It's always good to know about built-in methods and functions in Python. They can shorten your code and increase its efficiency. Previous article

Next article

INTERNET

INTERNET

INTERNET

INTERNET

INTERNET

INTERNET