最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺析PandasAI連接LLM對(duì)MySQL數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)分析

 更新時(shí)間:2025年08月05日 08:45:42   作者:人生海海 山山而川  
這篇文章主要為大家詳細(xì)介紹了PandasAI如何連接LLM對(duì)MySQL數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)分析,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

1. 引言

在之前的文章《PandasAI連接LLM進(jìn)行智能數(shù)據(jù)分析》中實(shí)現(xiàn)了使用PandasAI連接與DeepSeek模型通過自然語(yǔ)言進(jìn)行數(shù)據(jù)分析。不過那個(gè)例子中使用的是PandasAI 2.X,并且使用的是本地.csv文件來作為數(shù)據(jù)。在實(shí)際應(yīng)用的系統(tǒng)中,使用.csv作為庫(kù)表的情況比較少見。在本文中,就試試使用最新的PandasAI 3.0對(duì)MySQL數(shù)據(jù)庫(kù)中涉及到多個(gè)表的數(shù)據(jù)進(jìn)行數(shù)據(jù)分析。

2. 詳述

既然要連接MySQL數(shù)據(jù)庫(kù),那么就要先準(zhǔn)備數(shù)據(jù)了。在MySQL創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)chinese_retail_data,在數(shù)據(jù)庫(kù)中創(chuàng)建兩張表customers和orders,并且插入數(shù)據(jù)。這里模擬的是電商系統(tǒng)重點(diǎn)用戶表和訂單表。具體的SQL語(yǔ)句如下所示:

-- 創(chuàng)建數(shù)據(jù)庫(kù)
CREATE DATABASE IF NOT EXISTS chinese_retail_data;
USE chinese_retail_data;

-- 創(chuàng)建客戶表 (主表)
CREATE TABLE customers (
    customer_id INT PRIMARY KEY AUTO_INCREMENT,
    customer_name VARCHAR(100) NOT NULL,
    gender VARCHAR(10) NOT NULL,
    age_group VARCHAR(20) NOT NULL,
    city VARCHAR(50) NOT NULL,
    membership_level VARCHAR(20) DEFAULT '普通會(huì)員',
    registration_date DATE NOT NULL
);

