1

I am trying to reduce the code bloat in my project for the process of creating various date columns (weekday, business day, day index, week index) and I was wondering how I can take the index of my dataframe and build datetime attribute columns from the index.

I thought I could access the .index or index.values and then reference the datetime attributes like month, weekday, etc., but it doesn't appear that Index has those attributes. Would I need to convert the index values to a new list and then build the columns off of that?

Here is my code:

historicals = pd.read_csv("2018-2019_sessions.csv", index_col="date", na_values=0)
type(historicals)

// date formate = 2018-01-01, 2018-01-02, etc.

# Additional Date Fields
date_col = historicals.index
date_col.weekday

// AttributeError: 'Index' object has no attribute 'weekday'

1 Answer 1

1

Your index is in string format. You historicals.index probably looks like this

print(historicals.index)

Index(['2018-01-01', '2018-01-02'], dtype='object')

You need to convert it to datetimeindex and get its weekday attribute and assign to new column

historicals['weekday'] = pd.to_datetime(historicals.index).weekday

Or

date_col = pd.to_datetime(historicals.index)
print(date_col.weekday)
Sign up to request clarification or add additional context in comments.

1 Comment

That was exactly it. The index was actually in date format, but same issue. Only way to resolve it was to convert to datetime. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.