You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas是否有类似R tidyverse中relocate()的列顺序调整方法?

Pandas 实现 R tidyverse relocate() 功能的原生方法

Pandas 全版本都支持原生方法实现和 tidyverse 中 relocate() 完全一致的列移动效果,常用实现方式如下:

  • 单字段移动通用写法(全版本兼容)
    对应R示例 df %>% relocate("col1", .after="col2") 的Pandas实现代码:
    # 取出待移动的列
    target_col = df.pop("col1")
    # 计算插入位置:col2的索引+1就是col2之后的位置
    insert_pos = df.columns.get_loc("col2") + 1
    # 插入到目标位置
    df.insert(loc=insert_pos, column="col1", value=target_col)
    
    调整插入位置参数即可匹配relocate的不同用法:
    • 匹配.before="col2":去掉+1,直接用df.columns.get_loc("col2")作为插入位置
    • 匹配移动到第一列:插入位置设为0
    • 匹配移动到最后一列:插入位置设为len(df.columns)
  • 多字段批量移动写法
    如果需要同时调整多个列的位置,直接重排列名列表后赋值即可,写法更简洁:
    # 示例:将col1、col3移动到最前面,剩余列保持原有顺序
    move_cols = ["col1", "col3"]
    new_cols_order = move_cols + [col for col in df.columns if col not in move_cols]
    df = df[new_cols_order]
    

内容的提问来源于stack exchange,提问作者baggiponte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:18:02