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

Python pandas绘制横向条形图遇SyntaxError语法错误求助

问题排查与修正

1. 语法错误核心原因

报错行的语法错误实际是前面创建DataFrame的代码存在语法缺失,导致Python解析到plot行时仍未完成前面的语句,触发SyntaxError:

  • DataFrame构造时,列表元组未闭合(缺少])
  • columns参数前缺少等号=
  • 变量名不匹配:计算时用spa_total_sale_price,但DataFrame里写的是spa_tot_sale_price(同理其他国家的变量)
  • 瑞士的总计计算错误:swi_totals = spa.sum(...)应该是swi.sum(...),复制时误用了西班牙的数据集
  • 绘图时列名不匹配:DataFrame里列名是CountryName,但plot里写的是CountryMake

2. 优化后的完整代码

import pandas as pd
import matplotlib.pyplot as plt  # 需导入matplotlib才能显示图表

# 读取数据
sales = pd.read_excel('Simplified Car Sales Data.xlsx')

# 计算西班牙总计
spa = sales[sales['CountryName'] == 'Spain']
spa_totals = spa.sum(axis=0, numeric_only=True)
spa_total_sale_price = round(spa_totals['SalePrice'])
spa_total_cost_price = round(spa_totals['CostPrice'])

# 计算瑞士总计(修正sum的数据集)
swi = sales[sales['CountryName'] == 'Switzerland']
swi_totals = swi.sum(axis=0, numeric_only=True)
swi_total_sale_price = round(swi_totals['SalePrice'])
swi_total_cost_price = round(swi_totals['CostPrice'])

# 计算德国总计
ger = sales[sales['CountryName'] == 'Germany']
ger_totals = ger.sum(axis=0, numeric_only=True)
ger_total_sale_price = round(ger_totals['SalePrice'])
ger_total_cost_price = round(ger_totals['CostPrice'])

# 修正DataFrame构造语法与变量名
totals = pd.DataFrame(
    [
        ('Spain', spa_total_sale_price, spa_total_cost_price),
        ('Switzerland', swi_total_sale_price, swi_total_cost_price),
        ('Germany', ger_total_sale_price, ger_total_cost_price)
    ],
    columns=['CountryName', 'Total Sales Price', 'Total Cost Price']
)

# 修正列名并绘制横向条形图
totals.plot(x='CountryName', y=['Total Sales Price', 'Total Cost Price'], kind='barh')
plt.title('Total Sales vs Cost by Country')  # 可选:添加标题
plt.show()  # 显示图表

3. 关键修正点说明

  • 补全DataFrame构造的括号与等号,确保语法合法
  • 修正瑞士总计的计算数据源,避免使用西班牙的sum结果
  • 统一变量名,避免拼写错误
  • 绘图时指定正确的x轴列名CountryName,并添加plt.show()确保图表显示
  • 导入matplotlib.pyplot模块,这是pandas绘图依赖的底层库,否则图表可能无法正常显示

内容的提问来源于stack exchange,提问作者Erica

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:55:25