Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.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 是否有一种更简单的方法使用每N行数据帧进行计算?_Python_Pandas_Dataframe - Fatal编程技术网

Python 是否有一种更简单的方法使用每N行数据帧进行计算?

Python 是否有一种更简单的方法使用每N行数据帧进行计算?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据框,上面有国家名称和12月份产品的每日价格(注意:数据中没有周末/假日数据)。它看起来像这样: 对于每个州,我想计算产品价格的3天变化。我试着这样计算价格变化: days=3 for k in df["name"].unique(): test_df=df[df["name"]==k] test_df=test_df.reset_index(drop=True) test_df["3_chg"]=np.nan for i in r

我有一个数据框,上面有国家名称和12月份产品的每日价格(注意:数据中没有周末/假日数据)。它看起来像这样:


对于每个州,我想计算产品价格的3天变化。我试着这样计算价格变化:

days=3

for k in df["name"].unique():
      test_df=df[df["name"]==k]
      test_df=test_df.reset_index(drop=True)
      test_df["3_chg"]=np.nan


    for i in range(0,test_df.shape[0]-days):
        test_df["3_chg"].iloc[i]=(test_df.iloc[i]["product_price"]/test_df.iloc[i+days]["product_price"])-1
输出如下所示:

我正在使用我的代码获得所需的输出。然而,我想知道是否有更有效的方法来进行同样的计算。我的代码对于一小部分数据工作得很快,但是如果我使用所有50个州的数据,则需要很多时间


如果有其他选择,请告诉我。感谢使用
shift

df['3_change']=(df['product_price']-df.groupby('name')['product_price'].shift(3))/df['product_price']

(df['product_price']-df.groupby('name')['product_price'].shift(3))/df['product_price']感谢它的成功。我使用了:df[“3_chg”]=(df['product_price']/df.groupby('name')['product_price']].shift(-3))-1要我把它转换成一个答案吗?