4

I have a dataframe with Datetime index that I want to sort with the last Datetime.

For example, my dataframe is:

                            A       B       C       D
2018-12-05 20:12:10       48.58   50.81   46.71   48.18
2018-12-05 20:11:49       54.43   45.08   48.67   49.72
2018-12-05 20:11:41       49.86   52.40   48.47   50.02

And I want to sort it like this:

                            B       A       D       C
2018-12-05 20:12:10       50.81   48.58   48.18   46.71
2018-12-05 20:11:49       45.08   54.43   49.72   48.67
2018-12-05 20:11:41       52.40   49.86   50.02   48.47

I tried:

df.sort_values(by=df.iloc[0],ascending=False,inplace=True) and df.sort_values(by=df.index[0],ascending=False,inplace=True)

I get the error :"Exeption Unhandled Timestamp('2018-12-05 20:12:10')"

I also tried:

df.sort_values(by=df.iloc[0],ascending=False,inplace=True, axis=1) and df.sort_values(by=df.index[0],ascending=False,inplace=True, axis=1)

And I got a return : "None"

My index type is 'datetime64'

Any hints will be very appreciated. Thanks!

2
  • Can you explain? You say last datetime, but sort by df.iloc[1], What is the logic here? Commented Dec 21, 2018 at 4:46
  • Sorry, i meant df.iloc[0]. I was hoping that it would sort the first row wich is my last datetime. I edited my question, thanks. Commented Dec 21, 2018 at 4:55

1 Answer 1

5

Actually, your code will work without the inplace argument:

df.sort_values(by=df.index[0], ascending=False, axis=1)

                         B      A      D      C
2018-12-05 20:12:10  50.81  48.58  48.18  46.71
2018-12-05 20:11:49  45.08  54.43  49.72  48.67
2018-12-05 20:11:41  52.40  49.86  50.02  48.47

As another option, you can leverage argsort here:

df.iloc[:, (-df.iloc[0, :]).argsort()]

                         B      A      D      C
2018-12-05 20:12:10  50.81  48.58  48.18  46.71
2018-12-05 20:11:49  45.08  54.43  49.72  48.67
2018-12-05 20:11:41  52.40  49.86  50.02  48.47

Or,

df.iloc[:, np.argsort(-df.values[0])]

                         B      A      D      C
2018-12-05 20:12:10  50.81  48.58  48.18  46.71
2018-12-05 20:11:49  45.08  54.43  49.72  48.67
2018-12-05 20:11:41  52.40  49.86  50.02  48.47

Another method (slightly less efficient is to use sort_values(ascending=False) and use the index for selection by label:

df[df.iloc[0, :].sort_values(ascending=False).index]

                         B      A      D      C
2018-12-05 20:12:10  50.81  48.58  48.18  46.71
2018-12-05 20:11:49  45.08  54.43  49.72  48.67
2018-12-05 20:11:41  52.40  49.86  50.02  48.47
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.