Pandas 기반 데이터 에이전트 도구
read_csv, groupby, merge, describe 작업을 위한 도구 정의를 다룹니다.
Pandas 기반 데이터 에이전트 도구은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
데이터 에이전트를 위한 Pandas 도구
임의의 코드를 생성하는 대신 데이터 에이전트에 명확하게 정의된 pandas 도구 모음을 제공할 수 있습니다. 각 도구는 특정 데이터 작업을 수행하고 구조화된 결과를 반환합니다.
이 접근 방식은 자유 형식 코드 생성보다 안전하고 예측 가능하며, 에이전트가 처음부터 코드를 작성하는 대신 도구를 선택하고 연결합니다.
도구: read_csv
모든 데이터 분석 세션의 시작점입니다. read_csv는 CSV 파일을 메모리에 불러오고 데이터의 행과 열 구조 및 열 설명을 반환하므로, 에이전트가 어떤 데이터를 다루는지 파악할 수 있습니다.
import pandas as pd
from typing import Optional
# In-memory dataframe store (shared across tool calls in one session)
dataframes = {}
def read_csv(path: str, df_name: str = 'df') -> dict:
'''Load a CSV file and return schema info.'''
df = pd.read_csv(path)
dataframes[df_name] = df
return {
'df_name': df_name,
'rows': len(df),
'columns': list(df.columns),
'dtypes': df.dtypes.astype(str).to_dict(),
'sample': df.head(3).to_dict(orient='records'),
'null_counts': df.isnull().sum().to_dict()
}
# Agent usage:
result = read_csv('orders.csv', 'orders')
print(f"Loaded {result['rows']} rows, columns: {result['columns']}")도구: filter_dataframe
조건 문자열을 기준으로 행을 필터링합니다. 조건은 df.query()를 사용하여 데이터프레임에 대해 평가되며, df.query()는 pandas 표현식 중 안전한 일부를 지원합니다.
def filter_dataframe(df_name: str, condition: str, result_name: str = None) -> dict:
'''Filter rows matching condition. Returns filtered dataframe info.'''
df = dataframes.get(df_name)
if df is None:
return {'error': f'Dataframe {df_name!r} not found. Call read_csv first.'}
try:
filtered = df.query(condition)
store_name = result_name or f'{df_name}_filtered'
dataframes[store_name] = filtered
return {
'df_name': store_name,
'rows_before': len(df),
'rows_after': len(filtered),
'sample': filtered.head(3).to_dict(orient='records')
}
except Exception as e:
return {'error': f'Filter error: {e}'}
# Example: filter orders from 2024
result = filter_dataframe('orders', 'order_date >= "2024-01-01"', 'orders_2024')
print(f"Filtered to {result['rows_after']} rows")도구: groupby_aggregate
열을 기준으로 행을 그룹화하고 집계값을 계산합니다. 합계, 평균, 범주별 개수처럼 데이터 분석에서 가장 자주 필요한 작업 중 하나입니다.
def groupby_aggregate(df_name: str, group_column: str,
agg_column: str, agg_func: str) -> dict:
'''Group by column and aggregate. agg_func: sum, mean, count, min, max, median'''
df = dataframes.get(df_name)
if df is None:
return {'error': f'Dataframe {df_name!r} not found'}
VALID_FUNCS = {'sum', 'mean', 'count', 'min', 'max', 'median', 'std'}
if agg_func not in VALID_FUNCS:
return {'error': f'Invalid agg_func. Choose from: {VALID_FUNCS}'}
try:
result = df.groupby(group_column)[agg_column].agg(agg_func).reset_index()
result.columns = [group_column, f'{agg_column}_{agg_func}']
result = result.sort_values(f'{agg_column}_{agg_func}', ascending=False)
return {
'result': result.head(20).to_dict(orient='records'),
'total_groups': len(result)
}
except Exception as e:
return {'error': str(e)}
# Agent call: total revenue by product category
print(groupby_aggregate('orders', 'category', 'revenue', 'sum'))도구: merge_dataframes
공통 키를 기준으로 두 데이터프레임을 결합합니다. 이를 통해 여러 파일의 데이터를 합칠 수 있습니다. 예를 들어 주문 데이터와 고객 표를 결합하여 고객 이름을 가져올 수 있습니다.
def merge_dataframes(df1_name: str, df2_name: str,
on: str, how: str = 'inner',
result_name: str = 'merged') -> dict:
'''Join two dataframes on a key column.'''
df1 = dataframes.get(df1_name)
df2 = dataframes.get(df2_name)
if df1 is None:
return {'error': f'{df1_name!r} not found'}
if df2 is None:
return {'error': f'{df2_name!r} not found'}
VALID_HOW = {'inner', 'left', 'right', 'outer'}
if how not in VALID_HOW:
return {'error': f'Invalid join type. Choose from: {VALID_HOW}'}
try:
merged = df1.merge(df2, on=on, how=how)
dataframes[result_name] = merged
return {
'df_name': result_name,
'rows': len(merged),
'columns': list(merged.columns),
'sample': merged.head(3).to_dict(orient='records')
}
except Exception as e:
return {'error': str(e)}
# Join orders with customers on customer_id
print(merge_dataframes('orders', 'customers', on='customer_id'))도구: describe_dataframe
데이터프레임의 통계 요약을 반환합니다. 일반적으로 데이터를 불러온 후 에이전트가 가장 먼저 호출하는 도구이며, 분포와 범위, 잠재적인 데이터 품질 문제를 파악하는 데 사용됩니다.
def describe_dataframe(df_name: str) -> dict:
'''Return statistical summary and data quality info.'''
df = dataframes.get(df_name)
if df is None:
return {'error': f'Dataframe {df_name!r} not found'}
# Numeric stats
numeric_cols = df.select_dtypes(include='number').columns.tolist()
stats = {}
for col in numeric_cols:
s = df[col].describe()
stats[col] = {
'min': round(float(s['min']), 4),
'max': round(float(s['max']), 4),
'mean': round(float(s['mean']), 4),
'median': round(float(df[col].median()), 4),
'std': round(float(s['std']), 4),
'nulls': int(df[col].isnull().sum())
}
# Categorical columns summary
cat_cols = df.select_dtypes(include='object').columns.tolist()
cat_stats = {
col: {
'unique_values': df[col].nunique(),
'top_3': df[col].value_counts().head(3).to_dict()
}
for col in cat_cols
}
return {'numeric': stats, 'categorical': cat_stats, 'total_rows': len(df)}도구: sort_and_top_n
열을 기준으로 정렬한 상위 N개 행을 반환합니다. ‘상위 고객’, ‘최고의 제품’, ‘가장 높은 매출’과 같은 질문에 유용합니다.
def sort_and_top_n(df_name: str, sort_column: str,
n: int = 10, ascending: bool = False) -> dict:
'''Return top N rows sorted by column.'''
df = dataframes.get(df_name)
if df is None:
return {'error': f'{df_name!r} not found'}
if sort_column not in df.columns:
return {'error': f'Column {sort_column!r} not found. Available: {list(df.columns)}'}
sorted_df = df.sort_values(sort_column, ascending=ascending)
top = sorted_df.head(n)
return {
'rows': top.to_dict(orient='records'),
'total_rows_in_df': len(df),
'sort_column': sort_column,
'sort_order': 'ascending' if ascending else 'descending'
}
# Top 5 orders by total value
print(sort_and_top_n('orders', 'total_amount', n=5))도구: pivot_table
두 범주형 열을 집계값과 함께 교차 집계한 피벗 테이블을 생성합니다. ‘지역별 제품 범주별 매출’과 같은 질문에 적합합니다.
def pivot_table(df_name: str, index: str, columns: str,
values: str, aggfunc: str = 'sum') -> dict:
'''Create a pivot table.'''
df = dataframes.get(df_name)
if df is None:
return {'error': f'{df_name!r} not found'}
VALID_FUNCS = {'sum', 'mean', 'count', 'min', 'max'}
if aggfunc not in VALID_FUNCS:
return {'error': f'Invalid aggfunc. Choose from: {VALID_FUNCS}'}
try:
pivot = df.pivot_table(
index=index, columns=columns,
values=values, aggfunc=aggfunc,
fill_value=0
)
# Convert to nested dict for JSON serialization
result = pivot.round(2).to_dict()
return {
'pivot': result,
'index': index,
'columns': columns,
'values': values,
'aggfunc': aggfunc
}
except Exception as e:
return {'error': str(e)}도구: calculate_metric
기존 데이터프레임 열에서 매출 성장률, 전환율, 이탈률과 같은 단일 비즈니스 지표를 계산합니다. LLM에 pandas 표현식을 작성하도록 요청하는 것보다 정확합니다.
def calculate_metric(df_name: str, metric: str, params: dict = None) -> dict:
'''Calculate a named business metric from the dataframe.'''
df = dataframes.get(df_name)
if df is None:
return {'error': f'{df_name!r} not found'}
params = params or {}
try:
if metric == 'conversion_rate':
total_col = params.get('total_column', 'total')
converted_col = params.get('converted_column', 'converted')
rate = df[converted_col].sum() / df[total_col].sum() * 100
return {'metric': 'conversion_rate', 'value': round(rate, 2), 'unit': '%'}
elif metric == 'average_order_value':
revenue_col = params.get('revenue_column', 'revenue')
count_col = params.get('count_column', 'order_count')
aov = df[revenue_col].sum() / df[count_col].sum()
return {'metric': 'average_order_value', 'value': round(aov, 2)}
else:
return {'error': f'Unknown metric: {metric}'}
except Exception as e:
return {'error': str(e)}LLM 에이전트에 도구 등록
OpenAI의 함수 호출 형식을 사용하여 모든 pandas 도구를 LLM 에이전트에 등록합니다. 에이전트는 사용자의 질문을 바탕으로 호출할 도구를 결정합니다.
tools = [
{
'type': 'function',
'function': {
'name': 'read_csv',
'description': 'Load a CSV file for analysis',
'parameters': {
'type': 'object',
'properties': {
'path': {'type': 'string', 'description': 'Path to CSV file'},
'df_name': {'type': 'string', 'description': 'Name to reference this dataframe'}
},
'required': ['path']
}
}
},
{
'type': 'function',
'function': {
'name': 'groupby_aggregate',
'description': 'Group data by a column and compute sum, mean, count, min, max, or median',
'parameters': {
'type': 'object',
'properties': {
'df_name': {'type': 'string'},
'group_column': {'type': 'string'},
'agg_column': {'type': 'string'},
'agg_func': {'type': 'string', 'enum': ['sum', 'mean', 'count', 'min', 'max', 'median']}
},
'required': ['df_name', 'group_column', 'agg_column', 'agg_func']
}
}
}
]
if __name__ == '__main__':
print('Registered tools:')
for t in tools:
fn = t['function']
print(f" - {fn['name']}: {fn['description']}")
여러 도구 연결
복잡한 질문에는 여러 도구를 연결해야 합니다. 에이전트는 도구를 순서대로 호출하며, 한 도구의 출력을 다음 도구의 입력으로 사용합니다. 각 도구의 결과는 다음 도구를 호출하기 전에 에이전트로 반환됩니다.
import json
import openai
import os
client = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
TOOL_MAP = {
'read_csv': read_csv,
'filter_dataframe': filter_dataframe,
'groupby_aggregate': groupby_aggregate,
'describe_dataframe': describe_dataframe,
'merge_dataframes': merge_dataframes,
'sort_and_top_n': sort_and_top_n
}
def run_data_agent(question, data_paths):
messages = [
{'role': 'system', 'content': f'You are a data analyst. Available data: {data_paths}'},
{'role': 'user', 'content': question}
]
for _ in range(10): # max 10 tool calls
response = client.chat.completions.create(
model='gpt-4o', messages=messages, tools=tools
)
msg = response.choices[0].message
if not msg.tool_calls:
return msg.content # final answer
messages.append(msg)
for call in msg.tool_calls:
fn = TOOL_MAP[call.function.name]
args = json.loads(call.function.arguments)
result = fn(**args)
messages.append({'role': 'tool', 'tool_call_id': call.id,
'content': json.dumps(result)})
return 'Max tool calls reached'지식 확인
코드 인터프리터 패턴을 사용하는 것과 비교할 때 데이터 에이전트에 pandas 도구를 제공하는 방식의 핵심 장점은 무엇입니까?
요약: Pandas 기반 데이터 에이전트 도구
Pandas 도구는 데이터 에이전트에 안전하고 명확하게 정의된 작업을 제공합니다. read_csv, filter_dataframe, groupby_aggregate, merge_dataframes, describe_dataframe, sort_and_top_n, pivot_table이 여기에 해당합니다.
각 도구는 입력을 검증하고, 오류를 적절히 처리하며, 구조화된 결과를 반환합니다. OpenAI의 함수 호출 형식으로 도구를 등록하면 에이전트가 복잡한 여러 단계의 데이터 질문에 답하기 위해 도구 호출을 자동으로 연결합니다.
자주 묻는 질문
“Pandas 기반 데이터 에이전트 도구” 강의는 무료인가요?
네 — “Pandas 기반 데이터 에이전트 도구” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
“Pandas 기반 데이터 에이전트 도구”에서 뭘 배우나요?
read_csv, groupby, merge, describe 작업을 위한 도구 정의를 다룹니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“Pandas 기반 데이터 에이전트 도구” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 데이터 분석을 위한 코드 인터프리터 패턴
- Pandas 기반 데이터 에이전트 도구
- 자동화된 차트 및 시각화 생성
- 통계 요약 에이전트