1 Introduction To Numpy

Introduction to Numpy

Numpy is a tool/library we use for data calculation.

How to install numpy

You can go to your terminal and write:

pip install numpy

Import Numpy

If you have installed it and you want to use it, you must import it.

import numpy as np  # np is a short name that we give to numpy

Let's take an example

score = [20, 50, 30, 70, 10]
score

Output:

[20, 50, 30, 70, 10]

divide each score with 100

Error:

Note: Mathematical operations are not possible on a Python list.

Error:

Error:

List is not made for mathematical operations. Lists are mainly made to store values.

List to array Conversion

Because lists are not made for mathematical operations, if you want to do mathematical operations you need to convert the list into a Numpy array.

What is Array?

Array is Numpy's list. An array is like a list but it can perform mathematical operations.

How to convert list into array?

We have the np.array function in numpy to convert a list into an array.

Output:

Now you can perform mathematical / element-wise operations:

Output:

Output:

Output:

Properties of Numpy Array:

  1. A Python list can have multiple data types, for example: [1, 2, 3, 'abhi']

  2. A Numpy array has a single data type: [1, 2, 3], [1.0, 2.0, 3.0], or ['1', '2', '3']

int and float

When you have a list of ints and floats, the final array is always float (to avoid data loss).

Output:

int and string

When you have a list of ints and strings, the final array will be of string dtype.

Output:

Output:

float and string and int

Output:

you can forcibly change the data type of array values

You can forcibly change the data type of array values by using the dtype parameter.

Output:

Output:

Output:

limitation

Error:

Last updated