The World’s Largest Online Community for Developers

'; python - Key Error while sorting column in Pivot dataframe - LavOzs.Com

Refer the data frame screenshot df10

I have tried all options / solutions available to sort the pivot by year colum '2019'. However I am getting the following error.

KeyError: '2019'

Few lines above this error says :

*1690             values = self.axes[axis].get_level_values(key)._values
1691         else:
-> 1692             raise KeyError(key)
1694         # Check for duplicates*

I am using the following code

df10 = df10.sort_values('2019' , ascending=False)

I thought there is whitespace in the column so used below code as well and got the error


Can only use .str accessor with string values!

Here is the output of

print (df10.columns.tolist())
[2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019]
How can I sort a dictionary by key?
Selecting multiple columns in a pandas dataframe
Adding new column to existing DataFrame in Python pandas
How to change the order of DataFrame columns?
Delete column from pandas DataFrame
How to drop rows of Pandas DataFrame whose value in a certain column is NaN
How to select rows from a DataFrame based on column values?
Get list from pandas DataFrame column headers
How to pivot a dataframe
“Check for duplicates” error when I am trying to sort dataframe by datetime64