Numpy_examples_with_plots.ipynb Open in SWAN Download

Numpy examples with plots

NumPy is a foundation package for scientific computing.

In [1]:
import numpy as np

Creating NumPy Arrays

In [2]:
# Create a numpy array from a Python list

my_list = [1, 2, 3, 4, 5]
arr = np.array(my_list)
arr
Out[2]:
array([1, 2, 3, 4, 5])
In [3]:
# Create a numpy array with evenly spaced values

arr = np.arange(start=0, stop=10, step=2)  
arr
Out[3]:
array([0, 2, 4, 6, 8])
In [4]:
# Create a 1D array with 6 random values between 0 and 1

arr = np.random.rand(6)  
arr
Out[4]:
array([0.31334374, 0.84585485, 0.30977214, 0.70435732, 0.68546196,
       0.81527989])

NumPy Array Operations

In [5]:
arr[0]  # Accesses the element at index 0
Out[5]:
0.3133437374403655
In [6]:
arr[1:4]  # Accesses a slice of elements from index 1 to 3 (exclusive)
Out[6]:
array([0.84585485, 0.30977214, 0.70435732])
In [7]:
arr.shape  # Returns the shape of the array (dimensions)
Out[7]:
(6,)
In [8]:
arr.size  # Returns the total number of elements in the array
Out[8]:
6
In [9]:
np.mean(arr)  # Computes the mean of the array
Out[9]:
0.6123449836881373
In [10]:
np.max(arr)  # Finds the maximum value in the array
Out[10]:
0.8458548489635508
In [11]:
np.sum(arr)  # Computes the sum of all elements in the array
Out[11]:
3.6740699021288235
In [12]:
# Reshaping
arr.reshape((2, 3))  # Reshapes the array into a 2x3 matrix
Out[12]:
array([[0.31334374, 0.84585485, 0.30977214],
       [0.70435732, 0.68546196, 0.81527989]])
In [13]:
# Broadcasting
arr = arr + 5  # Adds 5 to each element of the array
arr
Out[13]:
array([5.31334374, 5.84585485, 5.30977214, 5.70435732, 5.68546196,
       5.81527989])

Array manipulation

In [14]:
arr.T  # Returns the transpose of the array
arr
Out[14]:
array([5.31334374, 5.84585485, 5.30977214, 5.70435732, 5.68546196,
       5.81527989])
In [15]:
# Concatenation
arr1 = np.arange(start=0, stop=10, step=2)  

arr_new = np.concatenate((arr, arr1))  # Concatenates two arrays along a specified axis

arr_new
Out[15]:
array([5.31334374, 5.84585485, 5.30977214, 5.70435732, 5.68546196,
       5.81527989, 0.        , 2.        , 4.        , 6.        ,
       8.        ])
In [16]:
# Splitting
np.split(arr, 2)  # Splits the array into two equal parts
Out[16]:
[array([5.31334374, 5.84585485, 5.30977214]),
 array([5.70435732, 5.68546196, 5.81527989])]
In [17]:
# Extract a slice form the array
arr[1:3]
Out[17]:
array([5.84585485, 5.30977214])
In [18]:
# Sum of 2 arrays

arr1 = np.array([1, 2, 3])
arr2 = np.array([10, 20, 30])
result = arr1 + arr2  # Adds the arrays element-wise
print(result)
[11 22 33]

NumPy and Statistics

In [19]:
data = np.array([10, 15, 20, 25, 30])

mean = np.mean(data)  # Computes the mean of the data
mean
Out[19]:
20.0
In [20]:
std = np.std(data)  # Computes the standard deviation of the data
std
Out[20]:
7.0710678118654755

Creating Multidimensional Arrays

In [21]:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
[[1 2 3]
 [4 5 6]]
In [22]:
zeros_arr = np.zeros((3, 4))  # Creates a 3x4 array filled with zeros
zeros_arr
Out[22]:
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])
In [23]:
ones_arr = np.ones((2, 3))  # Creates a 2x3 array filled with ones
ones_arr
Out[23]:
array([[1., 1., 1.],
       [1., 1., 1.]])
In [24]:
identity_mat = np.eye(3)  # Creates a 3x3 identity matrix
identity_mat
Out[24]:
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
In [25]:
random_arr = np.random.rand(2, 2)  # Creates a 2x2 array with random values between 0 and 1
random_arr
Out[25]:
array([[0.17128251, 0.01012276],
       [0.50822073, 0.90303273]])

Plots and visualization

Line Plot

In [31]:
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams.update({'font.size': 20, 'figure.figsize': [14,10]})

# Generate data
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

# Create a line plot
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sine Wave')
plt.show()
No description has been provided for this image

Scatter Plot

In [32]:
import numpy as np
import matplotlib.pyplot as plt

# Generate random data
x = np.random.rand(100)
y = np.random.rand(100)
colors = np.random.rand(100)
sizes = 100 * np.random.rand(100)

# Create a scatter plot
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Scatter Plot')
plt.colorbar()
plt.show()
No description has been provided for this image

Histogram

In [33]:
import numpy as np
import matplotlib.pyplot as plt

# Generate random data
data = np.random.randn(1000)

# Create a histogram
plt.hist(data, bins=30, alpha=0.7)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()
No description has been provided for this image

Bar Plot

In [34]:
import numpy as np
import matplotlib.pyplot as plt

# Generate data
labels = ['A', 'B', 'C', 'D']
values = [10, 15, 7, 12]

# Create a bar plot
plt.bar(labels, values)
plt.xlabel('Category')
plt.ylabel('Value')
plt.title('Bar Plot')
plt.show()
No description has been provided for this image

Heatmap

In [35]:
import numpy as np
import matplotlib.pyplot as plt

# Generate random data
data = np.random.rand(10, 10)

# Create a heatmap
plt.imshow(data, cmap='hot')
plt.colorbar()
plt.title('Heatmap')
plt.show()
No description has been provided for this image
In [ ]: