0

How do I sort a pandas data-frame by column? I read here http://pandas.pydata.org/...sort_values about sort_values. When I run

df = pd.DataFrame([(2,'a'),(1,'b')],columns = ['num','let'])
df
df.sort_values(by='num', axis=1, ascending=True, inplace=True)

I obtain error KeyError: 'num'

1
  • 2
    Remove axis=1, this is looking for index labels that match 'num' Commented Oct 5, 2017 at 11:00

1 Answer 1

3

You should remove axis=1, this tries to look for index labels that match 'num' which don't exist:

In[33]:
df.sort_values(by='num')

Out[33]: 
   num let
1    1   b
0    2   a

The default is axis=0 which looks for columns that match 'num'

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much EdChum, it worked. I was mislead by the description on the documentation pandas.pydata.org/pandas-docs/version/0.19.2/generated/… where is written " {0 or ‘index’, 1 or ‘columns’}" and by the fact that for dropping columns I use .drop(labes=['let'],axis=1)

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.