【问题标题】:Best way to optimize nested for loop优化嵌套 for 循环的最佳方法
【发布时间】:2022-01-26 13:40:53
【问题描述】:

我有一些嵌套的 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)

!Here is a picture of the data frame as well. ]1

【问题讨论】:

  • 什么是time,也分享一个示例数据框作为代码
  • 将数据帧发布为代码而不是图片
  • 数据框正在通过 Excel 工作表导入。我使用'pd.read excel'来导入。

标签: python pandas matplotlib jupyter-notebook jupyter


【解决方案1】:

您当前在嵌套循环中多次调用方法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.

不要认为它会改善太多,但至少有点!

【讨论】:

    【解决方案2】:

    不需要循环,您可以为每个条件创建两个布尔掩码,然后在两个掩码之间使用 & 索引您的原始数据帧。下面是一个例子。

    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
    

    【讨论】:

      猜你喜欢
      • 2012-01-27
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多