Data analysis is a cornerstone of AI and machine learning projects, and Python's Pandas library is the go-to tool for handling structured data. This guide covers the must-know basics of Pandas, including its two core data structures: Series and DataFrames, with hands-on code examples.
What is Pandas?
Pandas is an open-source Python library that provides high-performance, easy-to-use data structures and data analysis tools. It simplifies tasks like data cleaning, transformation, aggregation, and visualization, making it essential for data scientists and ML engineers.
Getting Started
First, install Pandas with pip install pandas. Then import it in your script:
import pandas as pd
Core Data Structures
Series
A Series is a one-dimensional labeled array that can hold any data type. It's like a column in an Excel spreadsheet or a dictionary with ordered keys.
# Create a Series from a list
data = [10, 20, 30, 40]
series = pd.Series(data, index=['a', 'b', 'c', 'd'])
print(series)
Output:
a 10
b 20
c 30
d 40
dtype: int64
DataFrame
A DataFrame is a two-dimensional labeled data structure with columns of potentially different types. It's similar to a SQL table or a spreadsheet.
# Create a DataFrame from a dictionary
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000]
}
df = pd.DataFrame(data)
print(df)
Output:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 35 70000
Key Pandas Operations
- Reading Data:
pd.read_csv('file.csv')loads data from a CSV file. - Viewing Data:
df.head()shows first 5 rows;df.describe()gives summary statistics. - Selecting Columns:
df['Name']returns a Series;df[['Name', 'Salary']]returns a DataFrame. - Filtering Rows:
df[df['Age'] > 30]filters rows where Age > 30. - Handling Missing Values:
df.dropna()removes rows with missing values;df.fillna(0)fills them. - Grouping:
df.groupby('Name').mean()groups by a column and computes the mean.
Pandas in AI and ML Workflows
Pandas is widely used in machine learning pipelines for:
- Data Cleaning: Handling missing values, duplicates, and outliers.
- Feature Engineering: Creating new columns from existing data.
- Exploratory Data Analysis (EDA): Summarizing and visualizing data.
- Preprocessing: Scaling, encoding categorical variables, and splitting datasets.
Example: EDA on a Sample Dataset
df = pd.read_csv('sample_data.csv')
print(df.info())
print(df.describe())
print(df['Category'].value_counts())
Mastering these basics will enable you to efficiently prepare data for any AI or machine learning project.