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

R用户转Python:如何用字符串变量重命名DataFrame列

解决方案:在Python中动态重命名DataFrame列

对应你在R中用dplyr实现的将存储在变量中的原列名,重命名为指定新列名的需求,以下是几种Python pandas的实现方式:

基础实现方法

核心思路是利用pd.DataFrame.rename(),通过字典映射原列名与新列名:

import pandas as pd

df = pd.DataFrame(
    {
        "a": [8,5,7,8],
        "b": [9,6,6,8],
        "c": [0,7,8,9],
    }
)

# 存储原列名的变量,对应R中的variable = "c"
variable = "c"
# 重命名:将原列"c"改为新列名"variable"
out = df.rename(columns={variable: "variable"})
print(out)

运行后输出:

a  b  variable
0  8  9         0
1  5  6         7
2  7  6         8
3  8  8         9

动态新列名扩展

如果新列名也需要从变量中读取(而非固定字符串),可以定义变量存储新列名:

variable = "c"
new_col_name = "variable"  # 新列名字符串存在变量中
out = df.rename(columns={variable: new_col_name})

贴近R管道风格的写法

如果你习惯R的链式调用(%>%),可以用pandas的pipe()方法实现类似逻辑:

out = df.pipe(lambda df: df.rename(columns={variable: "variable"}))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:36:13