首页 > 解决方案 > 如何根据列中包含的值子集对python中的数据框行进行排序

问题描述

我想根据第一列中包含的值对数据框行进行排序。第一列包含字符串,我对这些字符串中包含的一些数字感兴趣(即我想要的这些字符串中的“chr5:10..100”、“chr14:2..300”、“chrX:1..10”收集 5、14、X 号染色体)。我要提取的数字决定了我想要我的行的顺序。字符串中感兴趣的数字的初始和最终位置未知(第一个 pos 始终为 3,但最终确定找到“:”符号。

我应该怎么办?

提前致谢。

标签: pythonsorting

解决方案


df = pd.DataFrame({'Strings': ["chrA:2..300", "chr5:10..100", "chr14:2..300",
                               "chrX:2..300", "chrM:2..300", "chr1:1..10"]})  # sample data

to_sort = df['Strings'].str.extract(r'^chr(.+):', expand=False)  # extract symbols between chr and :
nums = to_sort.str.isnumeric()  # make a boolean mask: numeric strings is True, other - False
to_sort[nums] = to_sort[nums].astype(int)  # convert numeric strings to integers
df.index = pd.MultiIndex.from_arrays([~nums, to_sort])
# sort df by level 0 index (for grouping numbers and letters), then by level 1 index (inside numbers, inside letters)
df = df.sort_index(ignore_index=True)
print(df)

印刷:

        Strings
0    chr1:1..10
1  chr5:10..100
2  chr14:2..300
3   chrA:2..300
4   chrM:2..300
5   chrX:2..300

推荐阅读