对 Pandas Series 的向量化

使用 pandas 编写高效代码

Leonidas Souliotis

PhD Candidate

将 DataFrame 视为数组

GitHub 标志

使用 pandas 编写高效代码

如何进行 pandas 向量化

start_time = time.time()
poker[['R1', 'R2', 'R3', 'R4', 'R5']].sum(axis=1)
print("Time using pandas vectorization: {} sec".format(time.time() - start_time))
Time using pandas vectorization: 0.0026819705 sec
poker[['R1', 'R2', 'R3', 'R4', 'R5']].sum(axis=1).head()
|              |    | 
|--------------|----| 
| 0            | 47 | 
| 1            | 47 | 
| 2            | 47 | 
| 3            | 47 | 
| 4            | 47 | 
| dtype: int64 | -- |
使用 pandas 编写高效代码

与前述方法的比较

data_generator = data.iterrows()

start_time = time.time()
for index, value in data_generator:
        sum([value[1], value[3], value[5], value[7]])
print("Time using .iterrows(){} seconds" % (time.time() - start_time))
Results from the above operation calculated in 3.37918996 seconds
start_time = time.time()
data[['R1', 'R2', 'R3', 'R4', 'R5']].apply(lambda x: sum(x),axis=1)
print("Results from the above operation calculated in %s seconds" % (time.time() - start_time))
Results from the above operation calculated in 0.637711048 seconds
- 向量化 与 `.iterows()` 的差异:111,800.75%
- 向量化 与 `.apply()` 的差异:20,853%
使用 pandas 编写高效代码

开始练习!

使用 pandas 编写高效代码

Preparing Video For Download...