我正在尝试通过项目长度按月线性地摊销项目的成本。
为此,我迭代具有定义函数的项目框架,该项目将每行(或项目(变成成本计划的新数据框架。
然后,我希望将我的功能的返回数据框架合并在一起,以创建我的最终数据集作为我初始数据帧中所有项目的计费时间表的列表。
这是我定义的功能:
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函数的输出进行此操作。我确实知道该功能会对单个迭代产生预期结果。
另外,我对熊猫很新,所以如果有更好/更优化的方法来做到这一点,我很想听听。
我认为最清洁的选项可能是apply
和stack
的组合。因此,使用。沿行沿行返回PD.Series(其中索引每个日期是日期日期,值是摊销值(,然后使用.stack
将值折叠到其应有的位置,例如
def amortize(sers):
values = #get the values
dates = #get the dates
return pd.Series(values, index=dates)
new_df = initial_dataframe.apply(amortize, axis=1).stack()
而不是格式化 .apply()
,我认为您可以通过这一点实现这一点:
初始化一个空列表以存储所有DF,df_list = []
。在功能内部迭代中填充它,df_list.append(df)
。迭代后,将所有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)
输出应该看起来像
我结束了使用以下解决方案,该解决方案适合我使用全局数据框架:
globalDF = pd.DataFrame(columns=['Cost_Date','Name','Period_Cost'])
,然后在函数迭代期间,我使用contat函数在全局上构建:
globalDF = pd.concat([globalDF,df])
这与提供的列表附加方法非常相似。