python - 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 很陌生,所以如果有更好/更优化的方法来做到这一点,我很想听听。
解决方案
而不是格式化.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)
输出应如下所示
推荐阅读
- javascript - 如何使用 JavaScript 在 div 中创建输入标签
- amazon-s3 - 从 JS 访问存储在 AWS S3 上的深度缩放图像
- python - 如何在同一数据集中将数字与 str 隔离
- mysql - 导入文本文件中的注释行
- python - 在 Jupyter 中标记一行代码以供以后查看
- android - Gradle:与依赖项冲突
- carousel - Boostrap 缩略图轮播项目没有响应
- .net - 如何将“dotnet try-convert”实际应用于要转换为 .net 核心的文件?
- typescript - 如何使用 Typescript 为固定的简单对象创建接口?
- android - 导航组件 FragmentContainerView 在 fitSystemWindows=true 下不能很好地发挥作用