版本v3目前处于测试阶段。本文档反映了正在开发中的功能和特性,在最终发布前可能会有所变更。

聊天

.chat() 方法是 PandasAI 的核心功能,可实现与数据的自然语言交互。它允许您:

  • 使用自然语言查询您的数据
  • 生成可视化图表和统计分析
  • 同时处理多个DataFrames

如需更基于用户界面的数据分析体验,请查看我们的Data Platform

基础用法

import pandasai as pai

df_customers = pai.load("company/customers")

response = df_customers.chat("Which are our top 5 customers?")

与多个DataFrame进行对话

import pandasai as pai

df_customers = pai.load("company/customers")
df_orders = pai.load("company/orders")
df_products = pai.load("company/products")

response = pai.chat('Who are our top 5 customers and what products do they buy most frequently?', df_customers, df_orders, df_products)

可用的输出格式

PandasAI支持多种响应输出格式,每种格式都旨在有效处理不同类型的数据和分析结果。本文档概述了可用的输出格式及其使用场景。

数据框响应

当结果为pandas DataFrame时使用。此格式可保留数据的表格结构,并支持进一步的数据操作。

图表响应

处理可视化输出,支持数据分析过程中生成的各种图表类型。

字符串响应

以可读格式返回关于数据的文本响应、解释和洞察。

数值响应

专为数值输出设计的格式,通常用于计算、统计和指标分析。

错误响应

在分析过程中出现问题时提供结构化的错误信息。

使用说明

响应格式会根据执行的分析类型和输出性质自动确定。您无需显式指定格式——PandasAI会为结果选择最合适的呈现方式。

示例:

import pandasai as pai

df = pai.load("my-org/users")

response = df.chat("Who is the user with the highest age?") # Returns a String response
response = df.chat("How many users in total?") # Returns a Number response
response = df.chat("Show me the data") # Returns a DataFrame response
response = df.chat("Plot the distribution") # Returns a Chart response

响应类型详情

每种响应类型都针对特定使用场景设计:

  • 文本响应: 提供文本分析和解释
  • 数值响应: 返回计算得出的数值结果
  • DataFrame响应: 保留pandas DataFrames的结构和功能
  • 图表响应: 支持多种可视化格式和绘图库
  • 错误响应: 带有信息提示的结构化错误处理

响应系统具有可扩展性和类型安全性,确保输出根据其特定要求进行正确格式化与处理。

响应对象方法

响应对象提供了多种实用方法和属性来与结果进行交互:

值属性

默认情况下,当您打印响应对象时,它会自动返回其.value属性:

response = df.chat("What is the average age?")
print(response)  # Automatically calls response.value
# Output: The average age is 34.5 years

# For charts, printing will display the visualization
chart_response = df.chat("Plot age distribution")
print(chart_response)  # Displays the chart

生成的代码

你可以查看生成结果的代码:

response = df.chat("Calculate the correlation between age and salary")
print(response.last_code_executed)
# Output: df['age'].corr(df['salary'])

保存图表

对于图表响应,您可以将可视化结果保存到文件:

chart_response = df.chat("Create a scatter plot of age vs salary")
chart_response.save("scatter_plot.png")  # Saves the chart as PNG