如何有效地加快 Pandas 中我心爱代码的循环速度?

问题描述 投票:0回答:1

我一直在考虑使用多处理、cyton 和 numba 来加速我的代码的以下部分,但我就是无法弄清楚。我目前的结论是,我的代码无效,尽管我花了很多精力才使代码组合在一起并工作,但它根本无效,并且希望在此事上得到一些帮助:下面的代码运行大约需要 78 秒。

daten={'Contract':Contract_Name,'Product':Products,'Relative':Relative_Name,'Start_Date':Start_Dates,'End_Date':End_Dates,'Relevant':Relevant, 'Volume':Volumes,'Hours':Hours}
df=pd.DataFrame(daten)

Matrix=[]
pt = process_time()
df['Start_Date']=pd.to_datetime(df['Start_Date'])
df['End_Date']=pd.to_datetime(df['End_Date'])
h_prof['DeliveryStart']=pd.to_datetime(h_prof['DeliveryStart'])

for j in h_prof['DeliveryStart']:
        Vector=[]
        idx2=h_prof['DeliveryStart'].to_list().index(j)
        for i in df['Start_Date']:
            check=False
            idx=df['Start_Date'].to_list().index(i)
            if (i<=j)and(df['End_Date'][idx]>=j):
                if df['Product'][idx]=='bunn':
                    check=True
                elif h_prof['P_OP'][idx2]=='P':
                    check=True
            if check==True:
                Vector.append(1)
            else:
                Vector.append(0)
        Matrix.append(Vector)

提前非常感谢!

RangeIndex: 8760 entries, 0 to 8759
Data columns (total 10 columns):
 #   Column          Non-Null Count  Dtype         
---  ------          --------------  -----         
 0   Name            8760 non-null   object        
 1   Id              8760 non-null   int64         
 2   DeliveryStart   8760 non-null   datetime64[ns]
 3   DeliveryEnd     8760 non-null   datetime64[ns]
 4   Quantity        8760 non-null   float64       
 5   QuantityUnit    8760 non-null   object        
 6   Time            8760 non-null   object        
 7   Hour            8760 non-null   int64         
 8   WkDay           8760 non-null   int64         
 9   P_OP            8760 non-null   object        
dtypes: datetime64[ns](2), float64(1), int64(3), object(4)
memory usage: 684.5+ KB
python-3.x pandas for-loop multiprocessing numba
1个回答
0
投票

你似乎经常使用 .to_list() ,我建议只使用一次:

h_prof_start = h_prof['DeliveryStart'].to_list()

f_start = df['Start_Date'].to_list()"

并在查找 idx 和 idx2 时使用其余代码中的内容

© www.soinside.com 2019 - 2024. All rights reserved.