close

[Solved] sort_values() got an unexpected keyword argument ‘by’

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error sort_values() got an unexpected keyword argument ‘by’ in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How sort_values() got an unexpected keyword argument ‘by’ Error Occurs?

Today I get the following error sort_values() got an unexpected keyword argument ‘by’ in python.

How To Solve sort_values() got an unexpected keyword argument ‘by’ Error ?

  1. How To Solve sort_values() got an unexpected keyword argument 'by' Error ?

    To Solve sort_values() got an unexpected keyword argument 'by' Error If the 'string' argument is not duplicated then note that there are also some differences if the argument in .loc is on a list.

  2. sort_values() got an unexpected keyword argument 'by'

    To Solve sort_values() got an unexpected keyword argument 'by' Error If the 'string' argument is not duplicated then note that there are also some differences if the argument in .loc is on a list.

Solution 1

To add to the answer, why is it returning a series in one case and a data frame in another?

.loc function is returning a Series in the first case

for i in str_list: #str_list is a set contain some strings

df.loc[i].sort_values(by = ‘XXX’)

because the argument i appears only once in the DataFrame.

in the second case, the ‘string’ is duplicated and therefore will return a DataFrame.

df.loc[‘string’].sort_values(by = ‘XXX’)

If the ‘string’ argument is not duplicated then note that there are also some differences if the argument in .loc is on a list. for example.

df.loc[‘string’] -> returns a Series

df.loc[[‘string’]] -> returns a DataFrame

Maybe in the second case you are giving [‘string’] as the argument instead of ‘string’ ?

Hope this helps.

Solution 2

This is because the result of the loc operator is a pandas.Series object in your case. The sort_values in this case doesn’t have a keyword argument by because it can only sort the series values. Have a look at the difference in the signature when you call sort values in a pandas.DataFrame

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read