-- 創(chuàng)建訂單表 (從表,通過customer_id關(guān)聯(lián))
CREATE TABLE orders (
    order_id INT PRIMARY KEY AUTO_INCREMENT,
    customer_id INT,
    product_name VARCHAR(100) NOT NULL,
    category VARCHAR(50) NOT NULL,
    quantity INT NOT NULL,
    unit_price DECIMAL(10,2) NOT NULL,
    order_date DATE NOT NULL,
    payment_method VARCHAR(20) NOT NULL,
    delivery_status VARCHAR(20) NOT NULL,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

-- 插入客戶數(shù)據(jù)(字段值使用中文)
INSERT INTO customers (customer_name, gender, age_group, city, membership_level, registration_date) VALUES
('張偉', '男', '25-34歲', '北京', '黃金會(huì)員', '2023-01-15'),
('李娜', '女', '35-44歲', '上海', '鉑金會(huì)員', '2022-03-20'),
('王強(qiáng)', '男', '18-24歲', '廣州', '普通會(huì)員', '2024-01-05'),
('陳靜', '女', '45-54歲', '深圳', '黃金會(huì)員', '2023-06-12'),
('劉洋', '男', '25-34歲', '杭州', '普通會(huì)員', '2024-02-18'),
('趙敏', '女', '35-44歲', '成都', '鉑金會(huì)員', '2022-11-30'),
('孫浩', '男', '18-24歲', '南京', '普通會(huì)員', '2024-03-08'),
('周芳', '女', '45-54歲', '武漢', '黃金會(huì)員', '2023-09-25');

-- 插入訂單數(shù)據(jù)(字段值使用中文,關(guān)聯(lián)customer_id)
INSERT INTO orders (customer_id, product_name, category, quantity, unit_price, order_date, payment_method, delivery_status) VALUES
(1, '華為手機(jī)', '電子產(chǎn)品', 1, 5999.00, '2024-04-01', '支付寶', '已送達(dá)'),
(2, '美的空調(diào)', '家用電器', 1, 3200.00, '2024-04-03', '微信支付', '已送達(dá)'),
(3, '李寧運(yùn)動(dòng)鞋', '服飾鞋帽', 2, 499.00, '2024-04-05', '信用卡', '運(yùn)輸中'),
(1, '小米手環(huán)', '電子產(chǎn)品', 1, 299.00, '2024-04-08', '支付寶', '已送達(dá)'),
(4, '格力冰箱', '家用電器', 1, 4800.00, '2024-04-10', '微信支付', '已送達(dá)'),
(5, '耐克T恤', '服飾鞋帽', 3, 199.00, '2024-04-12', '支付寶', '已送達(dá)'),
(2, '蘋果平板', '電子產(chǎn)品', 1, 3899.00, '2024-04-15', '微信支付', '已送達(dá)'),
(6, '海爾洗衣機(jī)', '家用電器', 1, 2800.00, '2024-04-18', '信用卡', '已送達(dá)'),
(7, '阿迪達(dá)斯運(yùn)動(dòng)褲', '服飾鞋帽', 1, 599.00, '2024-04-20', '支付寶', '運(yùn)輸中'),
(1, '戴爾筆記本', '電子產(chǎn)品', 1, 7999.00, '2024-04-25', '微信支付', '已送達(dá)'),
(8, '西門子烤箱', '家用電器', 1, 2200.00, '2024-04-28', '信用卡', '已送達(dá)'),
(3, '優(yōu)衣庫(kù)襯衫', '服飾鞋帽', 4, 199.00, '2024-05-01', '支付寶', '已送達(dá)'),
(4, 'OPPO手機(jī)', '電子產(chǎn)品', 1, 2999.00, '2024-05-05', '微信支付', '已送達(dá)'),
(5, '彪馬運(yùn)動(dòng)鞋', '服飾鞋帽', 1, 699.00, '2024-05-08', '信用卡', '運(yùn)輸中'),
(2, '索尼耳機(jī)', '電子產(chǎn)品', 2, 899.00, '2024-05-12', '支付寶', '已送達(dá)');

然后準(zhǔn)備PandasAI的環(huán)境。注意默認(rèn)的Python環(huán)境pip安裝的可能仍然是2.X版本,不過在使用PandasAI官方文檔推薦使用Poetry之后,就可以pip安裝3.0了。

最后給出具體的Python腳本:

import pandasai
from pandasai_litellm import LiteLLM

llm_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"
llm_key = "sk-xxxxx"
llm_model_name = "deepseek-r1"

mysql_host = "127.0.0.1"
mysql_port = 3306
mysql_user = "root"
mysql_password = "test"

def init_dataset(table_names):
    pandasai.create(
        path = table_names[0],
        description = "電商系統(tǒng)客戶的基本信息,包括個(gè)人屬性、地理位置和會(huì)員等級(jí)等靜態(tài)特征。",
        source={
            "type": "mysql",
            "connection": {
                "host": mysql_host,
                "port": mysql_port,
                "user": mysql_user,           
                "password": mysql_password,
                "database": "chinese_retail_data"
            },
            "table": "customers",            
        },
        columns = [
            {"name": "customer_id", "type": "integer", "description": "客戶的唯一標(biāo)識(shí)符,用于關(guān)聯(lián)訂單數(shù)據(jù)。"},
            {"name": "customer_name", "type": "string", "description": "客戶的姓名,用于識(shí)別和溝通。"},
            {"name": "gender", "type": "string", "description": "客戶的性別,用于人口統(tǒng)計(jì)分析。"},
            {"name": "age_group", "type": "string", "description": "客戶所屬的年齡段,用于年齡相關(guān)的市場(chǎng)細(xì)分。"},
            {"name": "city", "type": "string", "description": "戶所在的城市,用于地域性銷售分析。"},
            {"name": "membership_level", "type": "string", "description": "客戶的會(huì)員等級(jí),反映客戶價(jià)值和忠誠(chéng)度。"},
            {"name": "registration_date", "type": "datetime", "description": "客戶的注冊(cè)日期,用于計(jì)算客戶生命周期。"},
        ]
    )

    pandasai.create(
        path = table_names[1],
        description = "電商系統(tǒng)客戶的訂單交易詳情,包括購(gòu)買的商品、數(shù)量、價(jià)格、時(shí)間和狀態(tài)等動(dòng)態(tài)行為。",
        source={
            "type": "mysql",
            "connection": {
                "host": mysql_host,
                "port": mysql_port,
                "user": mysql_user,
                "password": mysql_password,
                "database": "chinese_retail_data"
            },
            "table": "orders",
        },
        columns = [
            {"name": "order_id", "type": "integer", "description": "訂單的唯一標(biāo)識(shí)符,用于追蹤和管理訂單。"},
            {"name": "customer_id", "type": "integer", "description": "關(guān)聯(lián)到客戶的外鍵,建立與客戶表的聯(lián)系。"},
            {"name": "product_name", "type": "string", "description": "所購(gòu)商品的名稱,用于產(chǎn)品銷售分析。"},
            {"name": "category", "type": "string", "description": "商品所屬的類別,用于分類統(tǒng)計(jì)和趨勢(shì)分析。"},
            {"name": "quantity", "type": "integer", "description": "購(gòu)買的商品數(shù)量,影響總銷售額和庫(kù)存。"},
            {"name": "unit_price", "type": "float", "description": "商品的單價(jià),用于計(jì)算訂單金額和利潤(rùn)。"},
            {"name": "order_date", "type": "datetime", "description": "訂單創(chuàng)建的日期,用于時(shí)間序列和趨勢(shì)分析。"},
            {"name": "payment_method", "type": "string", "description": "客戶使用的支付方式,反映支付偏好。"},
            {"name": "delivery_status", "type": "string", "description": "訂單的配送狀態(tài),用于監(jiān)控物流和客戶滿意度。"},
        ]
    )

def ai_chat(table_names):
    llm = LiteLLM(model=llm_model_name, api_base=llm_url, api_key=llm_key, custom_llm_provider="openai", temperature=0.0, seed=10080)

    pandasai.config.set({"llm": llm, "save_logs": True, "verbose": False, "max_retries": 3})

    # 加載所有相關(guān)的表   
    tables = [pandasai.load(name) for name in table_names]

    chat_content = "統(tǒng)計(jì)一下目前電商系統(tǒng)中會(huì)員類型的占比,以及每種會(huì)員類型購(gòu)買商品的數(shù)額在銷售額總量的占比。請(qǐng)使用中文回答。"

    result = pandasai.chat(chat_content, *tables)

    print(result)

if __name__ == "__main__":    
    table_names = ["example/ecommerce-customers", "example/ecommerce-orders"]

    #init_dataset(table_names) #初始化只能一次

    ai_chat(table_names)

有以下幾點(diǎn)需要注意:

1.PandasAI 3.0比PandasAI 2.X方便的一點(diǎn)可以不用自定義LLM類來連接自定義的大模型了,使用內(nèi)置的LiteLLM就可以了。另外PandasAI官方還提供大模型可以使用,不過需要申請(qǐng)key。這里筆者連接的還是阿里云百煉平臺(tái)的DeepSeek。

2.PandasAI設(shè)計(jì)的數(shù)據(jù)接口筆者覺得有點(diǎn)奇怪,主要有兩點(diǎn):

  • pandasai.create創(chuàng)建的表格數(shù)據(jù)只能使用一次,如果數(shù)據(jù)存在第二次再調(diào)用這個(gè)函數(shù)(在init_dataset函數(shù)中)就會(huì)報(bào)錯(cuò)。
  • PandasAI對(duì)創(chuàng)建的數(shù)據(jù)集名稱還有要求,比如多個(gè)單詞必須以"-"進(jìn)行連接。

3.PandasAI官網(wǎng)創(chuàng)建MySQL數(shù)據(jù)集的案例代碼是:

sql_table = pai.create(
    path="example/mysql-dataset",
    description="Heart disease dataset from MySQL database",
    source={
        "type": "mysql",
        "connection": {
            "host": "database.example.com",
            "port": 3306,
            "user": "${DB_USER}",
            "password": "${DB_PASSWORD}",
            "database": "medical_data"
        },
        "table": "heart_data",
        "columns": [
            {"name": "Age", "type": "integer", "description": "Age of the patient in years"},
            {"name": "Sex", "type": "string", "description": "Gender of the patient (M = male, F = female)"},
            {"name": "ChestPainType", "type": "string", "description": "Type of chest pain (ATA, NAP, ASY, TA)"},
            {"name": "RestingBP", "type": "integer", "description": "Resting blood pressure in mm Hg"},
            {"name": "Cholesterol", "type": "integer", "description": "Serum cholesterol in mg/dl"},
            {"name": "FastingBS", "type": "integer", "description": "Fasting blood sugar > 120 mg/dl (1 = true, 0 = false)"},
            {"name": "RestingECG", "type": "string", "description": "Resting electrocardiogram results (Normal, ST, LVH)"},
            {"name": "MaxHR", "type": "integer", "description": "Maximum heart rate achieved"},
            {"name": "ExerciseAngina", "type": "string", "description": "Exercise-induced angina (Y = yes, N = no)"},
            {"name": "Oldpeak", "type": "float", "description": "ST depression induced by exercise relative to rest"},
            {"name": "ST_Slope", "type": "string", "description": "Slope of the peak exercise ST segment (Up, Flat, Down)"},
            {"name": "HeartDisease", "type": "integer", "description": "Heart disease diagnosis (1 = present, 0 = absent)"}
        ]
    }
)

但是筆者這里嘗試的正確的用法是:

pandasai.create(
    path = table_names[0],
    description = "電商系統(tǒng)客戶的基本信息,包括個(gè)人屬性、地理位置和會(huì)員等級(jí)等靜態(tài)特征。",
    source={
        "type": "mysql",
        "connection": {
            "host": mysql_host,
            "port": mysql_port,
            "user": mysql_user,           
            "password": mysql_password,
            "database": "chinese_retail_data"
        },
        "table": "customers",            
    },
    columns = [
        {"name": "customer_id", "type": "integer", "description": "客戶的唯一標(biāo)識(shí)符,用于關(guān)聯(lián)訂單數(shù)據(jù)。"},
        {"name": "customer_name", "type": "string", "description": "客戶的姓名,用于識(shí)別和溝通。"},
        {"name": "gender", "type": "string", "description": "客戶的性別,用于人口統(tǒng)計(jì)分析。"},
        {"name": "age_group", "type": "string", "description": "客戶所屬的年齡段,用于年齡相關(guān)的市場(chǎng)細(xì)分。"},
        {"name": "city", "type": "string", "description": "戶所在的城市,用于地域性銷售分析。"},
        {"name": "membership_level", "type": "string", "description": "客戶的會(huì)員等級(jí),反映客戶價(jià)值和忠誠(chéng)度。"},
        {"name": "registration_date", "type": "datetime", "description": "客戶的注冊(cè)日期,用于計(jì)算客戶生命周期。"},
    ]
)

關(guān)鍵不同點(diǎn)就在于columns屬性值的位置。使用前者實(shí)際上是會(huì)丟失表格字段描述的。表格字段描述非常重要,PandasAI會(huì)將其傳遞給LLM來理解表格數(shù)據(jù)。如果創(chuàng)建成功的話,可以在Python腳本所在目錄的datasets文件夾中,找到創(chuàng)建好的.yaml文件,其中有表格數(shù)據(jù)的字段表述值:

3. 結(jié)果

最終運(yùn)行結(jié)果如下所示:

membership_level  會(huì)員占比(%)  銷售額占比(%)
0             普通會(huì)員     37.5      9.30
1             鉑金會(huì)員     25.0     29.48
2             黃金會(huì)員     37.5     61.23

本例中還有一點(diǎn)值得注意的是這里進(jìn)行的數(shù)據(jù)分析是跨表數(shù)據(jù)分析,而不是像《PandasAI連接LLM進(jìn)行智能數(shù)據(jù)分析》中那樣使用的是單表。其實(shí)這就是個(gè)很有趣的問題,我們都知道業(yè)務(wù)系統(tǒng)的核心就是CURD,那么如果跨表查詢可以實(shí)現(xiàn),是不是意味著以后就可以通過自然語(yǔ)言來進(jìn)行業(yè)務(wù)呢?現(xiàn)在語(yǔ)音的正確識(shí)別率也不低,通過語(yǔ)言來進(jìn)行業(yè)務(wù)操作也不難吧。

到此這篇關(guān)于淺析PandasAI連接LLM對(duì)MySQL數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)分析的文章就介紹到這了,更多相關(guān)PandasAI MySQL數(shù)據(jù)分析內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 在Python函數(shù)中輸入任意數(shù)量參數(shù)的實(shí)例

    在Python函數(shù)中輸入任意數(shù)量參數(shù)的實(shí)例

    今天小編就為大家分享一篇在Python函數(shù)中輸入任意數(shù)量參數(shù)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • tensorflow之并行讀入數(shù)據(jù)詳解

    tensorflow之并行讀入數(shù)據(jù)詳解

    今天小編就為大家分享一篇tensorflow之并行讀入數(shù)據(jù)詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • python Cartopy的基礎(chǔ)使用詳解

    python Cartopy的基礎(chǔ)使用詳解

    這篇文章主要介紹了python Cartopy的基礎(chǔ)使用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • Python加密方法小結(jié)【md5,base64,sha1】

    Python加密方法小結(jié)【md5,base64,sha1】

    這篇文章主要介紹了Python加密方法,結(jié)合實(shí)例形式總結(jié)分析了md5,base64,sha1的簡(jiǎn)單加密方法,需要的朋友可以參考下
    2017-07-07
  • Python?seaborn?barplot畫圖案例

    Python?seaborn?barplot畫圖案例

    這篇文章主要介紹了Python?seaborn?barplot畫圖案例,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-07-07
  • pandas實(shí)現(xiàn)DataFrame顯示最大行列,不省略顯示實(shí)例

    pandas實(shí)現(xiàn)DataFrame顯示最大行列,不省略顯示實(shí)例

    今天小編就為大家分享一篇pandas實(shí)現(xiàn)DataFrame顯示最大行列,不省略顯示實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • python selenium如何防止被瀏覽器檢測(cè)

    python selenium如何防止被瀏覽器檢測(cè)

    隨著瀏覽器安全策略的不斷完善,如何有效地防止Selenium在自動(dòng)化測(cè)試過程中被瀏覽器檢測(cè)到,成為了開發(fā)者們面臨的一個(gè)新的挑戰(zhàn),下面小編來和大家探討一下Selenium在防止被瀏覽器檢測(cè)方面的技巧吧
    2025-05-05
  • Django之使用celery和NGINX生成靜態(tài)頁(yè)面實(shí)現(xiàn)性能優(yōu)化

    Django之使用celery和NGINX生成靜態(tài)頁(yè)面實(shí)現(xiàn)性能優(yōu)化

    這篇文章主要介紹了Django之使用celery和NGINX生成靜態(tài)頁(yè)面實(shí)現(xiàn)性能優(yōu)化,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • Python中的print()?函數(shù)和格式化操作方法

    Python中的print()?函數(shù)和格式化操作方法

    ?print()?函數(shù)和字符串格式化是每個(gè)Python開發(fā)者必須掌握的基礎(chǔ)技能,從簡(jiǎn)單的%?操作符到強(qiáng)大的f-string,Python一直在進(jìn)化,讓我們的編碼工作變得更加愉快和高效,本文介紹Python中的print()函數(shù)和格式化操作方法,感興趣的朋友一起看看吧
    2025-10-10
  • PyTorch基礎(chǔ)之torch.nn.CrossEntropyLoss交叉熵?fù)p失

    PyTorch基礎(chǔ)之torch.nn.CrossEntropyLoss交叉熵?fù)p失

    這篇文章主要介紹了PyTorch基礎(chǔ)之torch.nn.CrossEntropyLoss交叉熵?fù)p失講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-02-02

最新評(píng)論

进贤县| 伊宁市| 濮阳市| 阿克| 普定县| 黄山市| 马龙县| 象山县| 科尔| 湖北省| 吴旗县| 溧水县| 内黄县| 太原市| 上虞市| 新乡县| 常德市| 庄浪县| 泰和县| 石门县| 年辖:市辖区| 上杭县| 合山市| 绥德县| 正宁县| 吉木萨尔县| 无棣县| 原阳县| 开平市| 惠州市| 乐至县| 息烽县| 大方县| 新郑市| 阿城市| 盘锦市| 东乡族自治县| 新竹市| 荣昌县| 南城县| 玛纳斯县|