How can I convert Date Column to the last Business Day of that Date

Viewed 56

I would like to convert this Date column to the last Business Day of the month, that Date column represents. Anybody has an idea please? Thanks

import pandas as pd  

# assign data of lists.  
data = {'Name': ['2021-12-31', '2020-12-31', '2019-12-31', '2018-12-31', '2017-12-31']}  

# Create DataFrame  
df = pd.DataFrame(data)  
df = pd.date_range(df, freq='BM')

df
1 Answers

Here is how I usually do it:

import pandas as pd

data = {'Name': ['2021-12-31', '2020-12-31', '2019-12-31', '2018-12-31', '2017-12-31']}  

td = pd.Timedelta('1 day')
bd = pd.tseries.offsets.BusinessDay(n=-1)

data_EOM = {'NAME': [pd.Timestamp(ts) + td + bd for ts in data['Name']]}

td is used to shift the End-of-month date to the next month. bd is used to go back a single business date, ergo the last business day of the month you want. pd.Timestamp() is used to convert the string date into a timestamp object on which the timedelta objects above (td and bd) can be applied.

Finally, I use list comprehension to loop through the original date list to create the EOM date list you were looking for. From here, you can create your df just like you wanted.

Hope this helps!

Related