python - 如何根据列中包含的值子集对python中的数据框行进行排序
问题描述
我想根据第一列中包含的值对数据框行进行排序。第一列包含字符串,我对这些字符串中包含的一些数字感兴趣(即我想要的这些字符串中的“chr5:10..100”、“chr14:2..300”、“chrX:1..10”收集 5、14、X 号染色体)。我要提取的数字决定了我想要我的行的顺序。字符串中感兴趣的数字的初始和最终位置未知(第一个 pos 始终为 3,但最终确定找到“:”符号。
我应该怎么办?
提前致谢。
解决方案
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
推荐阅读
- php - 在占位符中添加按钮和链接的问题
- delphi - 如何使 TSynEdit 的 Wordwrap 与 TMemo 的一样?
- azure - 应用内容安全策略后 Azure 交换不起作用
- php - 即使在 ajax 上设置最小输入数量添加到 Woocommerce 中的购物车
- php - 使用 ISSET() 并且值永远不会 False 与 Html 选择选项代码
- flutter - 如何从网络图像中获取 ui.Image(dart:ui)?
- android - 在 ARCORE 中获取接触点
- python - 如何在函数参数中留出空格?
- css - :hover 上的 CSS 动画和动画
- c# - WebSocket 服务器仅使用 ssl 从握手标头接收“G”