You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用seaborn.lmplot绘制行求和后的支出与收入散点回归图?

解决Seaborn lmplot的行求和与绘图问题

代码错误分析

你当前的代码存在三个核心问题:

  1. 错误使用sum():直接对列名字符串列表调用sum(),会把字符串拼接而非计算数值求和,完全不符合需求。
  2. 误用groupby():这里不需要分组聚合,而是要对每行的指定列进行求和,groupby()是用于分组统计的工具,不适用此场景。
  3. lmplot参数错误:sns.lmplot的x和y参数需要传入数据框中已存在的列名,而非变量对象。

正确实现步骤

要实现需求,只需在原数据框中新增两个行求和后的列,再传入lmplot即可:

  1. 计算Private Sector Expenditure和Public Sector Expenditure的行和,生成Total_Expenditure列
  2. 计算指定5个收入列的行和,生成Total_Revenue列
  3. 用这两个新列作为x、y轴绘制lmplot

完整代码示例

import seaborn as sns
import pandas as pd

# 假设df_final是你合并后的完整数据集
# 生成总支出列
df_final['Total_Expenditure'] = df_final[['Private Sector Expenditure', 'Public Sector Expenditure']].sum(axis=1)
# 生成总收入列
revenue_cols = ['Content Services Revenue', 'Hardware Revenue', 
                'IT Services Revenue', 'Software Revenue', 'Telecommunication Services Revenue']
df_final['Total_Revenue'] = df_final[revenue_cols].sum(axis=1)

# 绘制lmplot
sns.lmplot(data=df_final, x='Total_Expenditure', y='Total_Revenue')

补充说明

  • axis=1参数指定按行求和(默认axis=0是按列求和)
  • 新列会直接添加到原数据框中,后续绘图时直接传入列名字符串即可
  • 如果需要保留原数据框不被修改,可以使用df_final.copy()创建副本后再操作

内容的提问来源于stack exchange,提问作者Lim Ze Kai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 18:32:28