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

使用Pandas获取牛油果最高均价时,输出地区名带行号和类型的问题

解决牛油果最高均价地区输出问题

问题原因

你的代码中,region['region'] 返回的是一个 pandas Series 对象,而非单个字符串值。当直接将其插入格式化字符串时,会输出该 Series 的完整表示(包含行索引和数据类型信息),这就是出现多余行号和 dtype: object 的原因。

修正后的代码

只需修改获取地区名称的逻辑,提取出标量值即可:

import pandas as pd

avocadoesDB = pd.read_csv("avocado.csv")
# 注:pd.read_csv 已返回 DataFrame,无需再次转换为 DataFrame
avocadoesDB = avocadoesDB[['AveragePrice', 'type', 'year', 'region']]

regions = avocadoesDB[['AveragePrice', 'region']]
regionMax = max(regions['AveragePrice'])
# 直接提取第一个匹配的地区名称(假设唯一)
region_name = regions.loc[regions['AveragePrice'] == regionMax, 'region'].iloc[0]

print(f"The highest average price for both types of potatoes is ${regionMax} from {region_name}.")

额外说明

  • 若存在多个地区拥有相同的最高均价,可改用以下方式输出所有地区:
    region_names = regions.loc[regions['AveragePrice'] == regionMax, 'region'].tolist()
    print(f"The highest average price for both types of potatoes is ${regionMax} from {', '.join(region_names)}.")
    
  • 代码中的 "potatoes" 是笔误,应为 "avocados",可根据需要修正。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:35:37