| name | python-programming |
| description | Python fundamentals, data structures, OOP, and data science libraries (Pandas, NumPy). Use when writing Python code, data manipulation, or algorithm implementation. |
| sasmp_version | 1.3.0 |
| bonded_agent | 01-python-data-science |
| bond_type | PRIMARY_BOND |
Python Programming for Data Science
Master Python from fundamentals to advanced data science applications.
Quick Start
Essential Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
Data Manipulation
df = pd.read_csv('data.csv')
print(df.head())
print(df.info())
print(df.describe())
df_filtered = df[df['age'] > 18]
summary = df.groupby('category')['sales'].agg(['sum', 'mean', 'count'])
df['new_col'] = df['col1'] * 2
Core Concepts
1. Data Structures
- Lists:
[1, 2, 3] - ordered, mutable
- Dictionaries:
{'key': 'value'} - key-value pairs
- Tuples:
(1, 2, 3) - immutable
- Sets:
{1, 2, 3} - unique elements
2. List Comprehensions
squares = [x**2 for x in range(10)]
filtered = [x for x in data if x > 0]
3. NumPy Arrays
arr = np.array([1, 2, 3, 4, 5])
arr * 2
arr.mean()
4. Pandas DataFrames
df = pd.DataFrame({
'name': ['Alice', 'Bob'],
'age': [25, 30],
'salary': [50000, 60000]
})
Performance Tips
Vectorization over Loops (10-100x faster):
result = []
for x in data:
result.append(x * 2)
result = np.array(data) * 2
Common Patterns
Reading Files
df = pd.read_csv('file.csv')
df = pd.read_excel('file.xlsx', sheet_name='Sheet1')
df = pd.read_json('file.json')
import sqlite3
conn = sqlite3.connect('database.db')
df = pd.read_sql_query("SELECT * FROM table", conn)
Missing Data
df.dropna()
df.fillna(0)
df.fillna(df.mean())
Merging Data
merged = pd.merge(df1, df2, on='id', how='left')
combined = pd.concat([df1, df2], axis=0)
Best Practices
- Use vectorized operations
- Optimize data types
- Avoid loops when possible
- Use built-in functions
- Profile before optimizing
Troubleshooting
Common Issues
Problem: MemoryError with large DataFrames
for chunk in pd.read_csv('large.csv', chunksize=10000):
process(chunk)
df['int_col'] = df['int_col'].astype('int32')
df['cat_col'] = df['cat_col'].astype('category')
Problem: Slow DataFrame operations
%timeit df.apply(func)
df['result'] = np.where(df['x'] > 0, df['x'] * 2, 0)
Problem: Import errors
pip list | grep pandas
pip install --upgrade pandas numpy
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
Problem: Data type mismatches
print(df.dtypes)
df['date'] = pd.to_datetime(df['date'])
df['price'] = pd.to_numeric(df['price'], errors='coerce')
Debug Checklist