Lisa
Lisa

Reputation: 4436

How can I sort a DataFrame by date ddMMMyyyy?

I have a sample dataframe as follows.

How can I sort it by the index by year instead of by month?

test=DataFrame([1,2,3],index=['28FEB1993','28FEB1994','30MAR1993'],columns=['value'])

I would like to have the following dataFrame as the result

test=DataFrame([1,2,3],index=['28FEB1993','30MAR1993','28FEB1994'],columns=['value'])

I think I stuck at how to parse ddMMMyyyy data format to a datetime object.

Thanks aton!

Upvotes: 0

Views: 210

Answers (1)

akuiper
akuiper

Reputation: 215047

You can use strptime:

from datetime import datetime
test.index = np.array([datetime.strptime(s, "%d%b%Y") for s in test.index.values])

test.sort_index()
#           value
# 1993-02-28    1
# 1993-03-30    3
# 1994-02-28    2

Or as suggested by @chrisb:

test.index = pd.to_datetime(test.index, format="%d%b%Y")

Upvotes: 1

Related Questions