I have a pandas dataframe which at beginning looks like this

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

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]
Any idea why??

location_idbecomesindexaftergroupby()groupby()and see what your dataframe was after that step :Dlocation_idis now an index, so you either access the index bydf_sorted.indexor you make a new columndf.sorted['location_id'] = df_sorted.indexdf.columns, or better yetdf.columns.tolist()to spot blank spaces.