0

How can I create an indicator for last day of the month?

Please help I've been struggling on this.

Input

Dates            Item        Sales           
2017-01-01       Apple       10
2017-01-02       Pear        10 
2017-01-31       Apple       10
2017-02-02       Apple       10
2017-01-28       Apple       10

Output

Dates            Item        Sales      Last day of month      
2017-01-01       Apple       10         No    
2017-01-02       Pear        10         No
2017-01-31       Apple       10         Yes
2017-02-02       Apple       10         No
2017-02-28       Apple       10         Yes
Brad Solomon
  • 34,372
  • 28
  • 129
  • 206
OptimusPrime
  • 617
  • 6
  • 17

2 Answers2

4

Use numpy.where with dt.is_month_end:

df['Last day of month'] = np.where(df['Dates'].dt.is_month_end, 'Yes', 'No')
print (df)
       Dates   Item  Sales Last day of month
0 2017-01-01  Apple     10                No
1 2017-01-02   Pear     10                No
2 2017-01-31  Apple     10               Yes
3 2017-02-02  Apple     10                No
4 2017-02-28  Apple     10               Yes

Thanks, Anton vBR for solution inspired by Wen:

df['Dates'].dt.is_month_end.map({1:'Yes',0:'No'}) 
jezrael
  • 729,927
  • 78
  • 1,141
  • 1,090
  • Obviously the right choice if pd already has a function for it. +1. Inspired by @Wen I think: `df['Dates'].dt.is_month_end.map({1:'Yes',0:'No'})` is easier to read. – Anton vBR Nov 18 '17 at 18:42
2

By using pd.offsets

df['Last day of month']=(df.Dates==df.Dates+pd.offsets.MonthEnd(0)).map({1:'Yes',0:'No'})
df
Out[275]: 
       Dates   Item  Sales Last day of month
0 2017-01-01  Apple     10                No
1 2017-01-02   Pear     10                No
2 2017-01-31  Apple     10               Yes
3 2017-02-02  Apple     10                No
4 2017-02-28  Apple     10               Yes
BENY
  • 296,997
  • 19
  • 147
  • 204