[英]pandas) how to use kind option in sort_values
嗨,我想按列中的值對數據框進行排序,列的值是帶數字的字符串組合。 我想通過拆分按值中的數字排序所以我搜索了一些模塊以僅從列表中選擇數字並在 sort_values 中應用 kind 選項..但它沒有用..沒有 kind 選項,它按'D1 D10 D11 D2 D3 ..'. 我想要排序 'D1 D2 D3 D4..D10 D11' 你能幫我嗎?
python
# 我想按 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
我認為這里應該更好地使用natsort和將列轉換為有序分類:
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
另外我認為在新版本的 Pandas 中,這應該可以使用新的參數key
,檢查這個。
函數應該由括號使用,而不是方括號,請嘗試使用:
df.sort_values(by=[Xlabel], inplace=True, kind=natural_keys(list(df[Xlabel])))
sort_values
現在具有關鍵參數:df.sort_values('Xlabel', key=lambda x: x.str.extract('(\d+)').squeeze().astype(int))
輸出:
Xlabel
0 D1
1 D2
2 D3
3 D4
4 D5
5 D10
6 D11
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.