0

I'm trying to sort a dataframe using the sort_values method. I have a dataframe (df) with just two columns ('TS','VALUES') and I always getting a error as the follwoing:

df.columns
Out[88]: Index(['TS', 'VALUES'], dtype='object')

df.sort_values(by='TS',axis=1,ascending=True,inplace=True,kind='quicksort',na_position='last')
Traceback (most recent call last):

  File "<ipython-input-89-53f79846b56c>", line 1, in <module>
    df.sort_values(by='TS',axis=1,ascending=True,inplace=True,kind='quicksort',na_position='last')

  File "C:\Users\gianm\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4421, in sort_values
    stacklevel=stacklevel)

  File "C:\Users\gianm\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1382, in _get_label_or_level_values
    raise KeyError(key)

KeyError: 'TS'

It seems python does not recognize the name of the columns. Where I'am wrong ? Thanks

jpp
  • 159,742
  • 34
  • 281
  • 339
polgia0
  • 347
  • 1
  • 3
  • 14

2 Answers2

1

Problem is axis=1, it working for sorting by index values, so need axis=0 or remove it, because default parameter in sort_values:

DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')

df = pd.DataFrame({'TS': [40,1,4], 'a':[1,5,2], 'd':[7,8,9]}, index=list('abc'))
print (df)
   TS  a  d
a  40  1  7
b   1  5  8
c   4  2  9

df.sort_values(by='TS',
               axis=0,
               ascending=True,
               inplace=True,
               kind='quicksort',
               na_position='last') 

print (df)
   TS  a  d
b   1  5  8
c   4  2  9
a  40  1  7

If remove parameters with default values:

df.sort_values(by='TS', inplace=True) 
print (df)
   TS  a  d
b   1  5  8
c   4  2  9
a  40  1  7

df.sort_values(by='a',axis=1,ascending=True,inplace=True,kind='quicksort',na_position='last') 
print (df)
   a  d  TS
a  1  7  40
b  5  8   1
c  2  9   4
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

Is one of the 2 columns you're passing to sort_values your index?

If so you can use reset_index() to convert the index into a new column and then sort by both the column and the index.

data.reset_index().sort_values(['Column','Index']).set_index('Index')
philjet
  • 45
  • 3