gpt4 book ai didi

python - pandas)如何在 sort_values 中使用 kind 选项

转载 作者:行者123 更新时间:2023-12-02 09:23:59 26 4
gpt4 key购买 nike

您好,我想按列中的值对数据框进行排序列的值是字符串与数字的组合。我想按分割后的值中的数字进行排序因此,我搜索了一些模块,只从列表中选择数字,并在 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 实现,请检查 this .

关于python - pandas)如何在 sort_values 中使用 kind 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59351228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com