Overview
This class introduced the foundational Python libraries for machine learning, focusing on NumPy and pandas. It covered the creation, manipulation, and basic operations of NumPy arrays, including indexing, slicing, and reshaping. The session then transitioned to pandas for data handling, demonstrating how to read data files and work with DataFrames. This lecture fits into the course as the essential data manipulation and preprocessing step before applying machine learning algorithms.
Learning outcomes
- Install and import NumPy and pandas.
- Create and manipulate NumPy arrays of various dimensions.
- Perform indexing, slicing, and reshaping on arrays.
- Concatenate, stack, and split arrays.
- Create pandas DataFrames and read data from CSV/JSON files.
- Use basic DataFrame methods like
head(),tail(),describe(), andloc.
Core concepts
NumPy and ndarray
Definition: NumPy (Numeric Python) is a library for efficient numerical computation. Its core object is the ndarray (N-dimensional array), which can be a scalar (0D), vector (1D), matrix (2D), or higher-dimensional array.
Why it matters: NumPy arrays are significantly faster (up to 50x) than Python lists for numerical operations due to contiguous memory storage and homogeneity. They form the backbone of numerical data structures in machine learning.
Connection: It is the primary data structure for feeding data into machine learning models in libraries like scikit-learn and TensorFlow.
Array Indexing and Slicing
Definition: Indexing accesses individual elements (starting at 0), while slicing extracts a subsequence using the syntax [start:stop:step].
Why it matters: Efficient data access and subsetting are crucial for data preparation, feature extraction, and batch processing in ML pipelines.
Connection: These operations are used to partition data into training and testing sets and to select specific features or samples.
Array Reshaping and Concatenation
Definition: Reshaping changes an array's dimensions without altering data. Concatenation joins arrays along a specified axis (0 for rows, 1 for columns). Why it matters: Machine learning models often require input data in specific shapes (e.g., a 2D matrix). These operations are essential for data wrangling and combining datasets. Connection: Used to prepare data batches and to combine features or samples from different sources.
pandas DataFrame
Definition: A pandas DataFrame is a 2D, tabular data structure with labeled rows and columns, similar to a spreadsheet or SQL table. Why it matters: It is the standard structure for data manipulation, cleaning, and exploration in Python, providing powerful tools for handling real-world, heterogeneous datasets. Connection: DataFrames are typically the starting point for any machine learning project, from which features are extracted and fed into models.
Data Ingestion (CSV/JSON)
Definition: Reading data from common file formats: CSV (Comma Separated Values) and JSON (JavaScript Object Notation).
Why it matters: Most real-world data is stored in these formats. Efficient ingestion is the first step in the ML workflow.
Connection: The pd.read_csv() and pd.read_json() functions load data directly into DataFrames for subsequent analysis and modeling.
Formulas and maths
np.array([1, 2, 3])
Symbols/Usage: Creates a NumPy array from a list. Used to initialize array data.
arr[0] or arr[0, 1]
Symbols/Usage: Indexing to access an element. arr is the array. Used to retrieve specific values.
arr[1:5] or arr[1:5:2]
Symbols/Usage: Slicing syntax [start:stop:step]. Used to extract a subset of an array.
arr.reshape(rows, columns)
Symbols/Usage: Reshapes array arr into the specified rows and columns. Used to change data dimensions for model input.
np.concatenate((array1, array2), axis=0 or 1)
Symbols/Usage: Joins array1 and array2 along axis 0 (rows) or 1 (columns). Used to merge arrays.
np.stack((array1, array2), axis=0 or 1)
Symbols/Usage: Stacks arrays along a new axis. Similar to concatenate but creates a new dimension. Used for combining arrays.
np.hstack((array1, array2))
Symbols/Usage: Stacks arrays horizontally (column-wise). Used for side-by-side joining.
np.vstack((array1, array2))
Symbols/Usage: Stacks arrays vertically (row-wise). Used for top-to-bottom joining.
np.split(array, 3)
Symbols/Usage: Splits array into 3 equal-sized sub-arrays. Used to partition data.
pd.read_csv('data.csv')
Symbols/Usage: Reads a CSV file into a pandas DataFrame. Used for data loading.
pd.read_json('data.json')
Symbols/Usage: Reads a JSON file into a pandas DataFrame. Used for data loading.
df.loc['day2']
Symbols/Usage: Accesses the row in DataFrame df with index label 'day2'. Used for label-based row selection.
df.head(10)
Symbols/Usage: Returns the first 10 rows of DataFrame df. Used for quick data inspection.
df.tail(10)
Symbols/Usage: Returns the last 10 rows of DataFrame df. Used for quick data inspection.
df.describe()
Symbols/Usage: Generates descriptive statistics (count, mean, std, min, percentiles) for numerical columns in DataFrame df. Used for data summary.
Worked examples
- Installing NumPy:
pip install numpy. - Creating a basic array:
import numpy as np; arr = np.array([1, 2, 3, 4, 5]). - Array dimensions:
- 0D:
np.array(42). - 1D:
np.array([1, 2, 3, 4, 5]). - 2D:
np.array([[1, 2, 3], [4, 5, 6]]). - 3D:
np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]).
- 0D:
- Indexing:
- 1D:
arr = np.array([1, 2, 3, 4]); arr[0]->1;arr[2] + arr[3]->7. - 2D:
arr = np.array([[1, 2, 3], [4, 5, 6]]); arr[0, 1]->2;arr[1, 2]->6. - 3D:
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]); arr[0, 1, 2]->6;arr[1, 1, 1]->11.
- 1D:
- Negative indexing:
arr[-1]accesses the last element. - Slicing:
arr = np.array([1, 2, 3, 4, 5, 6, 7]).arr[1:5]->[2, 3, 4, 5].arr[4:]->[5, 6, 7].arr[-3:-1]->[5, 6].arr[1:5:2]->[2, 4].
- Splitting: Splitting
[1, 2, 3, 4, 5, 6]into three parts yields three arrays. - Creating a DataFrame:
data = {"Duration": [420, 380, 390], "Calorie": [50, 40, 45]}; df = pd.DataFrame(data). - DataFrame indexing: With index
['day1', 'day2', 'day3'],df.loc['day2']returns[380, 40].
Questions asked in class
Q: In Python list, can we add items at any time?
A: Yes, it is possible.
Q: While creating an array in NumPy, do we always define a list?
A: No, we are defining an array using np.array(). The input can look like a list, but the result is a NumPy array object.
Q: Can we add/join five-dimension, two-dimension arrays?
A: Yes, operations like adding and joining can be performed.
Q: How does NumPy manage five-dimension indices?
A: Python can understand n-dimensions. A dimension is like a "list of lists."
Q: Is a matrix a two-dimensional array?
A: Yes, a two-dimension array is a matrix. One-dimension is a vector.
Q: Sir, can you explain about the axis zero and axis one?
A: Axis zero is row-wise addition; axis one is column-wise addition.
Q: Sir, if we have a multiple diameter in the data set how can we read the data from it?
A: First convert the file to CSV format, then you can work with it.
Q: Can we read JSON file?
A: Yes, 100%, but you need to have a JSON file. Use pd.read_json('data.json').
Q: Can we read XML file?
A: Yes, Python can read every file, but the command/syntax is different. In machine learning, we mainly read CSV or JSON files.
Q: How can check the data type of the column?
A: You can check the data type of a particular column; for example, carga and model might be objects, while volume, weight, co2 are integers.
Key takeaways
- NumPy's
ndarrayis the fundamental data structure for numerical computing in ML, offering significant speed advantages over Python lists. - The dimension of an array can be identified by counting the pairs of square brackets
[ ]. - Array indexing starts at 0, and negative indices count backwards from the end.
- Slicing uses the syntax
[start:stop:step], wherestartis inclusive andstopis exclusive. - Reshaping changes an array's layout without changing its data, crucial for preparing inputs for ML models.
- Concatenation (
np.concatenate) joins arrays along an axis (0 for rows, 1 for columns). - Stacking functions (
hstack,vstack) are specialized forms of concatenation for horizontal and vertical joining. - A pandas DataFrame is a 2D, labeled data structure essential for data manipulation and analysis.
- The
pd.read_csv()andpd.read_json()functions are primary methods for loading data into DataFrames. - Use
df.head(),df.tail(), anddf.describe()for initial data exploration and summary statistics. - The
df.loc[]indexer is used to select rows by their label. - Different columns in a DataFrame can have different data types (e.g., object, int64).
Exam-style questions
-
Given a 1D NumPy array
arr = np.array([10, 20, 30, 40, 50, 60, 70]), write the code to extract the elements[20, 30, 40]and then[50, 70]using slicing.
Outline: Usearr[1:4]for the first subset. For the second, use a step:arr[4::2]orarr[4:7:2]. -
You have two 2x2 NumPy arrays,
AandB. Explain the difference betweennp.concatenate((A, B), axis=0)andnp.hstack((A, B)). What would be the output shape for each if A and B are both shape (2,2)?
Outline:concatenatewithaxis=0stacks vertically, resulting in shape (4,2).hstackstacks horizontally, resulting in shape (2,4). -
A pandas DataFrame
dfhas columns 'Age' (int) and 'Name' (object). Write the code to display the first 3 rows and then generate a statistical summary for the numerical column.
Outline: Usedf.head(3)to show first rows. Usedf.describe()ordf['Age'].describe()for the summary.
Glossary
NumPy - A Python library for numerical computing with powerful N-dimensional array objects.
ndarray - The N-dimensional array object at the core of NumPy.
Indexing - Accessing an individual element of an array by its position.
Slicing - Extracting a portion of an array using a start, stop, and step.
Reshaping - Changing the shape (dimensions) of an array without changing its data.
Axis - A dimension along which an operation is performed (0 for rows, 1 for columns).
Concatenation - Joining two or more arrays along an existing axis.
Stacking - Joining arrays along a new axis.
pandas - A Python library for data manipulation and analysis, built on DataFrames.
DataFrame - A 2D, tabular pandas data structure with labeled axes.
CSV - Comma Separated Values, a simple file format for storing tabular data.
JSON - JavaScript Object Notation, a lightweight data-interchange format.
head() - A DataFrame method returning the first n rows.
describe() - A DataFrame method generating descriptive statistics.
loc - A label-based indexer for selecting rows in a DataFrame.
Follow-ups
- The instructor will share a complete file/notebook with code examples for NumPy and pandas practice.
- Lecture notes and example files will be uploaded to the chat/learning platform.
- Detailed operations on arrays (addition, joining) will be covered later.
- Practical use of the
reshapefunction will be explored further. - The other three essential libraries (matplotlib, seaborn, scikit-learn) will be covered in subsequent classes.
- The connection of these libraries to actual machine learning algorithms and data preprocessing is forthcoming.
- For local development environments, install pandas via
pip install pandas. - To work with datasets, files must be uploaded to the environment (Jupyter/Colab) before reading.