Pandas DataFrame插入列的完整指南:insert函数与条件赋值

清欢
清欢
发布时间:2026-10-15| 2人浏览过
原创

本文详细介绍如何在Pandas DataFrame中插入新列。通过解析insert(loc, column, value)函数的核心参数,演示了将列插入首列、中间及末尾的具体代码示例。此外,补充了基于条件判断对特定数据子集进行列赋值的实用技巧,帮助开发者灵活处理表格数据结构。

引言

在实际数据处理中,向Pandas DataFrame添加新列是常见需求。借助pandas内置的insert()方法,可以高效地完成这一操作,其基本调用格式如下所示。

insert(loc, column, value, allow_duplicates=False)

各参数含义如下:

  • loc:指定新列插入的位置索引,首列索引为0。
  • column:指定新列的名称。
  • value:提供新列的数据数组或列表。
  • allow_duplicates:布尔值,控制是否允许新列名与现有列名重复,默认为False。

下文将通过具体案例展示该函数的实际应用方式。

示例 1:插入新列作为第一列

以下代码演示如何将新列插入到现有DataFrame的第一列位置:

import pandas as pd
 
#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
                   'assists': [5, 7, 7, 9, 12],
                   'rebounds': [11, 8, 10, 6, 6]})
 
#view DataFrame
df
        points	assists	rebounds
0	25	5	11
1	12	7	8
2	15	7	10
3	14	9	6
4	19	12	6
 
#insert new column 'player' as first column
player_vals = ['A', 'B', 'C', 'D', 'E']
df.insert(loc=0, column='player', value=player_vals)
df
 
        player	points	assists	rebounds
0	A	25	5	11
1	B	12	7	8
2	C	15	7	10
3	D	14	9	6
4	E	19	12	6

示例 2:插入新列作为中间列

以下代码演示如何将新列插入到现有DataFrame的第三列位置:

import pandas as pd
 
#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
                   'assists': [5, 7, 7, 9, 12],
                   'rebounds': [11, 8, 10, 6, 6]})
 
#insert new column 'player' as third column
player_vals = ['A', 'B', 'C', 'D', 'E']
df.insert(loc=2, column='player', value=player_vals)
df
 
        points	assists	player	rebounds
0	25	5	A	11
1	12	7	B	8
2	15	7	C	10
3	14	9	D	6
4	19	12	E	6

示例 3:插入新列作为最后一列

以下代码演示如何将新列插入到现有DataFrame的最后一列位置:

import pandas as pd
 
#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
                   'assists': [5, 7, 7, 9, 12],
                   'rebounds': [11, 8, 10, 6, 6]})
 
#insert new column 'player' as last column
player_vals = ['A', 'B', 'C', 'D', 'E']
df.insert(loc=len(df.columns), column='player', value=player_vals)
df
 
        points	assists	player	rebounds
0	25	5	A	11
1	12	7	B	8
2	15	7	C	10
3	14	9	D	6
4	19	12	E	6

值得注意的是,使用len(df.columns)作为loc参数,可以确保无论DataFrame包含多少列,新列始终被追加至末尾。

如需查阅insert()函数的完整文档,可访问官方帮助页面。

补充:按条件选择分组分别赋值

除了直接插入,有时需要根据特定条件筛选数据,并对筛选出的部分赋予新列值。

实例:当最高温与最低温之差大于10度时,标记为“温差大”。

# 先创建空列(这是第一种创建新列的方法)
df['wencha_type'] = ''

df.loc[df["bWendu"]-df["yWendu"]>10, "wencha_type"] = "温差大"

df.loc[df["bWendu"]-df["yWendu"]<=10, "wencha_type"] = "温差正常"

总结

本文介绍了Pandas DataFrame插入列的相关操作,更多相关内容可参考本站过往文章或继续浏览后续教程,感谢支持。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。