pandas-ai
PandasAI enables natural language queries on pandas DataFrames using LLMs. Learn to ask questions in plain English, generate charts, clean data, and integrate with OpenAI and local models for conversational data analysis.
What this skill does
# PandasAI
PandasAI adds natural language capabilities to pandas. Ask questions about your data in English and get answers, charts, and transformations — powered by LLMs.
## Installation
```bash
# Install PandasAI
pip install pandasai
# With OpenAI
pip install pandasai[openai]
# With local models via Ollama
pip install pandasai[langchain]
```
## Basic Usage
```python
# basic.py: Ask questions about a DataFrame in natural language
import pandas as pd
from pandasai import SmartDataframe
from pandasai.llm import OpenAI
llm = OpenAI(api_token="your-openai-api-key")
df = pd.DataFrame({
"country": ["USA", "UK", "France", "Germany", "Japan"],
"population": [331_000_000, 67_000_000, 67_000_000, 83_000_000, 125_000_000],
"gdp_billion": [25_460, 3_070, 2_780, 4_070, 4_230],
})
sdf = SmartDataframe(df, config={"llm": llm})
# Ask questions in natural language
answer = sdf.chat("Which country has the highest GDP?")
print(answer) # USA
answer = sdf.chat("What is the average population?")
print(answer) # 134,600,000
answer = sdf.chat("List countries with GDP above 4000 billion")
print(answer)
```
## Multiple DataFrames
```python
# multi-df.py: Query across multiple related DataFrames
from pandasai import SmartDatalake
employees = pd.DataFrame({
"id": [1, 2, 3, 4, 5],
"name": ["Alice", "Bob", "Charlie", "Diana", "Eve"],
"department_id": [1, 2, 1, 3, 2],
"salary": [85000, 72000, 90000, 68000, 95000],
})
departments = pd.DataFrame({
"id": [1, 2, 3],
"name": ["Engineering", "Marketing", "Sales"],
"budget": [500000, 200000, 300000],
})
lake = SmartDatalake([employees, departments], config={"llm": llm})
result = lake.chat("What is the average salary per department?")
print(result)
result = lake.chat("Which department is over budget based on total salaries?")
print(result)
```
## Generate Charts
```python
# charts.py: Create visualizations from natural language
sdf = SmartDataframe(df, config={
"llm": llm,
"save_charts": True,
"save_charts_path": "./charts",
})
# Generate charts by asking
sdf.chat("Create a bar chart of GDP by country")
sdf.chat("Plot a pie chart of population distribution")
sdf.chat("Show a scatter plot of GDP vs population")
# Charts saved as PNG in ./charts/
```
## Data Cleaning
```python
# cleaning.py: Use natural language for data cleaning tasks
dirty_df = pd.DataFrame({
"name": ["Alice", "bob", "CHARLIE", None, "Eve"],
"email": ["[email protected]", "invalid", "[email protected]", "[email protected]", ""],
"age": [30, -5, 45, 200, 28],
"salary": [85000, 72000, None, 68000, 95000],
})
sdf = SmartDataframe(dirty_df, config={"llm": llm})
# Clean with natural language
cleaned = sdf.chat("Remove rows where age is negative or above 150")
cleaned = sdf.chat("Fill missing salaries with the median salary")
cleaned = sdf.chat("Standardize names to title case")
cleaned = sdf.chat("Remove rows with invalid email addresses")
```
## Custom Configuration
```python
# config.py: Advanced PandasAI configuration
from pandasai import SmartDataframe
sdf = SmartDataframe(df, config={
"llm": llm,
"conversational": True, # Natural language responses
"verbose": True, # Show generated code
"enable_cache": True, # Cache repeated queries
"max_retries": 3, # Retry on LLM errors
"custom_whitelisted_dependencies": ["scipy", "sklearn"],
"save_logs": True,
})
# View the generated Python code
sdf.chat("What is the correlation between GDP and population?")
print(sdf.last_code_generated)
```
## Using Local Models
```python
# local-llm.py: Use Ollama or other local models instead of OpenAI
from pandasai.llm.local_llm import LocalLLM
# With Ollama running locally
llm = LocalLLM(api_base="http://localhost:11434/v1", model="llama3")
sdf = SmartDataframe(df, config={"llm": llm})
answer = sdf.chat("Summarize this dataset")
print(answer)
```
## Pipeline Integration
```python
# pipeline.py: Use PandasAI in an automated analysis pipeline
from pandasai import SmartDataframe
from pandasai.llm import OpenAI
import pandas as pd
import json
def analyze_dataset(csv_path: str, questions: list[str]) -> dict:
"""Run a set of natural language questions against a CSV dataset."""
llm = OpenAI(api_token="your-key")
df = pd.read_csv(csv_path)
sdf = SmartDataframe(df, config={"llm": llm, "conversational": True})
results = {}
for question in questions:
try:
answer = sdf.chat(question)
results[question] = str(answer)
except Exception as e:
results[question] = f"Error: {e}"
return results
# Usage
report = analyze_dataset("sales.csv", [
"What was the total revenue last month?",
"Which product category had the most sales?",
"What is the month-over-month growth rate?",
])
print(json.dumps(report, indent=2))
```
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.