0Pricing
AI Agents · บทเรียน

เครื่องมือตัวแทนขับเคลื่อนด้วย Pandas

คำจำกัดความเครื่องมือสำหรับการดำเนินการ read_csv, groupby, merge และ describe

เครื่องมือตัวแทนขับเคลื่อนด้วย Pandas เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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() ซึ่งรองรับนิพจน์ 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

ลงทะเบียนเครื่องมือ pandas ทั้งหมดกับเอเจนต์ LLM โดยใช้รูปแบบการเรียกฟังก์ชันของ OpenAI เอเจนต์จะตัดสินใจว่าจะเรียกใช้เครื่องมือใดตามคำถามของผู้ใช้

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” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “เครื่องมือตัวแทนขับเคลื่อนด้วย Pandas”

คำจำกัดความเครื่องมือสำหรับการดำเนินการ read_csv, groupby, merge และ describe คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “เครื่องมือตัวแทนขับเคลื่อนด้วย Pandas” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม

ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. รูปแบบตัวแปลโค้ดสำหรับการวิเคราะห์ข้อมูล
  2. เครื่องมือตัวแทนขับเคลื่อนด้วย Pandas
  3. การสร้างแผนภูมิและภาพข้อมูลอัตโนมัติ
  4. ตัวแทนสรุปผลทางสถิติ
← กลับไปที่ AI Agents