-2

my dataframe is given below:

Name       time
a          10:30 A
a          01:30 P
a          11:30 A
a          01:10 P
    

i have wanted to sort time columns according to last string (A,P) like this

    Name       time
    a          10:30 A
    a          11:30 A
    a          01:10 P
    a          01:30 P
Bashar
  • 68
  • 1
  • 7
  • 1
    Could you provide some information on what you've tried so far? Also what is the format of the time column. It could be a string rather than time if you've not done something like df['time']=pd.to_datetime(df['time']) – A Rob4 Sep 16 '20 at 15:26
  • Welcome to SO! Please see [this](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). – ggorlen Sep 16 '20 at 15:34

1 Answers1

0

If these are strings, try:

>>> df = pd.DataFrame({"time": ["10:30 A", "01:30 P", "11:30 A", "01:10 P"]})
>>> df
      time
0  10:30 A
1  01:30 P
2  11:30 A
3  01:10 P
>>> df.assign(tmp=df["time"].str.slice(-1)).sort_values("tmp").drop("tmp", 1)
      time
0  10:30 A
2  11:30 A
1  01:30 P
3  01:10 P

If they're datetimes:

>>> df["time"] = pd.to_datetime(df["time"])
>>> df
                 time
0 2020-09-16 10:30:00
1 2020-09-16 13:30:00
2 2020-09-16 11:30:00
3 2020-09-16 13:10:00
>>> df.sort_values("time")
0 2020-09-16 10:30:00
2 2020-09-16 11:30:00
3 2020-09-16 13:10:00
1 2020-09-16 13:30:00
ggorlen
  • 44,755
  • 7
  • 76
  • 106