0

I have a pandas dataframe which at beginning looks like this enter image description here

Now I did some computation with the dataframe and the code is as follows

df_sorted = (df.groupby(df['location_id'])['users'].nunique()).to_frame()
df_sorted = df_sorted.sort_values(['users'], ascending=False)

now the dataframe looks like this enter image description here

but now I cannot access location_id from new dataframe with following code

df_sorted['location_id']

I get error saying KeyError: 'location_id' However when i do

df_sorted['users]

I get entire dataframe likeenter image description here

Any idea why??

4
  • 2
    location_id becomes index after groupby() Commented May 8, 2017 at 11:49
  • You should stop at groupby() and see what your dataframe was after that step :D Commented May 8, 2017 at 11:50
  • As @zipa says, location_id is now an index, so you either access the index by df_sorted.index or you make a new column df.sorted['location_id'] = df_sorted.index Commented May 8, 2017 at 11:51
  • When in doubt inspect df.columns, or better yet df.columns.tolist() to spot blank spaces. Commented May 8, 2017 at 11:52

1 Answer 1

2

location_id becomes index after groupby(). What you can do is use:

df_sorted = df_sorted.sort_values(['users'], ascending=False).reset_index()

This will return to previous indexing and turn location_id into column.

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.