3 回答
TA贡献1772条经验 获得超8个赞
prices = {'Apple': 3, 'Cherry': 4, "Blueberry": 2}
df_week_sales = pd.DataFrame(prod_days,
index=["Mon","Tues","Wed","Thurs"],
columns=["Apple","Cherry","Blueberry"])
df_week_sales
Apple Cherry Blueberry
Mon 13 8 6
Tues 9 7 4
Wed 7 4 0
Thurs 15 6 3
转置:
df = df_week_sales.transpose()
Mon Tues Wed Thurs
Apple 13 9 7 15
Cherry 8 7 4 6
Blueberry 6 4 0 3
df['Total Revenue'] = [np.sum(df_week_sales[x]*prices[x]) for x in df_week_sales.columns]
df
Mon Tues Wed Thurs Total Revenue
Apple 13 9 7 15 132
Cherry 8 7 4 6 100
Blueberry 6 4 0 3 26
results = df.transpose()
Apple Cherry Blueberry
Mon 13 8 6
Tues 9 7 4
Wed 7 4 0
Thurs 15 6 3
Total Revenue 132 100 26
prod_prices = np.array([3,4,2])
results['Revenue'] = df_week_sales.dot(prod_prices)
Apple Cherry Blueberry Revenue
Mon 13 8 6 83.0
Tues 9 7 4 63.0
Wed 7 4 0 37.0
Thurs 15 6 3 75.0
Total Revenue 132 100 26 NaN
了解您的预期输出底部是 83、63、37,但这根本没有意义。83 = 13*3 + 8*4 + 6*2, 63 = 9*3 + 4*2, 同样对于37. 那么你的75. 数据不应该以该方向显示。所以我会坚持这种方式,这样对于表示数据来说更有意义。
TA贡献1827条经验 获得超9个赞
你可以尝试这样的事情:
prod_prices = np.array([3,4,2])
prod_days = np.array([[13,9,7,15],
[8,7,4,6],
[6,4,0,3]]).T
df_week_sales = pd.DataFrame(prod_days,
index=["Mon","Tues","Wed","Thurs"],
columns=["Apple","Cherry","Blueberry"])
# obtain the dot product
weekly_total = prod_days.dot(prod_prices)
# obtain the last row index of the data frame
jj = df_week_sales.shape[0]
# get the list to append to the data frame (need to be of the same column length)
df_week_sales.loc[jj] = weekly_total[:-1]
# rename the last index as desired
df_week_sales.rename(index={jj: 'Total Rev.($)'}, inplace=True)
df_week_sales
TA贡献1780条经验 获得超5个赞
您可以通过两行来实现此目的:
total_revenues = [df_week_sales[x].sum() for x in df_week_sales.columns]* prod_prices
output = pd.concat([df_week_sales, pd.DataFrame(total_revenues, index= df_week_sales.columns, columns = ['Total Revenue']).T])
输出
| | Apple | Cherry | Blueberry |
|:--------------|--------:|---------:|------------:|
| Mon | 13 | 8 | 6 |
| Tues | 9 | 7 | 4 |
| Wed | 7 | 4 | 0 |
| Thurs | 15 | 6 | 3 |
| Total Revenue | 132 | 100 | 26 |
添加回答
举报