Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在这里替换for循环?_Python_Function_Performance - Fatal编程技术网

Python 如何在这里替换for循环?

Python 如何在这里替换for循环?,python,function,performance,Python,Function,Performance,我在python中创建了这个函数,用于为产品数据集生成不同的价格组合。因此,如果一个产品的价格是10美元,那么不同的可能价格将是[10,11,12,13,14,15]。 例如: 我的职能: def price_comb(df): K= [0,1,2,3,4,5] final_df = pd.DataFrame() c=0 for j in K: c+=1 print('K count=' + str(c)) for

我在python中创建了这个函数,用于为产品数据集生成不同的价格组合。因此,如果一个产品的价格是10美元,那么不同的可能价格将是[10,11,12,13,14,15]。 例如:

我的职能:

def price_comb(df):
    K= [0,1,2,3,4,5]
    final_df = pd.DataFrame()
    c=0
    for j in K:
        c+=1
        print('K count=' + str(c))
        for index,i in df.iterrows():
            if (i['price_per_tire']<=100):
                i['price_per_tire'] = i['price_per_tire'] + 1*j
            elif ((i['price_per_tire']>100) & (i['price_per_tire']<200)):
                i['price_per_tire'] = i['price_per_tire'] + 2*j
            elif ((i['price_per_tire']>200) & (i['price_per_tire']<300)):
                i['price_per_tire'] = i['price_per_tire'] + 3*j
            elif i['price_per_tire']>=300:
                i['price_per_tire'] = i['price_per_tire'] + 5*j
            final_df = final_df.append(i)
    return final_df 

然而,对于545k行数据集,它需要花费大量的时间(最多2天)。我正试图找到更快执行的方法。请提供代码的工作版本,此处不清楚每个轮胎的价格来源

这个算法是一个O(N2),所以需要做很多改进

第一个建议是避免使用numpy或pandas进行for循环,尝试使用向量方法解决您的问题。 这意味着可以使用掩码技术重构内部循环

for x in df.iterrows():
   if x[fld] < limit:
      x[fld] = f(x[fld])

df.iterrows()中x的
:
如果x[fld]<极限:
x[fld]=f(x[fld])
可以重构:

mask = df[fld] < limit
df[fld] = f(df[fld])   # if f(unction) can work in vectorial
df[fld] = df[fld].map(f)  # Rolling version but slower
mask=df[fld]
通过这种方法,您可以将代码加速到惊人的速度


另一点是df.append不是一个好的实践,进行内联更改将更有效。您必须在主循环之前创建所有所需的列,以便分配所有所需的空间。

。它们总是很慢,因为它们无法矢量化。首先,请清理您的代码,以便更易于阅读。使用有意义的变量名和清晰的描述。你的逻辑在200美元时有差距。您正在使用位逻辑(&)而不是布尔逻辑(and),并且。。。好的,这真的属于StackExchange.CodeReview,而不是堆栈溢出。总的来说,我建议您学习有关PANDAS、布尔表达式和dict访问的教程,以便您的代码更高效、更易于阅读。还要学习
+=
操作符。你为什么多次打电话给
i['price\u per\u tire']
?你有什么建议可以让我做得更好吗?谢谢你指出,我已经做了更正。现在应该可以用了。我不明白fld是什么。你能给我的代码举个例子来澄清一下吗。提前感谢Glauchi Rohan,fld是一个列的名称,这是一个使用掩码的工作示例:mask_减_100=df['price_per_tire']感谢glauco,这很有帮助
for x in df.iterrows():
   if x[fld] < limit:
      x[fld] = f(x[fld])

mask = df[fld] < limit
df[fld] = f(df[fld])   # if f(unction) can work in vectorial
df[fld] = df[fld].map(f)  # Rolling version but slower