Python 迭代DataFrame以计算新行值

Python 迭代DataFrame以计算新行值,python,pandas,Python,Pandas,我想迭代Pandas dataframe并计算新的行值。除2010年1月外,租金增长率为2%。我想计算新租金并更新租金列 2%是根据上一年的价值计算出来的,所以这就像滚动2% df = pd.DataFrame({ "Year": ['2010','2011','2012','2013','2014'], "Rent": ['1000','1000','1000','1000','

我想迭代Pandas dataframe并计算新的行值。除2010年1月外,租金增长率为2%。我想计算新租金并更新租金列

2%是根据上一年的价值计算出来的,所以这就像滚动2%

df = pd.DataFrame({
                   "Year": ['2010','2011','2012','2013','2014'],
                   "Rent": ['1000','1000','1000','1000','1000']
                 })


for index, row in df.iterrows():
    df.at[index, "Rent"] = round(row['Year']*row['Rent'],0) + round(2*row['Rent']/100,0)
我的尝试不太奏效

预期的输出/修改数据帧为:

df = pd.DataFrame({
                   "Year": ['2010','2011','2012','2013','2014'],
                   "Rent": ['1000','1020','1040.4','1060.8','1082]
                 })
  • 可能存在一些舍入错误,因此近似值可以

    • 我认为这是解决您问题的一种方法:

      df = pd.DataFrame({
                         "Year": ['2010','2011','2012','2013','2014'],
                         "Rent": ['1000','1000','1000','1000','1000']
                       })
      
      counter = 1
      for i in df.loc[1:, 'Rent']:
          i = (2 * int(df.loc[counter-1, 'Rent']) /100) + int(df.loc[counter-1, 'Rent'])
          print('rent: ' + str(df.loc[counter-1, 'Rent']))
          df.loc[counter, 'Rent'] = i
          counter += 1
      
      输出:

      
          Year    Rent
      0   2010    1000
      1   2011    1020.0
      2   2012    1040.4
      3   2013    1060.8
      4   2014    1081.2
      
      

      请共享预期的输出。您也可以打印输出数据帧。