Python EXCEL 小技巧:最快重新排列dataframe函数

工作原理

1.获取所有列名。

2.根据输入的列标识(列名或列索引)确定要移动的列名。

3.检查新位置是否有效。

4.先移除要移动的列,然后在新的位置插入该列。

5.返回一个新的DataFrame。

V1.0

python 复制代码
def move_column(df, col_identifier, new_idx):
    """
    移动DataFrame的列到新位置
    
    参数:
    df: pandas DataFrame
    col_identifier: 可以是列名(str)或列索引(int)
    new_idx: 新的位置索引(从0开始)
    
    返回:
    调整列顺序后的新DataFrame
    """
    # 获取所有列名
    cols = list(df.columns)
    
    # 根据输入类型确定要移动的列
    if isinstance(col_identifier, str):
        # 列名输入
        if col_identifier not in cols:
            raise ValueError(f"列名 '{col_identifier}' 不存在于DataFrame中")
        col_to_move = col_identifier
    elif isinstance(col_identifier, int):
        # 列索引输入
        if col_identifier < 0 or col_identifier >= len(cols):
            raise IndexError(f"列索引 {col_identifier} 超出范围")
        col_to_move = cols[col_identifier]
    else:
        raise TypeError("col_identifier 必须是字符串(列名)或整数(列索引)")
    
    # 确保新位置有效
    if new_idx < 0 or new_idx > len(cols):
        raise IndexError(f"新位置索引 {new_idx} 无效")
    
    # 创建新列顺序
    new_cols = [col for col in cols if col != col_to_move]  # 移除要移动的列
    new_cols.insert(new_idx, col_to_move)  # 在指定位置插入该列
    
    return df[new_cols]

使用示例

python 复制代码
import pandas as pd

# 创建示例DataFrame
data = {
    '姓名': ['张三', '李四', '王五'],
    '年龄': [25, 30, 28],
    '性别': ['男', '男', '女'],
    'sim': [0.8, 0.9, 0.7],  # 第四列
    '城市': ['北京', '上海', '广州']
}
df = pd.DataFrame(data)

print("原始列顺序:")
print(df.columns.tolist())  # ['姓名', '年龄', '性别', 'sim', '城市']

# 使用列名移动
df_moved = move_column(df, 'sim', 1)  # 将'sim'列移动到第2个位置
print("\n移动后列顺序:")
print(df_moved.columns.tolist())  # ['姓名', 'sim', '年龄', '性别', '城市']

# 使用列索引移动(效果相同)
df_moved2 = move_column(df, 3, 1)  # 将第4列移动到第2个位置
print("\n使用索引移动后列顺序:")
print(df_moved2.columns.tolist())  # ['姓名', 'sim', '年龄', '性别', '城市']

函数特点

  1. 双重支持:同时支持列名(str)和列索引(int)作为输入
  2. 错误处理:
    • 检查列名是否存在
    • 验证列索引是否有效
    • 确保新位置在合理范围内
  3. 清晰文档:包含详细的函数说明和参数解释
  4. 高效实现:使用列表推导式高效创建新列顺序

使用建议

  • 当列名已知时,推荐使用列名作为输入,这样代码更易读且不受列顺序变化影响
  • 当需要根据位置移动列时,可以使用列索引
  • 该函数不会修改原始DataFrame,而是返回一个新的DataFrame

2.0

使用pop和insert(更简洁)

python 复制代码
def move_column_efficient(df, col_identifier, new_idx):
    """
    使用pop和insert高效移动列
    """
    cols = list(df.columns)
    
    # 确定要移动的列索引
    if isinstance(col_identifier, str):
        if col_identifier not in cols:
            raise ValueError(f"列名 '{col_identifier}' 不存在于DataFrame中")
        old_idx = cols.index(col_identifier)
    elif isinstance(col_identifier, int):
        if col_identifier < 0 or col_identifier >= len(cols):
            raise IndexError(f"列索引 {col_identifier} 超出范围")
        old_idx = col_identifier
    else:
        raise TypeError("col_identifier 必须是字符串(列名)或整数(列索引)")
    
    # 确保新位置有效
    if new_idx < 0 or new_idx > len(cols):
        raise IndexError(f"新位置索引 {new_idx} 无效")
    
    # 使用pop和insert一次性完成操作
    col_name = cols.pop(old_idx)
    cols.insert(new_idx, col_name)
    
    return df[cols]

2.1

