Python数据分析:计算餐厅数据的人均价格平均值

本教程将演示如何使用Python分析餐厅数据,并计算不同餐厅种类、所在地区和评分的人均价格平均值。

数据准备

假设我们有一个名为'data.csv'的文件,包含以下字段:

  • 餐厅名称* 餐厅种类* 所在地区* 餐厅地址* 点评数量* 人均价格* 评分

代码示例pythonimport csvfrom 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].replace('¥', '')) # 去除价格前面的符号 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].replace('¥', '')) # 去除价格前面的符号 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].replace('¥', '')) # 去除价格前面的符号 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}')

代码解释

  1. 使用csv模块读取'data.csv'文件。2. 使用defaultdict(list)创建字典,根据餐厅种类、所在地区和评分存储对应的人均价格列表。3. 遍历数据,将价格信息添加到对应的列表中。4. 计算每个类别的人均价格平均值,并将结果存储在新的字典中。5. 打印输出结果。

总结

本教程介绍了如何使用Python分析餐厅数据,并计算不同餐厅种类、所在地区和评分的人均价格平均值。你可以根据自己的需求修改代码,分析其他数据指标。

Python数据分析:计算餐厅数据的人均价格平均值

原文地址: http://www.cveoy.top/t/topic/dotr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录