Python 计算 CSV 数据集中不同类别的人均价格平均值
以下是使用Python语言解决这个问题的示例代码:
import csv
from collections import defaultdict
# 读取data.csv文件
data = []
with open('data.csv', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
header = next(reader) # 跳过头部行
for row in reader:
data.append(row)
# 统计不同餐厅种类的人均价格的平均值
category_prices = defaultdict(list)
for row in data:
category = row[1]
price = float(row[5])
category_prices[category].append(price)
average_category_prices = {}
for category, prices in category_prices.items():
average_price = sum(prices) / len(prices)
average_category_prices[category] = average_price
# 统计不同所在地区的人均价格的平均值
area_prices = defaultdict(list)
for row in data:
area = row[2]
price = float(row[5])
area_prices[area].append(price)
average_area_prices = {}
for area, prices in area_prices.items():
average_price = sum(prices) / len(prices)
average_area_prices[area] = average_price
# 统计不同评分的人均价格的平均值
rating_prices = defaultdict(list)
for row in data:
rating = float(row[6])
price = float(row[5])
rating_prices[rating].append(price)
average_rating_prices = {}
for rating, prices in rating_prices.items():
average_price = sum(prices) / len(prices)
average_rating_prices[rating] = average_price
# 输出结果
print('不同餐厅种类的人均价格的平均值:')
for category, average_price in average_category_prices.items():
print(f'{category}: {average_price}')
print('
不同所在地区的人均价格的平均值:')
for area, average_price in average_area_prices.items():
print(f'{area}: {average_price}')
print('
不同评分的人均价格的平均值:')
for rating, average_price in average_rating_prices.items():
print(f'{rating}: {average_price}')
你可以将上述代码保存为一个Python脚本,并确保在同一目录下有名为'data.csv'的CSV文件。然后运行脚本,你将获得输出结果,分别是不同餐厅种类的人均价格的平均值、不同所在地区的人均价格的平均值和不同评分的人均价格的平均值。
原文地址: https://www.cveoy.top/t/topic/dm61 著作权归作者所有。请勿转载和采集!