Pandas is a powerful Python library for data manipulation and analysis. This tutorial introduces beginners to Pandas, covering the basics of creating, manipulating, and analyzing data using DataFrames and Series, as well as advanced features like merging, reshaping, time-series analysis, multi-indexing, handling large datasets, and visualization. All examples are simple and include explanations.
NumPy installed for some advanced features (pip install numpy)
Matplotlib and Seaborn for visualization (pip install matplotlib seaborn)
Importing Pandas
To use Pandas, import it with the common alias pd.
Code
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns
Pandas Data Structures
Pandas has two primary data structures: - Series: A one-dimensional array-like object, similar to a list or a column in a table. - DataFrame: A two-dimensional table with rows and columns, like a spreadsheet.
Creating a Series
A Series can be created from a list, dictionary, or array.
Code
# Creating a Series from a listdata = [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
The index parameter assigns labels to each value. If omitted, Pandas assigns default numeric indices (0, 1, 2, …).
Creating a DataFrame
A DataFrame can be created from a dictionary, list of dictionaries, or other data structures.
Code
# Creating a DataFrame from a dictionarydata = {'Name': ['Alice', 'Bob', 'Charlie'],'Age': [25, 30, 35],'City': ['New York', 'Los Angeles', 'Chicago']}df = pd.DataFrame(data)print(df)
Output:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
Each key in the dictionary becomes a column, and the values form the rows.
3. Viewing Data
Pandas provides methods to inspect DataFrames.
View first few rows: df.head(n) (default n=5)
View last few rows: df.tail(n)
Get basic info: df.info()
Summary statistics: df.describe()
Code
# Viewing the first 2 rowsprint(df.head(2))# Get DataFrame infoprint(df.info())
Selecting Data
You can select specific rows, columns, or values using indexing.
Selecting Columns
Access columns using their names.
Code
# Select a single column (returns a Series)print(df['Name'])# Select multiple columns (returns a DataFrame)print(df[['Name', 'City']])
Selecting Rows
Use loc (label-based) or iloc (integer-based) to select rows.
Code
# Select row by index labelprint(df.loc[0])# Select row by integer positionprint(df.iloc[1])
Filtering Data
Filter rows based on conditions.
Code
# Filter rows where Age > 30print(df[df['Age'] >30])
You can combine conditions using & (and) or | (or).
Code
# Filter rows where Age > 25 and City is Chicagoprint(df[(df['Age'] >25) & (df['City'] =='Chicago')])
Adding and Modifying Data
You can add new columns or modify existing ones.
Adding a Column
Code
# Add a new columndf['Salary'] = [50000, 60000, 75000]print(df)
Modifying Data
Update values using loc or conditions.
Code
# Update a specific valuedf.loc[0, 'Age'] =26# Increase all salaries by 10%df['Salary'] = df['Salary'] *1.1print(df)
Handling Missing Data
Pandas provides methods to handle missing values (NaN).
Code
# Introduce a missing valuedf.loc[1, 'City'] =Noneprint(df)# Fill missing values with a defaultdf['City'] = df['City'].fillna('Unknown')print(df)
Grouping and Aggregating
Group data by a column and compute aggregates (e.g., mean, sum).
Code
# Group by City and calculate average Salaryprint(df.groupby('City')['Salary'].mean())
aving and Loading Data
Pandas supports reading and writing data in various formats (CSV, Excel, JSON, etc.).
Convert a column to datetime and perform time-based operations.
Code
# Create a DataFrame with datesdf_time = pd.DataFrame({'Date': ['2023-01-01', '2023-02-01', '2023-03-01'],'Sales': [100, 150, 200]})df_time['Date'] = pd.to_datetime(df_time['Date'])# Set Date as indexdf_time.set_index('Date', inplace=True)# Resample to monthly frequency and compute meanmonthly_sales = df_time.resample('ME').mean()print(monthly_sales)
Rolling Windows
Calculate rolling statistics, like a moving average.
Code
# Calculate 2-period rolling meandf_time['Rolling_Mean'] = df_time['Sales'].rolling(window=2).mean()print(df_time)
Applying Custom Functions
Use apply or map to apply custom functions to DataFrames or Series.
Code
# Define a custom functiondef categorize_salary(salary):return'High'if salary >70000else'Low'# Apply to Salary columndf['Salary_Category'] = df['Salary'].apply(categorize_salary)print(df)
Multi-Indexing
Multi-indexing allows hierarchical indexing for more complex data organization.
Creating a Multi-Index DataFrame
Set multiple columns as the index to create a multi-level index.
Code
# Set multi-index using City and Yeardf_multi = df.set_index(['City', 'Year'])print(df_multi)
Selecting with Multi-Index
Access data using multi-level indices with loc.
Code
# Select data for New York in 2023print(df_multi.loc[('New York', 2023)])
Aggregating with Multi-Index
Group and aggregate with multi-level indices.
Code
# Group by City and Year, calculate average Salaryprint(df_multi.groupby(level=['City', 'Year'])['Salary'].mean())
Handling Large Datasets with Chunking
For large datasets, Pandas can process data in chunks to manage memory usage.
Reading in Chunks
Use chunksize with read_csv to process large files incrementally.
Code
# Example: Reading a large CSV file in chunks# Assume 'large_data.csv' existschunk_size =2for chunk in pd.read_csv('output.csv', chunksize=chunk_size):# Process each chunk (e.g., filter or aggregate)print(chunk.groupby('City')['Salary'].mean())
This approach is useful for files too large to fit in memory. You can perform operations (e.g., filtering, aggregating) on each chunk and combine results if needed.
Visualization with Matplotlib and Seaborn
Pandas integrates seamlessly with Matplotlib and Seaborn for data visualization.
Matplotlib: Bar Plot
Create a bar plot of average salaries by city.
Code
# Plot average salary by cityavg_salary = df.groupby('City')['Salary'].mean()avg_salary.plot(kind='bar', title='Average Salary by City')plt.xlabel('City')plt.ylabel('Salary')plt.show()
Output: A bar plot showing average salaries for each city.
Seaborn: Box Plot
Use Seaborn for a box plot to visualize salary distribution by salary category.
Code
# Box plot of salaries by Salary_Categorysns.boxplot(x='Salary_Category', y='Salary', data=df)plt.title('Salary Distribution by Category')plt.show()
Output: A box plot comparing salaries in ‘High’ and ‘Low’ categories.
Summary and Conclusion
This tutorial covers the essentials of Pandas for beginners, from creating and manipulating DataFrames and Series to advanced features like merging, reshaping, time-series analysis, multi-indexing, chunking for large datasets, and visualization with Matplotlib and Seaborn. Pandas is a versatile tool for data analysis, enabling efficient handling of structured data, complex indexing, and integration with visualization libraries. By mastering these concepts, you can perform sophisticated data manipulations and create insightful visualizations. Practice with real-world datasets to solidify your skills and explore Pandas’ full potential.
Resources
Official Pandas Documentation: https://pandas.pydata.org/docs/