1

I have two Pandas dataframes that are concatenated by column. The left dataframe is keyed as "Old" and the right dataframe is keyed as "New". Each dataframe has the same column names and I'd like to be about to sort_values by one of the "New" columns. I can't seem to access sort though due to the "Old" and "New" keys. Anyone have a work around? Thanks.

Edit#1 - Code example (want to sort by ['New']['Col1'] in df_combined:

df1=pd.DataFrame({'Col1' : [1, 2, 3, 4], 'Col2' : [4, 4, 5, 6], 'Col3' : [11, 
12, 13, 14]})
df2=pd.DataFrame({'Col1' : [7, 1, 51, 6], 'Col2' : [90, 99, 99, 97], 'Col3' : 
[11, 12, 13, 14]})
df_combined=pd.concat([df1, df2], axis='columns', keys=['Old','New'])
3
  • 2
    Please show your input dataframe. Commented Dec 27, 2017 at 23:11
  • Updated Scott. Thanks! Commented Dec 28, 2017 at 15:30
  • How do you want to sort this dataframe exactly? Commented Dec 28, 2017 at 15:31

1 Answer 1

1

To sort this dataframe you must use tuples for column selection:

df_combined.sort_values(by=('New', 'Col1'))

Output:

   Old            New          
  Col1 Col2 Col3 Col1 Col2 Col3
1    2    4   12    1   99   12
3    4    6   14    6   97   14
0    1    4   11    7   90   11
2    3    5   13   51   99   13
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.