多个循环和函数速度较慢的替代方案

2024-09-29 06:29:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要计算不同场景的组合(表示为DF1、DF2和D3列),并通过下面3个for循环中的函数传递它们。该函数没有获取数组作为输入,因此我必须遍历行以逐个传递参数

然而,这变得非常缓慢,并且需要很长的时间(指数达到3000,乘以i,j,k的6*3*3)。 有什么办法可以简化这一点吗? 感谢您的帮助,因为我没有发现这样的示例需要通过行和循环

 count=0
  for index, row in DF.iterrows():
    print(index)
    for i in range(0,6):
      for j in range(0,3):
        for k in range(0,3):
          OUT.loc[index,count]=FUNCTION(DF1[index,k],DF2[index,i],DF3[index,j],row[col])
          count += 1 

编辑

函数设置为\u tmp,从这里获取(它不获取数据帧的列,因此我必须逐行传递数据):pythermalcomforthttps://github.com/CenterForTheBuiltEnvironment/pythermalcomfort/blob/master/examples/calc_set_tmp.py

DF1.head(3) 
    Temp    T10p    T90p
1   303.04935   302.04935   304.04935
236 303.57208   302.57208   304.57208
471 301.36523   300.36523   302.36523

DF2.head(3)
    Tmrt_1     Tmrt_2      Tmrt_3      Tmrt_4      Tmrt_5       Tmrt_6
1   25.80   23.52   21.91   25.63   23.51   21.97088
236 25.61   23.38   21.81   25.50   23.42   21.92352
471 24.91   22.76   21.23   24.81   22.78   21.31014

DF3.head(3)
WindSpeed   V10p    V90p
1   2.26    1.134   3.4030
236 1.66    0.831   2.4958
471 1.83    0.915   2.7475

谢谢你的帮助


Tags: 函数inforindexcount场景rangehead
2条回答

也许你需要重新考虑你的方法。有时,开箱思考会导致我们找到一个时间复杂度为O(1)的解决方案。如果你给出你最初的问题,例如,为什么你需要组合,也许,那么我可以帮助你。也许你根本不需要组合

import pandas as pd
import random
import time
import numpy as np
import itertools as it

def f(a,b,c,d):
    return int(a+b+c+d)

df1 = pd.DataFrame(np.random.rand(100,3))
df2 = pd.DataFrame(np.random.rand(100,6))
df3 = pd.DataFrame(np.random.rand(100,3))
df = pd.DataFrame(np.random.rand(100,1))
out = pd.DataFrame()
#till here we created the random data frames
start = time.time()
count = 0
for index,row in df.iterrows():
    for i in range(6):
        for j in range(3):
            for k in range(3):
                out.loc[index, count] = f(df1.at[index,k], df2.at[index,i], df3.at[index,j], row[0])
                count+=1
print(time.time()-start)
# for 100 rows time is +- 11 seconds
start1 = time.time()

out1 = pd.DataFrame()
for i,r in df.iterrows():
    tmp = []
    tmp.append(list(df1.loc[i])) #add each row as a list to tmp
    tmp.append(list(df2.loc[i]))
    tmp.append(list(df3.loc[i]))
    tmp.append([r[0]])
    all_comb = list(it.product(*tmp)) # create a list of all possible combinations from tmp
    count = 0
    for comb in all_comb:
        out1.loc[i,count] = f(*comb) #send combinations to same function
        count+=1

print(time.time()-start1)
#for 100 rows time is 0.8 seconds

print(len(out))
print(len(out1))

相关问题 更多 >