Mathematical Concepts Using Python Lab
Python Libraries:
(i) NumPy: N-dimensional array, Random numbers, Matrix operations.
(ii) Pandas: Data Frame, read write csv file, Filtering, Slicing.
(iii) Matplotlib: Format strings in plot, Line plot, Scatter plot, Bar chart, Pie chart, Histograms.
**NumPy**
- **Explanation**: NumPy is a powerful library for numerical computing in Python. It provides
support for multi-dimensional arrays and various mathematical functions to work with these arrays
efficiently.
- **Commands/Functions**:
- Creating Arrays:
- `numpy.array()`: Create an array from a Python list or tuple.
- `numpy.zeros()`: Create an array filled with zeros.
- `numpy.ones()`: Create an array filled with ones.
- Array Operations:
- `numpy.shape()`: Get the shape of an array.
- `numpy.reshape()`: Reshape an array.
- `numpy.transpose()`: Transpose an array.
- Mathematical Functions:
- `numpy.add()`: Element-wise addition of arrays.
- `numpy.subtract()`: Element-wise subtraction of arrays.
- `numpy.multiply()`: Element-wise multiplication of arrays.
- `numpy.divide()`: Element-wise division of arrays.
- `numpy.dot()`: Dot product of two arrays.
- Random Numbers:
- `numpy.random.rand()`: Generate random numbers from a uniform distribution in [0, 1].
- `numpy.random.randn()`: Generate random numbers from a standard normal distribution.
**Pandas**
- **Explanation**: Pandas is a data manipulation library that provides data structures like
DataFrame to work with labeled and relational data easily.
- **Commands/Functions**:
- Creating DataFrames:
- `pandas.DataFrame()`: Create a DataFrame from a dictionary, list, or Numpy array.
- Data Manipulation:
- `DataFrame.head()`: Display the first few rows of a DataFrame.
- `DataFrame.tail()`: Display the last few rows of a DataFrame.
- `DataFrame.info()`: Get information about the DataFrame.
- `DataFrame.describe()`: Generate descriptive statistics of the DataFrame.
- Reading and Writing Data:
- `pandas.read_csv()`: Read data from a CSV file into a DataFrame.
- `DataFrame.to_csv()`: Write data from a DataFrame to a CSV file.
- Filtering and Slicing:
- `DataFrame.loc[]`: Access rows and columns using labels.
- `DataFrame.iloc[]`: Access rows and columns using integer positions.
**Matplotlib**
- **Explanation**: Matplotlib is a popular data visualization library in Python that helps create a
wide variety of plots and charts.
- **Commands/Functions**:
- Line Plot:
- `matplotlib.pyplot.plot()`: Create a line plot.
- `matplotlib.pyplot.xlabel()`: Set the label for the x-axis.
- `matplotlib.pyplot.ylabel()`: Set the label for the y-axis.
- Scatter Plot:
- `matplotlib.pyplot.scatter()`: Create a scatter plot.
- Bar Chart:
- `matplotlib.pyplot.bar()`: Create a bar chart.
- Pie Chart:
- `matplotlib.pyplot.pie()`: Create a pie chart.
- Histograms:
- `matplotlib.pyplot.hist()`: Create a histogram.
=====================
**Topic 1: NumPy**
Example 1: Creating and Operating on NumPy Arrays
```
Description: This example demonstrates how to create NumPy arrays and perform element-wise
addition and multiplication on them.
import numpy as np
# Creating NumPy arrays
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([5, 4, 3, 2, 1])
# Element-wise addition and multiplication
result_add = arr1 + arr2
result_multiply = arr1 * arr2
print("Array 1:", arr1)
print("Array 2:", arr2)
print("Addition Result:", result_add)
print("Multiplication Result:", result_multiply)
Example 2: Generating Random Numbers with NumPy
```python
```
Description: This example demonstrates how to create a Pandas DataFrame from a dictionary and
display the first few rows of the DataFrame using the `head()` function.
import numpy as np
# Generating an array of 5 random numbers between 0 and 1
random_array = np.random.rand(5)
print("Random Array:", random_array)
**Topic 2: Pandas**
Example 1: Creating and Manipulating DataFrames
```python
import pandas as pd
# Creating a DataFrame from a dictionary
data = {'Name': ['John', 'Jane', 'Mike', 'Emma'],
'Age': [25, 22, 30, 28],
'City': ['New York', 'London', 'Sydney', 'Toronto']}
df = pd.DataFrame(data)
# Displaying the first few rows of the DataFrame
print(df.head())
Example 2: Reading and Writing Data with Pandas
```python
```
Description: This example shows how to read data from a CSV file into a Pandas DataFrame using
`read_csv()` and how to write data from a DataFrame to a new CSV file using `to_csv()`.
import pandas as pd
# Reading data from a CSV file into a DataFrame
df = pd.read_csv('data.csv')
# Displaying information about the DataFrame
print(df.info())
# Writing data from a DataFrame to a new CSV file
df.to_csv('new_data.csv', index=False)
**Topic 3: Matplotlib**
Example 1: Line Plot
```python
```
Description: This example demonstrates how to create a simple line plot using Matplotlib to visualize
the relationship between X and Y values.
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [10, 7, 3, 8, 6]
# Creating a line plot
plt.plot(x, y, marker='o')
# Adding labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot Example')
# Display the plot
plt.show()
Example 2: Scatter Plot
```python
```
Description: This example shows how to create a scatter plot using Matplotlib to visualize the
individual data points and their distribution.
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [10, 7, 3, 8, 6]
# Creating a scatter plot
plt.scatter(x, y)
# Adding labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')
# Display the plot
plt.show()
=====================
**Case Study 1: N-dimensional Array Operations**
import numpy as np
# Case Study: N-dimensional Array Operations
# Creating a 3x3 matrix (2D array)
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Display the matrix
print("Original Matrix:")
print(matrix)
# Accessing elements in the matrix
element = matrix[1, 2]
print("Element at (1, 2):", element)
# Slicing rows and columns
row_slice = matrix[0, :]
column_slice = matrix[:, 1]
print("Row Slice:", row_slice)
print("Column Slice:", column_slice)
# Performing element-wise operations
addition_result = matrix + 2
multiplication_result = matrix * 3
print("Addition Result:")
print(addition_result)
print("Multiplication Result:")
print(multiplication_result)
# Reshaping the matrix
reshaped_matrix = matrix.reshape(9, 1)
print("Reshaped Matrix:")
print(reshaped_matrix)
```
**Case Study 2: Generating and Manipulating Random Numbers**
import numpy as np
# Generating random numbers between 0 and 1
random_numbers = np.random.rand(5)
print("Random Numbers:")
print(random_numbers)
# Generating random integers between a given range
random_integers = np.random.randint(1, 10, size=5)
print("Random Integers:")
print(random_integers)
# Calculating the mean and standard deviation
mean = np.mean(random_numbers)
std_deviation = np.std(random_numbers)
print("Mean:", mean)
print("Standard Deviation:", std_deviation)
# Sorting the random integers
sorted_integers = np.sort(random_integers)
print("Sorted Integers:")
print(sorted_integers)
```
**Case Study 3: Matrix Operations with NumPy**
import numpy as np
# Creating two matrices
matrix_a = np.array([[1, 2],
[3, 4]])
matrix_b = np.array([[5, 6],
[7, 8]])
# Matrix addition
addition_result = matrix_a + matrix_b
print("Matrix Addition Result:")
print(addition_result)
# Matrix subtraction
subtraction_result = matrix_a - matrix_b
print("Matrix Subtraction Result:")
print(subtraction_result)
# Matrix multiplication
multiplication_result = np.dot(matrix_a, matrix_b)
print("Matrix Multiplication Result:")
print(multiplication_result)
# Determinant of a matrix
determinant = np.linalg.det(matrix_a)
print("Determinant of Matrix A:", determinant)
# Inverse of a matrix
inverse_matrix_a = np.linalg.inv(matrix_a)
print("Inverse of Matrix A:")
print(inverse_matrix_a)
```
=====================
**Case Study 1: Working with Pandas DataFrames**
import pandas as pd
# Creating a DataFrame from a dictionary
data = {
'Name': ['John', 'Jane', 'Mike', 'Emma'],
'Age': [25, 22, 30, 28],
'City': ['New York', 'London', 'Sydney', 'Toronto']
}
df = pd.DataFrame(data)
# Display the DataFrame
print("Original DataFrame:")
print(df)
# Accessing specific columns
ages = df['Age']
print("Ages:")
print(ages)
# Adding a new column
df['Country'] = ['USA', 'UK', 'Australia', 'Canada']
print("DataFrame with New Column:")
print(df)
# Dropping a column
df.drop('Country', axis=1, inplace=True)
print("DataFrame after dropping 'Country' column:")
print(df)
```
**Case Study 2: Reading and Writing CSV Files with Pandas**
import pandas as pd
# Reading data from a CSV file into a DataFrame
df = pd.read_csv('data.csv')
# Display the first few rows of the DataFrame
print("Data from CSV File:")
print(df.head())
# Writing data from a DataFrame to a new CSV file
df.to_csv('new_data.csv', index=False)
print("DataFrame written to new_data.csv")
```
**Case Study 3: Filtering and Slicing Pandas DataFrames**
import pandas as pd
# Creating a DataFrame from a dictionary
data = {
'Name': ['John', 'Jane', 'Mike', 'Emma'],
'Age': [25, 22, 30, 28],
'City': ['New York', 'London', 'Sydney', 'Toronto']
}
df = pd.DataFrame(data)
# Filtering rows based on a condition
filtered_df = df[df['Age'] > 25]
print("Filtered DataFrame (Age > 25):")
print(filtered_df)
# Slicing rows and columns
sliced_df = df.loc[1:2, ['Name', 'City']]
print("Sliced DataFrame:")
print(sliced_df)
```
=====================
**Case Study 1: Line Plot and Scatter Plot**
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [10, 7, 3, 8, 6]
# Line Plot
plt.plot(x, y, marker='o', label='Line Plot')
# Scatter Plot
plt.scatter(x, y, color='red', label='Scatter Plot')
# Adding labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot and Scatter Plot Example')
# Adding legend
plt.legend()
# Display the plot
plt.show()
```
**Case Study 2: Bar Chart and Pie Chart**
import matplotlib.pyplot as plt
# Data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [25, 40, 30, 15]
# Bar Chart
plt.bar(categories, values, color='skyblue')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart Example')
# Display the plot
plt.show()
# Pie Chart
plt.pie(values, labels=categories, autopct='%1.1f%%', colors=['gold', 'lightgreen', 'lightcoral',
'lightskyblue'])
plt.title('Pie Chart Example')
# Display the plot
plt.show()
```
**Case Study 3: Histogram**
import matplotlib.pyplot as plt
import numpy as np
# Case Study: Histogram
# Generate random data
data = np.random.randn(1000)
# Histogram
plt.hist(data, bins=20, edgecolor='black')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram Example')
# Display the plot
plt.show()
```