[英]How to calculate Month to Date (MTD) and YTD using Pandas dataframe?
[英]How to calculate year to date (YTD) of a financial year starting from month April using Pandas dataframe?
我想使用 Pandas dataframe 计算一个财政年度的 YTD。 我使用下面的代码来找到它。但是我从一月份开始得到 YTD。
report_table['ytd_sales'] = report_table.groupby(['year','month', 'planttype', 'market', 'product'])['sales'].cumsum()
谁能帮我计算从四月到三月(财政年度)的年初至今。
通过numpy.where
创建financial_year
年度列:
report_table['financial_year'] = np.where(report_table['month'] > 3,
report_table['year']+1,
report_table['year'])
或month
和year
列创建日期时间,然后转换为financial_year
:
report_table['financial_year']=(pd.to_datetime(report_table[['month','year']].assign(day=1))
.dt.to_period('Q-MAR')
.dt.qyear)
report_table['ytd_sales'] = report_table.groupby(['financial_year', 'planttype', 'market', 'product'])['sales'].cumsum()
利用 -
report_table['Fiscal Year'] = report_table['Date'].dt.to_period('Q-MAR').dt.qyear
report_table['ytd_sales'] = report_table.groupby(['Fiscal Year',month, 'planttype', 'market', 'product'])['sales'].cumsum()
例子-
import pandas as pd
dates = {'Date': ['1/1/2021', '1/31/2021', '2/1/2021', '2/28/2021', '3/1/2021', '3/31/2021', '4/1/2021', '4/30/2021', '5/1/2021', '5/31/2021', '6/1/2021']}
df = pd.DataFrame(dates)
df['Date'] = pd.to_datetime(df['Date'])
print(df)
df['Fiscal Year'] = df['Date'].dt.to_period('Q-MAR').dt.qyear
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.