When try to sort my dataframe by the column "Number" i get the error code
1708 # Check for duplicates
KeyError: 'Number'
the dataframe looks something like this
Number Name City Sex
3 Jay A M
1 Marry A F
5 John B M
Number is int64 and the rest are objects
df.sort_values(by=['Number']) --> error
df.sort_values(by=['Name']) --> works
df.sort_values(by=['City']) --> error
df.sort_values(by=['Sex']) --> works
What i am looking for is something like this
Number Name City Sex
1 Marry A F
3 Jay A M
5 John B M
I try to make a DataFrame like yours and sort it & it works to sort by Number
column:
df=pd.DataFrame({'Number':[3,1,5],
'Name':['Jay','Marry','John'],
'City':['A','A','B'],
'Sex':['M','F','M']})
print(df)
print(df.Number.dtype)
df=df.sort_values(by=['Number'])
print(df)
Output:
Number Name City Sex
0 3 Jay A M
1 1 Marry A F
2 5 John B M
int64
Number Name City Sex
1 1 Marry A F
0 3 Jay A M
2 5 John B M
Maybe there is a white space in your columns, try this before sorting:
df.columns=df.columns.str.strip()