Here is a comprehensive guide to NumPy and Pandas as per your request, divided into sections for ease of understanding:
NumPy
1. Load NumPy
- Importing NumPy: To start working with NumPy, first, you need to import it. If you haven't installed NumPy, you can do so using pip (
pip install numpy).
import numpy as np
2. Constructing Arrays
- Basic Array Construction:
# From a list
array = np.array([1, 2, 3, 4, 5])
print(array)
# With a specified data type
array_float = np.array([1, 2, 3], dtype=float)
print(array_float)
# Using numpy functions
array_zeros = np.zeros(5)
array_ones = np.ones(5)
array_range = np.arange(1, 6)
print("Zeros:", array_zeros)
print("Ones:", array_ones)
print("Range:", array_range)
3. Pointwise Scalar Operations
array = np.array([1, 2, 3, 4, 5])
print("Original Array:", array)
# Addition
array_add = array + 2
print("After Adding 2:", array_add)
# Subtraction
array_subtract = array - 1
print("After Subtracting 1:", array_subtract)
# Multiplication
array_multiply = array * 3
print("After Multiplying by 3:", array_multiply)
# Division
array_divide = array / 2
print("After Dividing by 2:", array_divide)
4. Indexing and Slicing
- Accessing Parts of the Array:
array = np.array([1, 2, 3, 4, 5])
# Indexing
print("First Element:", array[0])
print("Last Element:", array[-1])
# Slicing
print("First to Third Element:", array[0:3])
print("From Second to End:", array[1:])
print("From Start to Second Last:", array[:-1])
5. Iterating over Elements
- Looping Through the Array:
array = np.array([1, 2, 3, 4, 5])
for element in array:
print(element)
6. Arrays and Types
- Understanding Data Types in NumPy:
array_int = np.array([1, 2, 3], dtype=int)
array_float = np.array([1, 2, 3], dtype=float)
print("Int Array:", array_int, "Type:", array_int.dtype)
print("Float Array:", array_float, "Type:", array_float.dtype)
7. Stacking Arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# Vertical Stack
vertical_stack = np.vstack((array1, array2))
print("Vertical Stack:\n", vertical_stack)
# Horizontal Stack
horizontal_stack = np.hstack((array1, array2))
print("Horizontal Stack:", horizontal_stack)
8. Splitting Arrays
array = np.array([1, 2, 3, 4, 5, 6])
# Split into two parts
split_array = np.split(array, 2)
print("Split Array:", split_array)
9. Copy and View
- Understanding Copies and Views:
original_array = np.array([1, 2, 3])
# View
view_array = original_array.view()
view_array[0] = 10
print("Original after view modification:", original_array)
# Copy
copy_array = original_array.copy()
copy_array[0] = 20
print("Original after copy modification:", original_array)
10. Reshaping Arrays
array = np.array([1, 2, 3, 4, 5, 6])
# Reshape to a 2x3 array
reshaped_array = array.reshape(2, 3)
print("Reshaped Array:\n", reshaped_array)
11. Matrix Operations
- Basic Matrix Multiplication:
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result = np.matmul(matrix1, matrix2)
print("Matrix Multiplication Result:\n", result)
Matrix operations are fundamental in linear algebra and are used extensively in data analysis, machine learning, and scientific computing. Matrix multiplication, in particular, is a key operation that combines two matrices to produce another matrix. The number of columns in the first matrix must equal the number of rows in the second matrix for the multiplication to be valid. The result is a new matrix where each element is computed as the dot product of rows from the first matrix and columns from the second.
Pandas
1. Load Pandas
import pandas as pd
2. Create a Series
series = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
print(series)
3. Convert a Dictionary to a Series
dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
series_from_dict = pd.Series(dictionary)
print(series_from_dict)
4. Creating an Index
index = pd.Index(['a', 'b', 'c', 'd', 'e'])
print(index)
5. Accessing Elements
series = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
print("Element at 'c':", series['c'])
6. Data Frames
- Basic DataFrame Creation:
data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 24, 35, 32],
'Country': ['USA', 'UK', 'Australia', 'Germany']}
df = pd.DataFrame(data)
print(df)
7. Add a Column, Add Row Indices, Convert One of the Columns into an Index
df = pd.DataFrame({
'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 24, 35, 32]
})
# Add a column
df['Country'] = ['USA', 'UK', 'Australia', 'Germany']
print("After adding column:\n", df)
# Add row indices (default integer index is always present)
print("Default Index:\n", df)
# Convert one of the columns into an index
df_set_name_index = df.set_index('Name')
print("After setting 'Name' as index:\n", df_set_name_index)
8. Recode an Index, Use Multiple Columns for Indexing
df = pd.DataFrame({
'ID': [1, 2, 3, 4],
'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 24, 35, 32]
})
# Recode an index (here, renaming for clarity)
df_renamed = df.rename(columns={'ID': 'User_ID'})
print("After renaming 'ID' to 'User_ID':\n", df_renamed)
# Use multiple columns for indexing (MultiIndex)
df_multi_index = df.set_index(['Name', 'Age'])
print("With MultiIndex:\n", df_multi_index)
9. Accessing Values in a DataFrame
- By Column Index, By Row Index, Individual Element by Position:
df = pd.DataFrame({
'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 24, 35, 32]
}, index=['a', 'b', 'c', 'd'])
# By Column Index
print("Age Column:\n", df['Age'])
# By Row Index
print("Row 'b':\n", df.loc['b'])
# Individual Element by Position (iloc for position, not label)
print("Element at Row 1, Column 1 (0-indexed):", df.iloc[1, 1])
10. Reading CSV Files
df = pd.read_csv('yourfile.csv')
print(df)
11. Filtering Data
df = pd.DataFrame({
'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 24, 35, 32]
})
# Filtering
filtered_df = df[df['Age'] > 30]
print("People older than