简体   繁体   中英

How to add a new column based on different conditions on other columns pandas

This is my dataframe:

Date        Month
04/21/2019  April
07/03/2019  July
01/05/2018  January
09/23/2019  September

I want to add a column called fiscal year. A new fiscal year starts on 1st of July every year and ends on the last day of June. So for example if the year is 2019 and month is April, it is still fiscal year 2019. However, if the year is 2019 but month is anything after June, it will be fiscal year 2020. The resulting data frame should look like this:

 Date        Month      FY
04/21/2019  April      FY19
07/03/2019  July       FY20
01/05/2019  January    FY19
09/23/2019  September  FY20

How do I achieve this?

try via pd.PeriodIndex() + pd.to_datetime() :

df['Date']=pd.to_datetime(df['Date'])
df['FY']=pd.PeriodIndex(df['Date'],freq='A-JUN').strftime("FY%y")

output:

    Date        Month       FY
0   2019-04-21  April       FY19
1   2019-07-03  July        FY20
2   2019-01-05  January     FY19
3   2019-09-23  September   FY20

Note: I suggest you you convert your 'Date' to datetime first then do any operation on it or If you don't want to convert 'Date' column then use the above code in a single step:

df['FY']=pd.PeriodIndex(pd.to_datetime(df['Date']),freq='A-JUN').strftime("FY%y")

One way using pandas.Dateoffset :

df["FY"] = (pd.to_datetime(df["Date"]) 
            + pd.DateOffset(months=6)).dt.strftime("FY%Y")
print(df)

Output:

         Date      Month      FY
0  04/21/2019      April  FY2019
1  07/03/2019       July  FY2020
2  01/05/2019    January  FY2019
3  09/23/2019  September  FY2020

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM