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

Pandas 1.5.2中如何在DataFrame.assign里引用新创建的列?

Pandas 1.5.2中assign方法引用新创建列的正确方式

你的代码报错AttributeError: 'DataFrame' object has no attribute 'test1',原因是直接通过df.test1访问的是原始DataFrame,而assign方法里的新列是逐步添加到临时构建的对象中的,原始df在这个过程中并未被修改,自然不存在test1列。

官方文档提到的“后续参数可以引用新创建的列”,需要通过lambda函数实现——lambda的参数代表当前assign过程中正在构建的DataFrame,能直接访问前面已经添加的列。

正确代码示例:

import pandas as pd

df = pd.DataFrame({"col1":[1,2,3], "col2": [4,5,6]})
result = df.assign(
    test1="hello",
    test2=lambda x: x.test1 + " world"
)
print(result)

运行后输出:

col1  col2  test1        test2
0     1     4  hello  hello world
1     2     5  hello  hello world
2     3     6  hello  hello world

这里lambda x中的x就是包含了test1列的临时DataFrame,因此可以正常引用x.test1来生成test2。

内容的提问来源于stack exchange,提问作者scūriolus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:55:22