3

With the following code I am expecting the dataframe (rows) to be sorted from oldest to latest timestamp. Something like this...

         #raw_dataframe#                         #sorted dataframe#
  Symbol          tagdatetime             Symbol          tagdatetime
0      A  2020-03-01 01:00:00           0      B  2020-01-01 01:00:00
1      B  2020-01-01 01:00:00   ===>    1      A  2020-03-01 01:00:00
2      C  2020-06-01 01:00:00           2      C  2020-06-01 01:00:00

But the actual output is unsorted for the following code,

import pandas as pd
df = pd.DataFrame( {'Symbol':['A','B','C'] ,
    'tagdatetime':['2020-03-01 01:00:00','2020-01-01 01:00:00','2020-06-01 01:00:00']})
print(df,"\n-------------------------------")
df['tagdatetime'] = pd.to_datetime(df['tagdatetime'], format="%Y-%m-%d %H:%M:%S").sort_values()
print(df)

Output:
      Symbol          tagdatetime
    0      A  2020-03-01 01:00:00
    1      B  2020-01-01 01:00:00
    2      C  2020-06-01 01:00:00 
    -------------------------------
     Symbol         tagdatetime
    0      A 2020-03-01 01:00:00
    1      B 2020-01-01 01:00:00
    2      C 2020-06-01 01:00:00

And I have tried many other solutions, but none seems working for me. where am I doing wrong? what happens to sort when I have two or more rows with the same timestamp?

Please answer..

reddi hari
  • 173
  • 1
  • 12

1 Answers1

1

Use the following code:

df = pd.DataFrame( {'Symbol':['A','B','C'] ,
    'tagdatetime':['2020-03-01 01:00:00','2020-01-01 01:00:00','2020-06-01 01:00:00']})

df['tagdatetime'] = pd.to_datetime(df['tagdatetime'], format='%Y-%m-%d %H:%M:%S')
df.sort_values(by='tagdatetime', inplace=True)
print(df)

You need to convert column tagdatetime to datetime format before sorting & then sort values by column tagdatetime

Furqan Hashim
  • 1,304
  • 2
  • 15
  • 35
  • datetime is correctly parsed by the OP - the point is to update the `df`, either with `inplace=True` or `df = df.sort_values(by='tagdatetime')` – FObersteiner Jul 03 '20 at 08:52
  • Answer that I've posted is a generalized so it could carter larger audience. The OP clearly mentions that he is unable to sort I've answered that in my post. OP did parsed correctly. – Furqan Hashim Jul 03 '20 at 09:08