pandas——改写pandas源文件以实现:使用pd.DataFrame.itertuples但不自动修正列名

使用pd.DataFrame.itertuples不自动修正列名

何为pandas.DataFrame.itertuples?

相较于 pandas.DataFrame.iterrows 而言,pandas.DataFrame.itertuples更好地提供了按行遍历DataFrame 的功能,详见pandas------按行遍历dataframe的优选方法(itertuples,iterrows)

这这里,我们需要了解的是,itertuples返回的是一个namedtuple迭代器。同时可以传递两个参数:name和index。其中,index决定了是否包含索引,而name决定了namedtuple的名称。

何为namedtuple?

那么到这里,就需要提到关于namedtuple的基本信息。

可以查看python------什么是namedtuple?了解它,理解它,掌握它

一旦了解过namedtuple后,我们就可以知道namedtuple有一个参数:rename。这个参数决定了是否将无效的字段名自动替换为位置名称。

问题所在

先看一下pandas.DataFrame.itertuples的源代码,方便起见我只摘取需要关注的一部分:

python 复制代码
def itertuples(
        self, index: bool = True, name: str | None = "Pandas", rename: bool = True
    ) -> Iterable[tuple[Any, ...]]:
    arrays = []
        fields = list(self.columns)
        if index:
            arrays.append(self.index)
            fields.insert(0, "Index")
            arrays.extend(self.iloc[:, k] for k in range(len(self.columns)))

        if name is not None:
            # https://github.com/python/mypy/issues/9046
            # error: namedtuple() expects a string literal as the first argument
            itertuple = collections.namedtuple(  # type: ignore[misc]
                name, fields, rename=True
            )
            return map(itertuple._make, zip(*arrays))

        # fallback to regular tuples
        return zip(*arrays)

如上所示,它直接定义了rename=True,也就默认让itertuples自动修正无效的字段名。

那么我们就需要将rename参数重新在itertuples中恢复,同时也不能影响pandas的正常使用

解决办法

直接将 rename=True改为rename=False即可。

友情提示

rename这个参数为True时,可以自动修正。但为False时,如果列名不符合python的命名规则,直接报错,并不是按照原名称进行输出。所以在使用时谨慎使用。

相关推荐
codists27 分钟前
2025年9月文章一览
python
语落心生29 分钟前
FastDeploy SD & Flux 扩散模型边缘端轻量化推理部署实现
python
java1234_小锋42 分钟前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 立即执行模式(Eager Execution)
python·深度学习·tensorflow·tensorflow2
王大傻09281 小时前
numpy -- 算术函数 reciprocal() 和 power() 简介
python·numpy
咕白m6251 小时前
Python 将 Excel 转换为图片:实现数据可视化
后端·python
深蓝电商API1 小时前
不止是 Python:聊聊 Node.js/Puppeteer 在爬虫领域的应用
爬虫·python·node.js
Autumn72992 小时前
【材料学python入门】conda、 jupyter、cpu、GPAW、wsl、ubuntu
python·jupyter·conda
K2I-2 小时前
UCI中Steel Plates Faults不平衡数据集处理
python
蓑笠翁0012 小时前
Django REST Framework 全面指南:从模型到完整API接口开发
后端·python·django
感谢地心引力3 小时前
【Python】基于 PyQt6 和 Conda 的 PyInstaller 打包工具
数据库·python·conda·pyqt·pyinstaller