TLDR:如何調整 for 回圈以獲得更快的執行時間:
import numpy as np
import pandas as pd
import time
np.random.seed(0)
# Given a DataFrame df and a row_index
df = pd.DataFrame(np.random.randint(0, 3, size=(30000, 50)))
target_row_index = 5
start = time.time()
target_row = df.loc[target_row_index]
result = []
# Method 1: Optimize this for-loop
for row in df.iterrows():
"""
Logic of calculating the variables check and score:
if the values for a specific column are 2 for both rows (row/target_row), it should add 1 to the score
if for one of the rows the value is 1 and for the other 2 for a specific column, it should subtract 1 from the score.
"""
check = row[1] target_row # row[1] takes 30 microseconds per call
score = np.sum(check == 4) - np.sum(check == 3) # np.sum takes 47 microseconds per call
result.append(score)
print(time.time()-start)
# Goal: Calculate the list result as efficient as possible
# Method 2: Optimize Apply
def add(a, b):
check = a b
return np.sum(check == 4) - np.sum(check == 3)
start = time.time()
q = df.apply(lambda row : add(row, target_row), axis = 1)
print(time.time()-start)
所以我有一個大小為 30'000 的資料框和這個資料框中的一個目標行,它具有給定的行索引。現在我想通過計算分數來將此行與資料集中的所有其他行進行比較。分數計算如下:
- 如果兩行的特定列的值均為 2,則應將分數加 1
- 如果其中一行的值為 1,而特定列的另一行的值為 2,則應從分數中減去 1。
結果就是我們剛剛計算的所有分數的串列。
由于我需要經常執行此代碼,因此我想對其性能進行優化。很感謝任何形式的幫助。
我已經閱讀了使用 Pandas 時的優化你可以推薦更多資源嗎?謝謝
uj5u.com熱心網友回復:
如果您愿意將您的陣列轉換df為NumPy陣列,NumPy那么有一些非常好的矢量化會有所幫助。我使用NumPy的代碼如下:
df = pd.DataFrame(np.random.randint(0, 3, size=(30000, 50)))
target_row_index = 5
start_time = time.time()
# Converting stuff to NumPy arrays
target_row = df.loc[target_row_index].to_numpy()
np_arr = df.to_numpy()
# Calculations
np_arr = target_row
check = np.sum(np_arr == 4, axis=1) - np.sum(np_arr == 3, axis=1)
result = list(check)
end_time = time.time()
print(end_time - start_time)
您的完整代碼(對我來說在 Google Colab 上)輸出時間為14.875332832336426 s,而NumPy上面的代碼輸出時間為0.018691539764404297 s,當然,result兩種情況下的串列都是相同的。
請注意,一般來說,如果您的計算是純數字的,那么NumPy實際上總是比回圈Pandas好。真正通過字串閃耀,當您需要列名和行名時,但對于純數字,由于矢量化,這是要走的路。forPandasNumPy
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/457947.html
上一篇:資料幀的條件操作
