6

I am trying to sort a dataframe by a particular column: "Lat". However, although when I print out the column names, "Lat" clearly shows up, when I try to use it as the "by" parameter in the sort_values function, I get a KeyError. It doesn't matter which column name I use, I get a key error no matter what.

I have tried using different columns, running in place, stripping the columns names, nothing seems to work

print(lights_df.columns.tolist())
lights_by_lat = lights_df.sort_values(axis = 'columns', by = "Lat", kind 
= "mergesort")

outputs:

['the_geom', 'OBJECTID', 'TYPE', 'Lat', 'Long']

KeyError: 'Lat'

^output from trying to sort

2
  • want axis='index' (or just leave it out since it's the default) Commented Jul 23, 2019 at 17:53
  • 5
    The confusion here is because for sort, axis specifies the axis to be sorted. You are using a column to change the ordering of rows, so axis='index' is what's needed. With a better minimal reproducible example maybe it would be worth an answer. Commented Jul 23, 2019 at 18:01

2 Answers 2

7

All you have to do is remove the axis argument:

lights_by_lat = lights_df.sort_values(by = "Lat", kind = "mergesort")

and you should be good.

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

1 Comment

See @ALollz comment on OP post for the explanation
1

I think it's because you are seeking on the wrong axis.  For example, this dataframe: DATAFRAME

Let's say: I want to order by the row axis with label "1". So you put this:

df.sort_values(by='1',axis=0,inplace=False)

But the result give the error: KeyError: '1'

The solution is changing the axis to columns:

df.sort_values(by='1',axis=1,inplace=False)

I think it's because you want to order by row label "1" data, but the axis is "index", so ordering by "1" label is not possible because numbers are reordered in the column axis and not the index axis.

I hope this helps others.

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.