简体   繁体   English

优化执行速度,提高代码可读性

[英]Optimize the execution speed and improve the readability of code

How can I optimize the speed and improve readability for the following piece of code?如何优化以下代码的速度并提高可读性?

for j in range(len(Relevant_data)):
    for x in ['A', 'BB', 'BV', 'Cy', 'R','T']:
      if Relevant_data['Type'].iloc[j]==x:
           if Relevant_data['Amount'].iloc[j]>=np.asscalar(t.loc[x,0.0].values) and Relevant_data['Amount'].iloc[j]<np.asscalar(t.loc[x,0.25].values):
                Relevant_data['Bin'].iloc[j]="{} of {}".format("Bin1",x)
            elif Relevant_data['Amount'].iloc[j]>=np.asscalar(t.loc[x,0.25].values) and Relevant_data['Amount'].iloc[j]<np.asscalar(t.loc[x,0.50].values):
                Relevant_data['Bin'].iloc[j]="{} of {}".format("Bin2",x)
            elif Relevant_data['Amount'].iloc[j]>=np.asscalar(t.loc[x,0.50].values) and Relevant_data['Amount'].iloc[j]<np.asscalar(t.loc[x,0.75].values):
                Relevant_data['Bin'].iloc[j]="{} of {}".format("Bin3",x)
            elif Relevant_data['Amount'].iloc[j]>=np.asscalar(t.loc[x,0.75].values) and Relevant_data['Amount'].iloc[j]<=np.asscalar(t.loc[x,1.00].values):
                Relevant_data['Bin'].iloc[j]="{} of {}".format("Bin4",x)

I was able to increase the readability and improve the execution time of my code.我能够提高代码的可读性并缩短执行时间。

def analyze(Amount_R,Type_R): 
    if np.asscalar(t.loc[Type_R,0.0].values)<=Amount_R<np.asscalar(t.loc[Type_R,0.25].values):
        return "{} of {}".format("Bin1",Type_R)  
    if np.asscalar(t.loc[Type_R,0.25].values)<=Amount_R<np.asscalar(t.loc[Type_R,0.50].values):
        return "{} of {}".format("Bin2",Type_R) 
    if np.asscalar(t.loc[Type_R,0.50].values)<=Amount_R<np.asscalar(t.loc[Type_R,0.75].values):
        return "{} of {}".format("Bin3",Type_R)  
    if np.asscalar(t.loc[Type_R,0.75].values)<=Amount_R<=np.asscalar(t.loc[Type_R,1.00].values):
        return "{} of {}".format("Bin4",Type_R) 
Relevant_data_Retailers['Bin']=np.vectorize(analyze)(Relevant_data_Retailers['Transaction_Amount'],Relevant_data_Retailers['Transaction_Type'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM