首页 > 解决方案 > Pandas - 将应用函数的结果数据帧合并到新数据帧中

问题描述

我试图在项目长度内按月线性摊销项目成本。

为此,我使用定义的函数迭代项目数据框,该函数将每一行(或项目)转换为成本计划的新数据框。

然后,我希望将我的函数返回的数据框合并在一起,以创建我的最终数据集,作为我初始数据框中所有项目的计费时间表列表。

这是我定义的函数:

    def amortizeProject(name, start, end, cost):
      """ Create an amortized cost schedule by month for a given project where:
        name = project Name
        start = start date of project
        end = end date of project
        cost = total cost of project
      """
      # Create an index of the payment dates
      rng = pd.date_range(start, end, freq='MS')
      rng.name = "Cost_Date"

      # Build up the Amortization schedule as a DataFrame
      df = pd.DataFrame(index=rng,columns=['Name','Period_Cost'], dtype='float')

      # Add index by period
      df.reset_index(inplace=True)
      df.index += 1
      df.index.name = "Period"
      df["Name"] = name
      df["Period_Cost"] = np.pmt(0, rng.size, cost)

      # Return the new dataframe
      df = df.round(2)
      return df

我正在尝试迭代我的 initial_dataframe,即:

            Name       Start         End     Cost
    0  Project 1  2019-07-01  2020-07-01  1000000
    1  Project 2  2020-01-01  2021-03-31   350000

像这样使用函数:

    new_dataframe = initial_dataframe.apply(lambda x: amortizeProject(x['Name'], x['Start'], x['End'], x['Cost']), axis=1)

理想情况下, new_dataframe 将是所有结果迭代的串联,但我不确定格式化 .apply 函数的输出以执行此操作的正确方法。我确实知道该函数会为单次迭代产生预期的结果。

另外,我对 Pandas 很陌生,所以如果有更好/更优化的方法来做到这一点,我很想听听。

标签: pythonpandasdataframe

解决方案


而不是格式化.apply(),我认为你可以通过这个来实现:

初始化一个空列表以存储所有 df, df_list = []。在函数内部迭代期间填充它,df_list.append(df). 迭代后,将该列表中存储的所有 df 连接到 df, df = pd.concat(df_list)

所以你发布的代码应该是:

def amortizeProject(name, start, end, cost):
  """ Create an amortized cost schedule by month for a given project where:
    name = project Name
    start = start date of project
    end = end date of project
    cost = total cost of project
  """
  # Create an index of the payment dates
  rng = pd.date_range(start, end, freq='MS')
  rng.name = "Cost_Date"

  # Build up the Amortization schedule as a DataFrame
  df = pd.DataFrame(index=rng,columns=['Name','Period_Cost'], dtype='float')

  # Add index by period
  df.reset_index(inplace=True)
  df.index += 1
  df.index.name = "Period"
  df["Name"] = name
  df["Period_Cost"] = np.pmt(0, rng.size, cost)

  # Return the new dataframe
  df = df.round(2)
  df_list.append(df)
  return df_list


df_list = []
new_dataframe = initial_dataframe.apply(lambda x: amortizeProject(x['Name'], x['Start'], x['End'], x['Cost']), axis=1)
df = pd.concat(df_list)
print(df)

输出应如下所示


推荐阅读