为了账号安全,请及时绑定邮箱和手机立即绑定

计算 Pandas Dataframe 中每种产品的平均价格

计算 Pandas Dataframe 中每种产品的平均价格

陪伴而非守候 2023-08-08 15:36:12
我有一个如下所示的数据框:import pandas as pdZ = pd.DataFrame({'Product': ['Apple', 'Apple', 'Apple', 'Orange', 'Orange], 'Selling Price': [1.1, 1.2, 1.3, 2.1, 2.2]})有数千种独特的产品和数亿的售价。我如何有效地报告每种独特产品的平均售价?Result = pd.DataFrame({'Product': ['Apple', 'Orange'], 'Average Selling Price': [1.2, 2.15]})挑战在于数据存储在数百个不同的 .csv 文件中(文件名存储在列表中files),我无法同时将其加载到我的环境中。所以我会做类似的事情for i in files:     X = pd.read_csv(i)     # add unique products to the data frame Z     # add the sum of their selling prices to Z     # add the number of times the product was sold# for each unique product, divide the sum of selling prices by the number of times that product was sold感谢您的任何帮助,您可以提供!
查看完整描述

1 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

final_df = pd.DataFrame()

for i in files:

    X = pd.read_csv(i)

    X_agg = X.groupby('Product', as_index=False).agg({'Selling Price':['count', 'sum']})

    X_agg.columns = ['Product', 'sale_count', 'selling_sum']

    final_df = pd.concat([final_df, X_agg])

    final_df = final_df.groupby('Product', as_index=False).agg({'sale_count':'sum', 'selling_sum':'sum'})


查看完整回答
反对 回复 2023-08-08
  • 1 回答
  • 0 关注
  • 175 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信