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

pandas DataFrame三列以下划线拼接方法及NoneType赋值报错解决

问题解决方法

1 报错原因修复

你遇到的TypeError: 'NoneType' object does not support item assignment报错,根本原因是操作对象self.df为None值,无法对其执行新增列的赋值操作。可按以下两点排查修复:

  • 检查之前的代码是否存在将返回None的操作赋值给self.df的情况:pandas中带inplace=True参数的方法会直接修改原对象,返回值为None,错误示例:self.df = df.drop(columns=['test'], inplace=True),这类写法会把self.df覆盖为None,要么去掉inplace=True参数接收返回的新对象,要么不把inplace操作的结果赋值给变量。
  • 操作前先确认self.df被正确赋值,可先执行self.df = df.copy()把原始数据同步到类属性中。

2 列拼接最优实现

不推荐用apply+lambda的方式实现行拼接,性能较低,pandas原生字符串拼接方法效率更高,代码也更简洁,正确实现如下:

import pandas as pd

# 先完成self.df的正确赋值
self.df = df.copy()

# 方法1:直接用加号拼接,写法直观
self.df["ID"] = self.df["cell_id:cell_id"].astype(str) + "_" \
                + self.df["region:region"].astype(str) + "_" \
                + self.df["tile_num:tile_num"].astype(str)

# 方法2:用str.cat方法,适合拼接列较多的场景
# self.df["ID"] = self.df["cell_id:cell_id"].astype(str).str.cat(
#     [self.df["region:region"].astype(str), self.df["tile_num:tile_num"].astype(str)],
#     sep="_"
# )

# 提取需要的列得到最终结果
result_df = self.df[["ID", "ABC"]]

执行后得到的result_df就是你需要的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:06:02