[英]How do I efficiently loop over this dataframe and perform a function using inbuilt numpy or pandas?
[英]How do I efficiently map transformations over a pandas DataFrame
一个有趣的问题。
我有一个(大)表,看起来像:
交易日期(索引) | store_id | 部门编号 | 总收入 |
---|---|---|---|
'2020-01-01' | 商店1 | 水果 | 7.50 美元 |
'2020-01-01' | 商店2 | 水果 | 2.75 美元 |
'2020-01-01' | 商店1 | 蔬菜 | 47.50 美元 |
'2020-01-01' | 商店2 | 蔬菜 | 8.25 美元 |
... | ... | ... | ... |
我想根据store_id
和department_id
的值转换gross_revenue
列。
为了论证起见,假设我想将所有Store1
销售额增加 25%,将Veg
销售额增加 10%,将Fruit
销售额增加 75%(暂时不用担心订单)。
我希望用户能够写:
modifiers = {
'store_id': {
'Store1': lambda x: x*1.25
},
'department_id: {
'Veg' : lambda x: x*1.10,
'Fruit': lambda x: x*1.75
}
}
在 Pandas 中是否有执行此操作的高效方法?
作为基线,此代码有效:
from functools import reduce
ans = (table
.assign(gross_revenue = lambda x: x
.apply(lambda row: reduce(lambda x, f: f(x), [row['gross_revenue'],
modifiers.get(row['business_id'], lambda x: x),
modifiers.get(row['department_description'], lambda x: x)
]), axis=1)
)
)
但是,它需要将近 2 分钟(表格是 5-10m 行)。
有谁知道更快的方法?
提前致谢。
使用map
:
store_adjust = {'Store1': 1.25, 'Store10':1.3}
dep_adjust = {'Veg': 1.10, 'Fruit':1.75}
df['gross_revenue'] *= ( df['store_id'].map(store_adjust).fillna(1) *
df['department_id'].map(dep_adjust).fillna(1) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.