如何在Pandas DataFrame中对含F前缀的列子集进行自然排序?
Pandas实现仅对F前缀列进行自然排序
需求说明
现有Pandas DataFrame,其中存在一组连续的以F开头的列(列名格式为F+数字,数字数量不固定),需要仅对这组列按数字部分进行自然排序(如F1、F3、F20而非F1、F20、F3),其余列保持原有位置不变。
实现步骤与代码
- 拆分列组:把DataFrame的列拆分为三部分——F列之前的非F列、所有F前缀列、F列之后的非F列
- 对F列自然排序:提取F列名中的数字,转为整数后作为排序依据,对F列进行排序
- 重组列顺序:将三部分列按原有顺序拼接,得到最终的列顺序
完整代码如下:
import pandas as pd # 原始DataFrame df = pd.DataFrame({ 'tmp': ['A', 'A', 'B', 'Z', 'D', 'C'], 'F1': [2, 1, 9, 8, 7, 4], 'F20': [0, 1, 9, 4, 2, 3], 'F3': ['a', 'B', 'c', 'D', 'e', 'F'], 'aabb': ['a', 'B', 'c', 'D', 'e', 'F'] }) # 1. 拆分列组 cols = df.columns.tolist() # 找到第一个F开头的列索引 start_idx = next(i for i, col in enumerate(cols) if col.startswith('F')) # 找到最后一个F开头的列索引 end_idx = next(i for i, col in reversed(list(enumerate(cols))) if col.startswith('F')) non_f_before = cols[:start_idx] f_cols = cols[start_idx:end_idx+1] non_f_after = cols[end_idx+1:] # 2. 对F列进行自然排序:提取数字转整数作为排序键 sorted_f_cols = sorted(f_cols, key=lambda x: int(x[1:])) # 3. 重组列顺序并生成新DataFrame new_cols = non_f_before + sorted_f_cols + non_f_after df_sorted = df[new_cols] print(df_sorted)
运行结果
执行后会得到目标DataFrame:
tmp F1 F3 F20 aabb 0 A 2 a 0 a 1 A 1 B 1 B 2 B 9 c 9 c 3 Z 8 D 4 D 4 D 7 e 2 e 5 C 4 F 3 F
说明
- 该方案不依赖F列的具体数量和数字大小,只要F列是连续分组的,就能自动识别并排序
- 排序逻辑通过提取列名中F后的数字转为整数,实现自然排序(避免字符串排序导致F20排在F3前面的问题)
内容的提问来源于stack exchange,提问作者Mario
相关产品推荐
相关产品推荐

