如何按字符串中的数字对DataFrame列值进行排序?
问题描述
DataFrame的每一列数据格式均为「数字+.+字符串值」,尝试按其中的数字对各列排序,但未成功。
当前输出:
Row1: Column1: 1.Test, Column2: 1.Test, Column3: 2.Test Row2: Column1: 3.Test, Column2: 2.Test, Column3: 1.Test Row3: Column1: 2.Test, Column2: 3.Test, Column3: 3.Test
目标输出:
Row1: Column1: 1.Test, Column2: 1.Test, Column3: 1.Test Row2: Column1: 2.Test, Column2: 2.Test, Column3: 2.Test Row3: Column1: 3.Test, Column2: 3.Test, Column3: 3.Test
当前尝试的代码:
dfPrincipal.sort_values(by=list(dfPrincipal.columns),axis=0, ascending=False)
解决方案
直接调用sort_values会按字符串字典序排序,无法识别值中的数字逻辑。需要提取每个值里的数字作为排序依据,对每一列单独排序后重组DataFrame。
方法一:匿名函数简化处理
# 对每一列按值中的数字升序排序 df_sorted = dfPrincipal.apply(lambda col: col.sort_values(key=lambda x: int(x.split('.')[0])).values)
方法二:定义提取函数(可读性更强)
def extract_number(s): # 分割字符串并提取开头的数字 return int(s.split('.')[0]) # 逐列应用排序逻辑 df_sorted = dfPrincipal.apply(lambda col: col.sort_values(key=extract_number))
如果需要降序排序,只需在sort_values中添加ascending=False参数:
df_sorted = dfPrincipal.apply(lambda col: col.sort_values(key=extract_number, ascending=False))
处理后即可得到每列按数字排序后的目标结果。
内容的提问来源于stack exchange,提问作者Carlos Lozano
相关产品推荐
相关产品推荐

