最佳化的 pandas 迭代

撰寫高效的 Python 程式碼

Logan Thomas

Scientific Software Technical Trainer, Enthought

pandas 內部原理

  • 消除迴圈也適用於使用 pandas
  • pandas 建立在 NumPy 之上
    • 善用 NumPy 陣列的效率

alt="pandas 函式庫標誌疊在 NumPy 套件標誌、再疊在 Python 程式語言標誌上;從 pandas 到 NumPy 的連線標示 Builds on,從 NumPy 到 python 的連線也標示 Builds on"

撰寫高效的 Python 程式碼
print(baseball_df)
  Team League  Year   RS   RA   W    G  Playoffs
0  ARI     NL  2012  734  688  81  162         0
1  ATL     NL  2012  700  600  94  162         1
2  BAL     AL  2012  712  705  93  162         1
...
wins_np = baseball_df['W'].values

print(type(wins_np))
<class 'numpy.ndarray'>
print(wins_np)
[ 81  94  93 ...]
撰寫高效的 Python 程式碼

向量化的威力

  • 廣播(向量化)非常高效!
baseball_df['RS'].values - baseball_df['RA'].values
array([  46,  100,    7, ...,  188,  110, -117])
撰寫高效的 Python 程式碼

用陣列計算得失分差

run_diffs_np = baseball_df['RS'].values - baseball_df['RA'].values

baseball_df['RD'] = run_diffs_np print(baseball_df)
     Team League  Year   RS   RA    W    G  Playoffs   RD
0     ARI     NL  2012  734  688   81  162         0   46
1     ATL     NL  2012  700  600   94  162         1  100
2     BAL     AL  2012  712  705   93  162         1    7
3     BOS     AL  2012  734  806   69  162         0  -72
4     CHC     NL  2012  613  759   61  162         0 -146
...
撰寫高效的 Python 程式碼

方法比較

%%timeit
run_diffs_np = baseball_df['RS'].values - baseball_df['RA'].values

baseball_df['RD'] = run_diffs_np
124 µs ± 1.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
撰寫高效的 Python 程式碼

一起來練習吧!

撰寫高效的 Python 程式碼

Preparing Video For Download...