Home > OS >  Pandas Sort Values By Date Doesn't Sort By Year
Pandas Sort Values By Date Doesn't Sort By Year

Time:08-11

I have a large data set that is in this format

enter image description here

I'd like to order this data set by the "created_at" column, so I converted the "created_at" column to type datetime following this guide: enter image description here

What am I missing?

CodePudding user response:

With a datetime type, this should be able to sort directly, make sure to assign the output as sorting is not in place:

# no need for an intermediate column nor to pass the full format
data['created_at'] = pd.to_datetime(data['created_at'].str.split(" ").str[0])

# assign output
data = data.sort_values(by='created_at')

CodePudding user response:

As in the comments already stated. the sorted df needs to be assigned again. sort_values doesn't work inplace by default.

data = data.sort_values(by='created_at')

# OR 

data.sort_values(by='created_at', inplace=True)
  • Related