本帖最后由 mrliu133 于 2021-8-24 20:12 编辑
下面是我的一个叫做revenue_data的DataFrame,我需要根据月份来判断总价格应该如何处理,要求是这样:如果月份是7、8月份,那么对应的总价格要除以30000,不是7、8月份,总价格要除以20000.我在想如何通过apply实现这个操作。求助各位大佬!!!
[td]arrival_date_month | hotel | total_price | 8 | 1 | City Hotel | 26.377266 | 9 | 1 | Resort Hotel | 12.437193 | 6 | 2 | City Hotel | 38.400599 | 7 | 2 | Resort Hotel | 18.932737 | 15 | 3 | Resort Hotel | 27.774822 | 14 | 3 | City Hotel | 54.811296 | 0 | 4 | City Hotel | 68.453941 | 1 | 4 | Resort Hotel | 36.497996 | 17 | 5 | Resort Hotel | 41.279494 | 16 | 5 | City Hotel | 78.440667 | 13 | 6 | Resort Hotel | 55.771113 | 12 | 6 | City Hotel | 73.355813 | 11 | 7 | Resort Hotel | 80.470650 | 10 | 7 | City Hotel | 56.180908 | 3 | 8 | Resort Hotel | 97.968554 | 2 | 8 | City Hotel | 65.881062 | 22 | 9 | City Hotel | 67.931298 | 23 | 9 | Resort Hotel | 49.247103 | 20 | 10 | City Hotel | 62.050656 | 21 | 10 | Resort Hotel | 30.790179 | 18 | 11 | City Hotel | 34.284156 | 19 | 11 | Resort Hotel | 17.405493 | 5 | 12 | Resort Hotel | 22.283578 | 4 | 12 | City Hotel | 32.068453 |
下面是两种不是通过apply实现目的的两种方法:
方法1:
[Python] 纯文本查看 复制代码 condition = (revenue_data.arrival_date_month==7)|(revenue_data.arrival_date_month==8)
revenue_data.loc[(revenue_data.arrival_date_month==7)|(revenue_data.arrival_date_month==8),"total_price"] /= 30000 # 转换成万欧元
revenue_data.loc[~(condition), "total_price"] = revenue_data.loc[~(condition), "total_price"] / 20000 # 转换成万欧元
revenue_data
方法2:
[Python] 纯文本查看 复制代码 for row in revenue_data.index:
if revenue_data.loc[row, "arrival_date_month"] == 7 or revenue_data.loc[row, "arrival_date_month"] == 8:
# print(revenue_data.loc[row, "total_price"])
revenue_data.loc[row, "total_price"] /= 30000
else:
revenue_data.loc[row, "total_price"] /= 20000
revenue_data
|