1

I have a DataFrame in python, the cell value is the purchase quantity like:

 code   1/18     2/18      3/18     4/18     5/18 
 1      NaN      15        15       16       14
 2      NaN      NaN       30       23       24 
 3      24       21        23       NaN      26

I want to order the code in terms of the date they were first purchased, the result would be:

code   1/18     2/18      3/18     4/18     5/18   
3      24       21        23       NaN      26
1      NaN      15        15       16       14
2      NaN      NaN       30       23       24 

Please help!

1 Answer 1

1

I think need specify columns for sorting by indexing - here by all columns without first:

print (df.columns[1:].tolist())
['1/18', '2/18', '3/18', '4/18', '5/18']

df = df.sort_values(by=df.columns[1:].tolist())
print (df)
   code  1/18  2/18  3/18  4/18  5/18
2     3  24.0  21.0    23   NaN    26
0     1   NaN  15.0    15  16.0    14
1     2   NaN   NaN    30  23.0    24

If first column is index:

print (df.columns.tolist())
['1/18', '2/18', '3/18', '4/18', '5/18']

df = df.sort_values(by=df.columns.tolist())
print (df)
      1/18  2/18  3/18  4/18  5/18
code                              
3     24.0  21.0    23   NaN    26
1      NaN  15.0    15  16.0    14
2      NaN   NaN    30  23.0    24
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.