Python Basics
Learn how to declare variables, work with strings, and perform basic arithmetic operations in Python.
# Variable Assignment
x = 5
y = "Hello, Python!"
print(x, y)
# Basic Arithmetic
a = 10
b = 2
print(a + b) # 12
# Math Operations on Variables
x = 5
print(x) # 5
x + 2 # 7
x - 2 # 3
x * 2 # 10
x ** 2 # 25
x % 2 # 1
x / float(2) # 2.5
# String Operations
my_string = "Python is awesome!"
print(my_string.upper()) # "PYTHON IS AWESOME!"
print(my_string.lower()) # "python is awesome!"
print(my_string.count('o')) # 2
print(my_string.replace('o', 'e')) # "Pythen is awesome!"
# Lists in Python
a = "is"
b = "nice"
my_list = ["my", "list", a, b]
my_list2 = [[4, 5, 6, 7], [3, 4, 5, 6]]
# Subset
print(my_list[1]) # "list"
print(my_list[-3]) # "list"
# Slice
print(my_list[1:3]) # ["list", "is"]
print(my_list[:3]) # ["my", "list", "is"]
# List Methods
my_list.append('!')
my_list.remove('!')
my_list.reverse()
my_list.sort()
# Import libraries
import numpy as np
from math import pi
# Accessing Help
help(str)
# Conditional Statements
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
# Loops in Python
# For Loop
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# While Loop
count = 0
while count < 5:
print(count)
count += 1
NumPy Basics
Learn how to create arrays and perform array operations with NumPy.
import numpy as np
# Creating an array
my_array = np.array([1, 2, 3, 4])
print(my_array)
# Array operations
print(my_array * 2)
import numpy as np
# Creating arrays
my_array = np.array([1, 2, 3, 4])
print(my_array)
# Creating multi-dimensional arrays
my_2d_array = np.array([[1, 2, 3], [4, 5, 6]])
print(my_2d_array)
# Arrays with specific values
zeros_array = np.zeros((3, 4)) # Array of zeros
ones_array = np.ones((2, 3)) # Array of ones
empty_array = np.empty((2, 2)) # Empty array
print(zeros_array, ones_array, empty_array)
# Creating evenly spaced arrays
linear_array = np.linspace(0, 10, 5) # Evenly spaced values
step_array = np.arange(0, 10, 2) # Values with a step
print(linear_array, step_array)
# Basic operations
my_array = np.array([1, 2, 3, 4])
print(my_array + 5) # Add scalar
print(my_array * 2) # Multiply scalar
print(my_array ** 2) # Element-wise exponentiation
# Element-wise operations with another array
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
print(array1 + array2)
print(array1 * array2)
print(array1 / array2)
# Statistical operations
my_array = np.array([1, 2, 3, 4, 5])
print(np.mean(my_array)) # Mean
print(np.median(my_array)) # Median
print(np.std(my_array)) # Standard deviation
print(np.sum(my_array)) # Sum
print(np.min(my_array)) # Minimum
print(np.max(my_array)) # Maximum
# Indexing and slicing
my_array = np.array([10, 20, 30, 40, 50])
print(my_array[0]) # First element
print(my_array[-1]) # Last element
print(my_array[1:4]) # Slice from index 1 to 3
# Indexing multi-dimensional arrays
my_2d_array = np.array([[1, 2, 3], [4, 5, 6]])
print(my_2d_array[0, 1]) # Access element at row 0, column 1
print(my_2d_array[:, 1]) # Access all rows in column 1
# Boolean masking
my_array = np.array([10, 20, 30, 40, 50])
mask = my_array > 30
print(my_array[mask]) # Elements greater than 30
# Fancy indexing
indices = [0, 2, 4]
print(my_array[indices]) # Access specific indices
# Reshaping arrays
my_array = np.array([1, 2, 3, 4, 5, 6])
reshaped_array = my_array.reshape((2, 3))
print(reshaped_array)
# Transposing arrays
my_2d_array = np.array([[1, 2], [3, 4], [5, 6]])
transposed = my_2d_array.T
print(transposed)
# Broadcasting example
array1 = np.array([1, 2, 3])
array2 = np.array([[10], [20], [30]])
result = array1 + array2
print(result)
# Matrix multiplication
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result = np.dot(matrix1, matrix2) # Dot product
print(result)
# Element-wise multiplication
result = matrix1 * matrix2
print(result)
# Random numbers
random_array = np.random.rand(3, 3) # Uniformly distributed
normal_array = np.random.randn(3, 3) # Normally distributed
print(random_array, normal_array)
Pandas Library
Learn how to variables, work with strings, and perform basic arithmetic operations in Python.
import pandas as pd
# Creating a Series
data = [1, 2, 3, 4, 5]
series = pd.Series(data, index=['a', 'b', 'c', 'd', 'e'])
print(series)
# Creating a DataFrame
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"City": ["New York", "Los Angeles", "Chicago"]
}
df = pd.DataFrame(data)
print(df)
# Reading CSV
df = pd.read_csv("data.csv")
# Writing to CSV
df.to_csv("output.csv", index=False)
# Reading Excel
df = pd.read_excel("data.xlsx")
# Writing to Excel
df.to_excel("output.xlsx", index=False)
# Reading from a SQL Database
from sqlalchemy import create_engine
engine = create_engine("sqlite:///:memory:")
df = pd.read_sql("SELECT * FROM table_name", engine)
# Writing to a SQL Database
df.to_sql("table_name", engine, index=False)
# Exploring DataFrame
print(df.head()) # First 5 rows
print(df.tail()) # Last 5 rows
print(df.info()) # Summary of the DataFrame
print(df.describe()) # Statistics of numerical columns
print(df.shape) # Dimensions of the DataFrame
print(df.columns) # Column names
print(df.index) # Row indices
# Selecting columns
print(df["Name"]) # Single column
print(df[["Name", "Age"]]) # Multiple columns
# Filtering rows
filtered_df = df[df["Age"] > 30]
print(filtered_df)
# Selecting specific rows and columns
print(df.loc[1, "Name"]) # By label
print(df.iloc[1, 0]) # By position
# Conditional filtering
print(df[(df["Age"] > 25) & (df["City"] == "Chicago")])
# Adding a new column
df["Salary"] = [50000, 60000, 70000]
# Removing a column
df = df.drop("City", axis=1)
# Adding a new row
new_row = {"Name": "David", "Age": 28, "City": "Boston"}
df = df.append(new_row, ignore_index=True)
# Removing a row
df = df.drop(1, axis=0)
# Checking for missing values
print(df.isnull())
# Filling missing values
df["Age"].fillna(30, inplace=True)
# Dropping rows or columns with missing values
df = df.dropna() # Drop rows
df = df.dropna(axis=1) # Drop columns
# Sorting
sorted_df = df.sort_values("Age", ascending=False)
print(sorted_df)
# Ranking
df["Rank"] = df["Age"].rank()
print(df)
# Grouping data
grouped = df.groupby("City")
print(grouped["Age"].mean()) # Average age by city
# Aggregating data
aggregated = df.groupby("City").agg({"Age": ["mean", "max"], "Salary": "sum"})
print(aggregated)
# Merging
df1 = pd.DataFrame({"ID": [1, 2], "Name": ["Alice", "Bob"]})
df2 = pd.DataFrame({"ID": [1, 2], "Age": [25, 30]})
merged_df = pd.merge(df1, df2, on="ID")
print(merged_df)
# Concatenating
df1 = pd.DataFrame({"Name": ["Alice", "Bob"]})
df2 = pd.DataFrame({"Name": ["Charlie", "David"]})
concatenated_df = pd.concat([df1, df2], ignore_index=True)
print(concatenated_df)
# Joining
left = pd.DataFrame({"Name": ["Alice", "Bob"], "Age": [25, 30]})
right = pd.DataFrame({"Name": ["Alice", "Bob"], "Salary": [50000, 60000]})
joined_df = left.join(right.set_index("Name"), on="Name")
print(joined_df)
# Creating a pivot table
pivot = df.pivot_table(values="Salary", index="City", columns="Age", aggfunc="mean")
print(pivot)
# Creating a datetime index
df["Date"] = pd.to_datetime(df["Date"])
df.set_index("Date", inplace=True)
# Resampling
monthly_data = df.resample("M").mean()
print(monthly_data)
# Time-based filtering
filtered_data = df["2024-01":"2024-03"]
print(filtered_data)
# Applying custom functions
df["Age Category"] = df["Age"].apply(lambda x: "Young" if x < 30 else "Old")
# Applying element-wise functions
df["Salary"] = df["Salary"].applymap(lambda x: x * 1.1)
MatPlotLib Library
Learn how to variables, work with strings, and perform basic arithmetic operations in Python.
import matplotlib.pyplot as plt
# Basic Line Plot
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.title("Basic Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
# Customizing Line Styles, Colors, and Markers
plt.plot(x, y, color='red', linestyle='--', marker='o', linewidth=2)
plt.title("Customized Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
# Creating Multiple Subplots
fig, axs = plt.subplots(2, 2, figsize=(8, 6))
axs[0, 0].plot(x, y, color='blue')
axs[0, 0].set_title("Top Left")
axs[0, 1].scatter(x, y, color='green')
axs[0, 1].set_title("Top Right")
axs[1, 0].bar(x, y, color='purple')
axs[1, 0].set_title("Bottom Left")
axs[1, 1].hist(y, bins=5, color='orange')
axs[1, 1].set_title("Bottom Right")
plt.tight_layout()
plt.show()
# Adding Legends and Annotations
plt.plot(x, y, label="Line 1", color='red')
plt.scatter([2, 3], [20, 25], label="Special Points", color='blue')
# Add annotations
plt.annotate("Peak", xy=(4, 30), xytext=(3, 25),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.title("Legend and Annotations")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.show()
# Using Styles
plt.style.use('ggplot')
x = range(10)
y = [i ** 2 for i in x]
plt.plot(x, y)
plt.title("Styled Plot with ggplot")
plt.show()
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# 3D Plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
ax.plot_surface(X, Y, Z, cmap='viridis')
plt.title("3D Surface Plot")
plt.show()
# Colormap Example
data = np.random.rand(10, 10)
plt.imshow(data, cmap='plasma', interpolation='nearest')
plt.colorbar()
plt.title("Colormap Example")
plt.show()
# Interactive Plot Example
plt.ion()
for i in range(1, 6):
y = [j * i for j in x]
plt.plot(x, y)
plt.title(f"Interactive Update {i}")
plt.pause(0.5)
plt.ioff()
plt.show()
# Save Plot as Image
plt.plot(x, y)
plt.title("Save Plot Example")
plt.savefig("plot.png", dpi=300, transparent=True)
plt.show()
# Adjust Layout
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
for i, ax in enumerate(axs.flat):
ax.plot(x, [xi * (i + 1) for xi in x])
ax.set_title(f"Plot {i+1}")
plt.tight_layout()
plt.show()
# Object-Oriented Customization
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(x, y, label='y = x^2', color='purple', linewidth=2)
# Adding gridlines and spines
ax.grid(True)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# Axis labels and title
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_title("Advanced Customization with OO API")
ax.legend()
plt.show()
# Object-Oriented Customization
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(x, y, label='y = x^2', color='purple', linewidth=2)
# Adding gridlines and spines
ax.grid(True)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# Axis labels and title
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_title("Advanced Customization with OO API")
ax.legend()
plt.show()
# Histogram
data = np.random.randn(1000)
plt.hist(data, bins=30, color='green', alpha=0.7)
plt.title("Histogram Example")
plt.show()
# Boxplot
data = [np.random.rand(50), np.random.rand(50)]
plt.boxplot(data)
plt.title("Boxplot Example")
plt.show()