💡 What is a Pandas DataFrame?
A Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it as a spreadsheet, an SQL table, or a dictionary of Series objects. It is the primary data structure used across all data science, machine learning, and AI feature engineering pipelines.
1. Creating a DataFrame from a Python Dictionary
Constructing a structured table from a Python dictionary where keys represent column headers and lists represent row values.
Python (df_from_dict.py)
import pandas as pd
def create_dataframe_dict():
data = {
'Employee': ['Alice', 'Bob', 'Charlie', 'Diana'],
'Department': ['Engineering', 'Marketing', 'Sales', 'HR'],
'Salary': [95000, 68000, 72000, 65000],
'Active': [True, True, False, True]
}
df = pd.DataFrame(data)
print(df)
create_dataframe_dict()
Output:
Employee Department Salary Active
0 Alice Engineering 95000 True
1 Bob Marketing 68000 True
2 Charlie Sales 72000 False
3 Diana HR 65000 True
2. Inspecting Data with `.head()`, `.tail()`, and `.info()`
Using structural inspection methods to verify column datatypes, non-null counts, and sample row previews.
Python (df_inspect.py)
import pandas as pd
def inspect_df():
df = pd.DataFrame({
'ID': [101, 102, 103, 104, 105],
'Score': [85.5, 92.0, 78.4, 90.1, 88.9]
})
print("--- First 2 Rows (.head) ---")
print(df.head(2))
print("\n--- DataFrame Structure & Info ---")
print(df.info())
inspect_df()
Output:
--- First 2 Rows (.head) ---
ID Score
0 101 85.5
1 102 92.0
--- DataFrame Structure & Info ---
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 ID 5 non-null int64
1 Score 5 non-null float64
dtypes: float64(1), int64(1)
memory usage: 208.0 bytes
3. Generating Descriptive Statistics with `.describe()`
Instantly computing count, mean, standard deviation, min, quartiles, and max for all numerical columns.
Python (df_describe.py)
import pandas as pd
def describe_data():
df = pd.DataFrame({
'Units_Sold': [120, 250, 180, 310, 95],
'Revenue_USD': [1200.0, 2500.0, 1800.0, 3100.0, 950.0]
})
print(df.describe())
describe_data()
Output:
Units_Sold Revenue_USD
count 5.000000 5.000000
mean 191.000000 1910.000000
std 86.429162 864.291621
min 95.000000 950.000000
25% 120.000000 1200.000000
50% 180.000000 1800.000000
75% 250.000000 2500.000000
max 310.000000 3100.000000
4. Reading Data from a CSV File (`pd.read_csv`)
Ingesting comma-separated values from local storage or cloud URLs into a Pandas DataFrame.
Python (read_csv_example.py)
import pandas as pd
def load_csv_data():
# Example reading a sales dataset CSV file
# df = pd.read_csv('sales_data.csv', parse_dates=['Date'])
# Simulating read_csv with StringIO for demonstration
from io import StringIO
csv_data = "OrderID,Customer,Amount\n1,Alice,250.50\n2,Bob,120.00"
df = pd.read_csv(StringIO(csv_data))
print(df)
load_csv_data()
Output:
OrderID Customer Amount
0 1 Alice 250.5
1 2 Bob 120.0
5. Exporting Data to a CSV File (`df.to_csv`)
Saving cleaned DataFrames back into CSV format without including the default row index numbers.
Python (export_csv.py)
import pandas as pd
def save_to_csv():
df = pd.DataFrame({
'Product': ['Laptop', 'Mouse'],
'Price': [1200, 25]
})
# Export without row index
df.to_csv('cleaned_products.csv', index=False)
print("DataFrame successfully exported to cleaned_products.csv")
save_to_csv()
Output:
DataFrame successfully exported to cleaned_products.csv
6. Ingesting and Exporting JSON Data (`pd.read_json`)
Parsing hierarchical JSON API payloads into structured DataFrames and exporting back to JSON records.
Python (json_io.py)
import pandas as pd
from io import StringIO
def handle_json():
json_payload = '[{"City": "New York", "Temp": 72}, {"City": "London", "Temp": 60}]'
# Load JSON into DataFrame
df = pd.read_json(StringIO(json_payload))
print("--- Loaded from JSON ---")
print(df)
# Export back to JSON records string
json_output = df.to_json(orient='records')
print("\nExported JSON String:", json_output)
handle_json()
Output:
--- Loaded from JSON ---
City Temp
0 New York 72
1 London 60
Exported JSON String: [{"City":"New_York","Temp":72},{"City":"London","Temp":60}]
7. Reading and Writing Excel Files (`pd.read_excel`)
Working with multi-sheet Microsoft Excel workbooks using the `openpyxl` library engine.
Python (excel_io.py)
import pandas as pd
def excel_operations():
df = pd.DataFrame({
'Quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
'Revenue': [45000, 52000, 48000, 61000]
})
# Write to Excel workbook sheet
excel_file = 'annual_revenue.xlsx'
df.to_excel(excel_file, sheet_name='Summary', index=False)
# Read back from Excel sheet
loaded_df = pd.read_excel(excel_file, sheet_name='Summary')
print(loaded_df)
excel_operations()
Output:
Quarter Revenue
0 Q1 45000
1 Q2 52000
2 Q3 48000
3 Q4 61000
8. High-Performance Apache Parquet I/O (`pd.read_parquet`)
Using compressed columnar Parquet storage to drastically reduce file sizes and accelerate load times for big data.
Python (parquet_io.py)
import pandas as pd
def parquet_operations():
df = pd.DataFrame({
'Transaction_ID': range(1000),
'Amount': [val * 1.5 for val in range(1000)]
})
parquet_file = 'transactions.parquet'
# Save to Parquet with Snappy compression
df.to_parquet(parquet_file, compression='snappy', index=False)
# Read back from Parquet
loaded_df = pd.read_parquet(parquet_file)
print(loaded_df.head(3))
parquet_operations()
Output:
Transaction_ID Amount
0 0 0.0
1 1 1.5
2 2 3.0
9. Inspecting DataFrame Dimensions, Columns, and Index
Accessing underlying DataFrame shape attributes, column name arrays, and index configurations.
Python (df_attributes.py)
import pandas as pd
def check_attributes():
df = pd.DataFrame({
'A': [1, 2],
'B': [3, 4],
'C': [5, 6]
})
print("Shape (Rows, Cols):", df.shape)
print("Column Names:", df.columns.tolist())
print("Index Range:", df.index)
print("Data Types:\n", df.dtypes)
check_attributes()
Output:
Shape (Rows, Cols): (2, 3)
Column Names: ['A', 'B', 'C']
Index Range: RangeIndex(start=0, stop=2, step=1)
Data Types:
A int64
B int64
C int64
dtype: object
10. Transposing DataFrames (`df.T`)
Flipping rows and columns of a DataFrame to restructure summary reports or matrix layouts.
Python (df_transpose.py)
import pandas as pd
def transpose_dataframe():
df = pd.DataFrame({
'Metric': ['Revenue', 'Profit', 'Employees'],
'2024': [500000, 120000, 45],
'2025': [650000, 180000, 60]
}).set_index('Metric')
print("--- Original DataFrame ---")
print(df)
print("\n--- Transposed DataFrame (df.T) ---")
print(df.T)
transpose_dataframe()
Output:
--- Original DataFrame ---
2024 2025
Metric
Revenue 500000 650000
Profit 120000 180000
Employees 45 60
--- Transposed DataFrame (df.T) ---
Metric Revenue Profit Employees
2024 500000 120000 45
2025 650000 180000 60