如果你不基于一些条件,而是可以在一行代码中将所有电力消耗数据应用于该价格:df ['energy_kwh'] * 28,类似这种。那么这个特定的操作就是矢量化操作的一个例子,它是在pandas中执行的最快方法。
但是如何将条件计算应用为pandas中的矢量化运算?
一个技巧是:根据你的条件,选择和分组DataFrame,然后对每个选定的组应用矢量化操作。
在下面代码中,我们将看到如何使用pandas的.isin()方法选择行,然后在矢量化操作中实现新特征的添加。在执行此操作之前,如果将date_time列设置为DataFrame的索引,会更方便:
- # 将date_time列设置为DataFrame的索引
- df.set_index('date_time', inplace=True)
- @timeit(repeat=3, number=100)
- def apply_tariff_isin(df):
- # 定义小时范围Boolean数组
- peak_hours = df.index.hour.isin(range(17, 24))
- shoulder_hours = df.index.hour.isin(range(7, 17))
- off_peak_hours = df.index.hour.isin(range(0, 7))
- # 使用上面apply_traffic函数中的定义
- df.loc[peak_hours, 'cost_cents'] = df.loc[peak_hours, 'energy_kwh'] * 28
- df.loc[shoulder_hours,'cost_cents'] = df.loc[shoulder_hours, 'energy_kwh'] * 20
- df.loc[off_peak_hours,'cost_cents'] = df.loc[off_peak_hours, 'energy_kwh'] * 12
我们来看一下结果如何。
- >>> apply_tariff_isin(df)
- Best of 3 trials with 100 function calls per trial:
- Function `apply_tariff_isin` ran in average of 0.010 seconds.
提示,上面.isin()方法返回的是一个布尔值数组,如下:
- [False, False, False, …, True, True, True]
布尔值标识了DataFrame索引datetimes是否落在了指定的小时范围内。然后把这些布尔数组传递给DataFrame的.loc,将获得一个与这些小时匹配的DataFrame切片。然后再将切片乘以适当的费率,这就是一种快速的矢量化操作了。
上面的方法完全取代了我们最开始自定义的函数apply_tariff(),代码大大减少,同时速度起飞。
运行时间比Pythonic的for循环快315倍,比iterrows快71倍,比apply快27倍!