python 复制代码
def move_column_efficient(df, col_identifier, new_idx):
    """
    高效移动DataFrame列位置
    
    参数:
    df: pandas DataFrame
    col_identifier: 列名(str)或列索引(int)
    new_idx: 目标位置索引(0-based)
    
    返回:
    调整列顺序后的新DataFrame
    """
    cols = list(df.columns)
    
    # 处理列标识符
    if isinstance(col_identifier, str):
        if col_identifier not in cols:
            raise ValueError(f"列名 '{col_identifier}' 不存在")
        old_idx = cols.index(col_identifier)
    elif isinstance(col_identifier, int):
        if not (0 <= col_identifier < len(cols)):
            raise IndexError(f"列索引 {col_identifier} 超出范围[0, {len(cols)-1}]")
        old_idx = col_identifier
    else:
        raise TypeError("参数必须是列名字符串或列索引整数")
    
    # 处理新位置索引
    if not (0 <= new_idx <= len(cols)):
        raise IndexError(f"新位置索引 {new_idx} 应在[0, {len(cols)}]范围内")
    
    # 高效移动列
    if old_idx != new_idx:  # 仅当位置不同时操作
        col_name = cols.pop(old_idx)
        # 调整新位置索引(如果旧索引在新索引之前)
        adj_new_idx = new_idx - 1 if old_idx < new_idx else new_idx
        cols.insert(adj_new_idx, col_name)
    
    return df[cols]
python 复制代码
def move_column_efficient(df, col_identifier, new_idx):
    """
    Efficiently repositions a column within a DataFrame.
    
    Parameters:
    df: pandas DataFrame
        The input DataFrame.
    col_identifier: str or int
        Column name (string) or column index (integer).
    new_idx: int
        Target position index (0-based).
    
    Returns:
    DataFrame
        A new DataFrame with the column order adjusted.
    """
    cols = list(df.columns)
    
    # Handle column identifier
    if isinstance(col_identifier, str):
        if col_identifier not in cols:
            raise ValueError(f"Column name '{col_identifier}' does not exist")
        old_idx = cols.index(col_identifier)
    elif isinstance(col_identifier, int):
        if not (0 <= col_identifier < len(cols)):
            raise IndexError(f"Column index {col_identifier} is out of range [0, {len(cols)-1}]")
        old_idx = col_identifier
    else:
        raise TypeError("Parameter must be a column name string or column index integer")
    
    # Validate target position index
    if not (0 <= new_idx <= len(cols)):
        raise IndexError(f"Target position index {new_idx} must be within [0, {len(cols)}]")
    
    # Efficiently reposition column
    if old_idx != new_idx:  # Only perform operation if positions differ
        col_name = cols.pop(old_idx)
        # Adjust target index if original index precedes the target position
        adj_new_idx = new_idx - 1 if old_idx < new_idx else new_idx
        cols.insert(adj_new_idx, col_name)
    
    return df[cols]

改进点说明

  1. 添加位置变化检查:避免不必要的列顺序调整
python 复制代码
if old_idx != new_idx:  # 仅当位置不同时操作
  1. 更精确的新位置索引处理:解决当旧索引在新索引之前时,pop操作后索引偏移的问题
python 复制代码
   adj_new_idx = new_idx - 1 if old_idx < new_idx else new_idx
  1. 更详细的错误信息:提供更具体的范围提示
python 复制代码
raise IndexError(f"列索引 {col_identifier} 超出范围[0, {len(cols)-1}]")
相关推荐
小薛引路2 小时前
office便捷办公06:根据相似度去掉excel中的重复行
windows·python·excel
Hs_QY_FX2 小时前
Python 分类模型评估:从理论到实战(以信用卡欺诈检测为例)
人工智能·python·机器学习·数据挖掘·多分类评估
Gitpchy2 小时前
Day 18 推断聚类后簇的类型
python·机器学习·聚类
查士丁尼·绵2 小时前
笔试-基站维护
python
deephub2 小时前
REFRAG技术详解:如何通过压缩让RAG处理速度提升30倍
人工智能·python·大语言模型·rag
唐叔在学习2 小时前
venv - Python最佳的轻量化环境隔离方式
后端·python
小白学大数据2 小时前
Python爬虫数据可视化:深度分析贝壳成交价格趋势与分布
爬虫·python·信息可视化
小小测试开发2 小时前
Python Arrow库:告别datetime繁琐,优雅处理时间与时区
开发语言·前端·python
我的xiaodoujiao2 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 18--测试框架Pytest基础 2--插件和参数化
python·学习·测试工具·pytest
程序员的奶茶馆3 小时前
Python 数据结构面试真题:如何实现 LRU 缓存机制
python·面试