简体   繁体   中英

pandas) how to use kind option in sort_values

Hi I want to sort dataframe by value in column column'values are string combination with number. I want to sort by number in values by splited So I searched some modules to pick only number from list and apply kind option in sort_values.. but It didn't work.. Without kind option, it sort by 'D1 D10 D11 D2 D3..'. I want sort 'D1 D2 D3 D4..D10 D11' Can you help me?

python # I want to sort by D1 D2 D3 D4 D5 D10 D11... df[Xlabel] = ['D1','D2','D3','D4','D5','D10','D11']

 def atoi(text):
  return int(text) if text.isdigit() else text
 def natural_keys(text):
  return [ atoi(c) for c in re.split('(\d+)',text) ]

 # my trying but didn't work with error message like below..
 df.sort_values(by=[Xlabel], inplace=True, kind=natural_keys[list(df[Xlabel])])

 # my trying working well but it didn't sort well
 # It sort by ( D1 D10 D11 D2 D3... ) it's not my hope
 df.sort_values(by=[Xlabel], inplace=True])
#error message when trying my method
df.sort_values(by=[Xlabel], inplace=True, kind=natural_keys[list(df[Xlabel])])
TypeError: 'function' object is not subscriptable

I think here should be better use natsort with convert column to ordered categoricals:

df = pd.DataFrame({'Xlabel':['D1','D2','D3','D4','D5','D10','D11']})

import natsort as ns

df['Xlabel'] = pd.Categorical(df['Xlabel'],
                              ordered=True,
                              categories= ns.natsorted(df['Xlabel'].unique()))
df = df.sort_values('Xlabel')
print (df)
  Xlabel
0     D1
1     D2
2     D3
3     D4
4     D5
5    D10
6    D11

Also I think in new version of pandas this should be possible with new parameter key , check this .

函数应该由括号使用,而不是方括号,请尝试使用:

df.sort_values(by=[Xlabel], inplace=True, kind=natural_keys(list(df[Xlabel])))

Update for pandas 1.1.0 sort_values now has key parameter:

df.sort_values('Xlabel', key=lambda x: x.str.extract('(\d+)').squeeze().astype(int))

Output:

  Xlabel
0     D1
1     D2
2     D3
3     D4
4     D5
5    D10
6    D11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM