我有一個如下所示的數據框: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'})
添加回答
舉報
0/150
提交
取消