Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.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 函数不循环所有值并在循环中的第一个值后停止_Python_Pandas_Function_Loops_For Loop - Fatal编程技术网

Python 函数不循环所有值并在循环中的第一个值后停止

Python 函数不循环所有值并在循环中的第一个值后停止,python,pandas,function,loops,for-loop,Python,Pandas,Function,Loops,For Loop,我是python新手,如果我不清楚,很抱歉。我试图创建一个循环,以获得不同产品的移动平均成本。我有一个数据集,自2019-01-01以来,每月有55000多种产品(我的产品id)及其成本。我试图创建一个函数,以获得最近3个月成本的移动平均值。到目前为止,我已经编写了这个函数,它可以工作,但只对一个产品运行,然后停止循环。我需要能够在列中所有唯一的产品ID上运行此函数。这就是我的数据集的样子 这将返回仅包含第一个产品ID的一行的数据帧,因此它可以正常工作,但会在第一个产品之后停止 提前感谢:)试

我是python新手,如果我不清楚,很抱歉。我试图创建一个循环,以获得不同产品的移动平均成本。我有一个数据集,自2019-01-01以来,每月有55000多种产品(我的产品id)及其成本。我试图创建一个函数,以获得最近3个月成本的移动平均值。到目前为止,我已经编写了这个函数,它可以工作,但只对一个产品运行,然后停止循环。我需要能够在列中所有唯一的产品ID上运行此函数。这就是我的数据集的样子

这将返回仅包含第一个产品ID的一行的数据帧,因此它可以正常工作,但会在第一个产品之后停止


提前感谢:)

试着像这样将
返回从循环中取出:

def abc(df_189):
    dfObj = pd.DataFrame(columns=['my_product_id', 'Cost'])
    my_products = df_189.my_product_id.unique()
    for i in my_products:
        df_test = df_189[df_189.my_product_id == i]
        
        Grouped=df_test.groupby('date')
        
        GetWeightAvg=lambda g: np.average(g['cost'], weights=g['quantity'])
        
        pr=Grouped.apply(GetWeightAvg).sort_index(ascending=False).head(3).mean()
        
        dfObj = dfObj.append({'my_product_id': i, 'Cost': pr}, ignore_index=True)
    return dfObj

我怎么会错过那个!非常感谢你,我的朋友
def abc(df_189):
    dfObj = pd.DataFrame(columns=['my_product_id', 'Cost'])
    my_products = df_189.my_product_id.unique()
    for i in my_products:
        df_test = df_189[df_189.my_product_id == i]
        
        Grouped=df_test.groupby('date')
        
        GetWeightAvg=lambda g: np.average(g['cost'], weights=g['quantity'])
        
        pr=Grouped.apply(GetWeightAvg).sort_index(ascending=False).head(3).mean()
        
        dfObj = dfObj.append({'my_product_id': i, 'Cost': pr}, ignore_index=True)
    return dfObj