【发布时间】:2020-07-28 16:42:32
【问题描述】:
如何优化以下代码的速度并提高可读性?
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)
【问题讨论】:
-
我认为将其转换为 lambda 函数不是一个好主意。你应该优先考虑编写可读的代码。
-
lambda 函数只是语法糖——你的意思是
np.,vectorize? -
我想缩短执行时间。对此方向的任何帮助将不胜感激。
-
请提供最小的可重现代码。谢谢。
标签: python pandas numpy dataframe lambda