我有一些嵌套的 for 回圈可以作業,并且會附加一個分數串列。這目前運行非常緩慢。有沒有辦法輕松優化它并讓它運行得更快?
scores = []
for day in range(0,len(date)):
x = []
for entry in range(0,len(df_new)):
if df_new['timestamp(America/New_York)'].dt.strftime('%Y-%m-%d').iloc[entry] == date[day]:
for times in range(0,len(time)):
if df_new['timestamp(America/New_York)'].dt.strftime('%H:%M:%S').iloc[entry] == time[times]:
x.append(df_new['score'].iloc[entry])
scores.append(x)
!這里也是資料框的圖片。] 1
uj5u.com熱心網友回復:
您當前df_new['timestamp(America/New_York)'].dt.strftime('%Y-%m-%d')在嵌套回圈中多次呼叫該方法,這意味著您將不得不多次獲取該資料。
您可以做的是df_new['timestamp(America/New_York)'].dt.strftime('%Y-%m-%d')在回圈之前將值存盤在變數中,然后只呼叫該變數,因為它現在包含您需要的資料。
像這樣的東西
data_frame = df_new['timestamp(America/New_York)'].dt.strftime('%Y-%m-%d')
for entry in range(0,len(df_new)):
if data_frame.iloc[entry] == date[day]:
for times in range(0,len(time)):
etc. etc.
不要認為它會改善太多,但至少有點!
uj5u.com熱心網友回復:
不需要回圈,您可以為每個條件創建兩個布爾掩碼,然后&在兩個掩碼之間使用索引原始資料幀。一個例子如下所示。
print(df)
ts score
0 2021-09-16 11:45:00 88.6
1 2021-09-16 11:48:00 92.3
2 2021-09-30 11:45:00 44.5
3 2021-09-30 12:45:00 55.4
print(dates)
['2021-09-16']
print(times)
['11:45:00', '11:48:00']
mask1 = df["ts"].dt.strftime('%Y-%m-%d').isin(dates)
mask2 = df["ts"].dt.strftime('%H:%M:%S').isin(times)
df.loc[mask1 & mask2]
ts score
0 2021-09-16 11:45:00 88.6
1 2021-09-16 11:48:00 92.3
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399466.html
標籤:Python 熊猫 matplotlib jupyter-笔记本 jupyter
上一篇:MatplotlibDeprecationWarning:tick1On函式在Matplotlib3.1中已棄用,并將在3.3中洗掉
