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]:
In [3]:
# Create a numpy array with evenly spaced values
arr = np.arange(start=0, stop=10, step=2)
arr
Out[3]:
In [4]:
# Create a 1D array with 6 random values between 0 and 1
arr = np.random.rand(6)
arr
Out[4]:
NumPy Array Operations¶
In [5]:
arr[0] # Accesses the element at index 0
Out[5]:
In [6]:
arr[1:4] # Accesses a slice of elements from index 1 to 3 (exclusive)
Out[6]:
In [7]:
arr.shape # Returns the shape of the array (dimensions)
Out[7]:
In [8]:
arr.size # Returns the total number of elements in the array
Out[8]:
In [9]:
np.mean(arr) # Computes the mean of the array
Out[9]:
In [10]:
np.max(arr) # Finds the maximum value in the array
Out[10]:
In [11]:
np.sum(arr) # Computes the sum of all elements in the array
Out[11]:
In [12]:
# Reshaping
arr.reshape((2, 3)) # Reshapes the array into a 2x3 matrix
Out[12]:
In [13]:
# Broadcasting
arr = arr + 5 # Adds 5 to each element of the array
arr
Out[13]:
Array manipulation¶
In [14]:
arr.T # Returns the transpose of the array
arr
Out[14]:
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]:
In [16]:
# Splitting
np.split(arr, 2) # Splits the array into two equal parts
Out[16]:
In [17]:
# Extract a slice form the array
arr[1:3]
Out[17]:
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)
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]:
In [20]:
std = np.std(data) # Computes the standard deviation of the data
std
Out[20]:
Creating Multidimensional Arrays¶
In [21]:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
In [22]:
zeros_arr = np.zeros((3, 4)) # Creates a 3x4 array filled with zeros
zeros_arr
Out[22]:
In [23]:
ones_arr = np.ones((2, 3)) # Creates a 2x3 array filled with ones
ones_arr
Out[23]:
In [24]:
identity_mat = np.eye(3) # Creates a 3x3 identity matrix
identity_mat
Out[24]:
In [25]:
random_arr = np.random.rand(2, 2) # Creates a 2x2 array with random values between 0 and 1
random_arr
Out[25]:
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()
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()
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()
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()
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()
In [ ]: