gpt4 book ai didi

python - 对 Pandas 中的字符串进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 01:53:11 25 4
gpt4 key购买 nike

我在 pandas 中有一个数据框,我想按列对其进行排序。如果我在下面的代码中使用 .sort_values():

df.sort_values(by='id')

我在“id”列中得到的输出为:

1075_2016-06-01_0_1
1075_2016-06-01_10_1
1075_2016-06-01_10_2
1075_2016-06-01_11_1
1075_2016-06-01_11_2
1075_2016-06-01_1_1
1075_2016-06-01_1_2

我预计:

1075_2016-06-01_0_1
1075_2016-06-01_1_1
1075_2016-06-01_1_2
1075_2016-06-01_10_1
1075_2016-06-01_10_2
1075_2016-06-01_11_1
1075_2016-06-01_11_2

在 pandas 中执行此操作的最佳方法是什么?

最佳答案

一种可能的解决方案 natsort通过 loc 获取排序值和更改原始 DataFrame 的索引:

from natsort import index_natsorted, order_by_index

df2 = df.loc[order_by_index(df.index, index_natsorted(df['id']))]

或者用_拆分所有值,然后将列转换为整数,可选地转换为日期时间,对索引进行排序,最后使用loc与原始DataFrame:

df1 = df['id'].str.split('_', expand=True)
df1[[0,2,3]] = df1[[0,2,3]].astype(int)
df1[1] = pd.to_datetime(df1[1])

df2 = df.loc[df1.sort_values([0,1,2,3]).index]
print (df2)
id
0 1075_2016-06-01_0_1
5 1075_2016-06-01_1_1
6 1075_2016-06-01_1_2
1 1075_2016-06-01_10_1
2 1075_2016-06-01_10_2
3 1075_2016-06-01_11_1
4 1075_2016-06-01_11_2

下一个解决方案是使用 argsort 进行排序和更改顺序,方法是按位置索引,使用 iloc 处理任何索引值:

f = lambda x: [int(x[0]), pd.to_datetime(x[1]), int(x[2]), int(x[3])]
df2 = df.iloc[df['id'].str.split('_').map(f).argsort()]
print (df2)
id
0 1075_2016-06-01_0_1
5 1075_2016-06-01_1_1
6 1075_2016-06-01_1_2
1 1075_2016-06-01_10_1
2 1075_2016-06-01_10_2
3 1075_2016-06-01_11_1
4 1075_2016-06-01_11_2

关于python - 对 Pandas 中的字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57535099/

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