[英]How to calculate year to date (YTD) of a financial year starting from month April using Pandas dataframe?
I want to calculate YTD of a financial year using Pandas dataframe.我想使用 Pandas dataframe 计算一个财政年度的 YTD。 I used below code to find it.But I got YTD from month January.
我使用下面的代码来找到它。但是我从一月份开始得到 YTD。
report_table['ytd_sales'] = report_table.groupby(['year','month', 'planttype', 'market', 'product'])['sales'].cumsum()
Can anyone help me to calculate YTD fom month April to March(financial year).谁能帮我计算从四月到三月(财政年度)的年初至今。
Create column of financial_year
by numpy.where
:通过
numpy.where
创建financial_year
年度列:
report_table['financial_year'] = np.where(report_table['month'] > 3,
report_table['year']+1,
report_table['year'])
Or crete datetime by both columns month
and year
and then convert to financial_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()
USE -利用 -
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()
Example-例子-
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
Ref link- https://datagy.io/pandas-fiscal-year/参考链接- https://datagy.io/pandas-fiscal-year/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.