Python Pandas DataFrame 创建、索引、增删操作详解

Felix
Felix
发布时间:2026-10-13| 3人浏览过
原创

本文详细解析 Python 中 Pandas DataFrame 的核心操作。涵盖从字典和多维数组创建 DataFrame 的方法,重点讲解列与行的索引技巧,特别是 iloc 与 loc 的区别及赋值警告处理。同时演示如何新增多列数据及删除指定的行与列,提供实用的代码示例与避坑指南。

前言

近期在网上搜索关于 pandas.DataFrame 的操作指南时,发现多数内容仅涉及基础用法。然而,将这些基础操作组合起来以正确处理 DataFrame 往往耗时较长,且容易引发 BUG。为此,本文对常见操作进行系统总结,旨在帮助读者更高效地掌握相关技巧。

一、创建 DataFrame 的简单操作:

1、根据字典创建:

In [1]: import pandas as pd
In [3]: aa={'one':[1,2,3],'two':[2,3,4],'three':[3,4,5]}
In [4]: bb=pd.DataFrame(aa)
In [5]: bb
Out[5]: 
 one three two
0 1 3 2
1 2 4 3
2 3 5 4`

利用字典创建时,字典的键(keys)将自动成为 DataFrame 的列名(columns)。若未指定索引(index),系统将默认从 0 开始计数生成索引。

bb=pd.DataFrame(aa,index=['first','second','third'])
bb
Out[7]: 
 one three two
first 1 3 2
second 2 4 3
third 3 5 4

2、从多维数组中创建

import numpy as np
In [9]: del aa
In [10]: aa=np.array([[1,2,3],[4,5,6],[7,8,9]])
In [11]: aa
Out[11]: 
array([[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]])
In [12]: bb=pd.DataFrame(aa)
In [13]: bb
Out[13]: 
 0 1 2
0 1 2 3
1 4 5 6
2 7 8 9

从多维数组构建 DataFrame 时,建议显式指定 columns 和 index 参数。若不指定,生成的默认索引和列名通常不够直观,影响可读性。

bb=pd.DataFrame(aa,index=[22,33,44],columns=['one','two','three'])
In [15]: bb
Out[15]: 
 one two three
22 1 2 3
33 4 5 6
44 7 8 9

3、用其他的 DataFrame 创建

bb=pd.DataFrame(aa,index=[22,33,44],columns=['one','two','three'])
bb
Out[15]: 
 one two three
22 1 2 3
33 4 5 6
44 7 8 9
cc=bb[['one','three']].copy()
Cc
Out[17]: 
 one three
22 1 3
33 4 6
44 7 9

通过现有 DataFrame 创建新实例时,建议使用 copy() 方法进行深拷贝。这样修改新 DataFrame(如 cc)的值不会影响原始 DataFrame(如 bb)。

cc['three'][22]=5
bb
Out[19]: 
 one two three
22 1 2 3
33 4 5 6
44 7 8 9

cc
Out[20]: 
 one three
22 1 5
33 4 6
44 7 9

二、DataFrame 的索引操作:

对于 DataFrame 而言,索引操作最为复杂且容易出错,需格外注意。

1、索引一列或几列,比较简单:

bb['one']
Out[21]: 
22 1
33 4
44 7
Name: one, dtype: int32

当需要索引多个列时,必须将列名放入列表中。否则,直接传入多个列名会导致报错,因为 Pandas 期望接收一个可迭代的变量。

bb[['one','three']]
Out[29]: 
 one three
22 1 3
33 4 6
44 7 9

2、索引一条记录或几条记录:

bb[1:3]
Out[27]: 
 one two three
33 4 5 6
44 7 8 9
bb[:1]
Out[28]: 
 one two three
22 1 2 3

在索引行记录时,冒号(:)是必需的语法元素。若省略冒号,系统可能会错误地将其识别为列索引操作。

3、索引某几列的变量的某几条记录,这个折磨了我好久:

第一种

bb.loc[[22,33]][['one','three']]
Out[30]: 
 one three
22 1 3
33 4 6

这种方式仅支持读取值,无法直接修改其中的数据。这可能与 loc() 函数的特性有关,导致赋值操作受限。

bb.loc[[22,33]][['one','three']]=[[2,2],[3,6]]
In [32]: bb
Out[32]: 
 one two three
22 1 2 3
33 4 5 6
44 7 8 9

第二种:也是只能看

bb[['one','three']][:2]
Out[33]: 
 one three
22 1 3
33 4 6

尝试在这种模式下修改数据会触发报错,因此该方法仅适用于读取场景。

In [34]: bb[['one','three']][:2]=[[2,2],[2,2]]
-c:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
F:\Anaconda\lib\site-packages\pandas\core\frame.py:1999: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
 return self._setitem_slice(indexer, value)

第三种:可以改变数据的值!!!

iloc 方法依据数据的实际行列位置进行索引,不依赖于 index 和 columns 的名称。

bb.iloc[2:3,2:3]
Out[36]: 
 three
44 9

bb.iloc[1:3,1:3]
Out[37]: 
 two three
33 5 6
44 8 9
bb.iloc[0,0]
Out[38]: 1

下面是证明:

bb.iloc[0:4,0:2]=[[9,9],[9,9],[9,9]]
In [45]: bb
Out[45]: 
 one two three
22 9 9 3
33 9 9 6
44 9 9 9

三、在原有的 DataFrame 上新建一个 columns 或几个 columns

1、什么都不用的,只能单独创建一列,多列并不好使,亲测无效:

bb['new']=[2,3,4]
bb
Out[51]: 
 one two three new
22 9 9 3 2
33 9 9 6 3
44 9 9 9 4
bb[['new','new2']]=[[2,3,4],[5,3,7]]
KeyError: "['new' 'new2'] not in index"

直接赋予列表时,数据会按照给定的 index 顺序进行赋值。但通常我们需要根据特定的 index 进行对应赋值,更高级的赋值方法见下文。

2、使用字典进行多列按 index 赋值:

aa={33:[234,44,55],44:[657,77,77],22:[33,55,457]}
In [58]: bb=bb.join(pd.DataFrame(aa.values(),columns=['hi','hello','ok'],index=aa.keys()))
In [59]: bb
Out[59]: 
 one two three new hi hello ok
22 9 9 3 2 33 55 457
33 9 9 6 3 234 44 55
44 9 9 9 4 657 77 77

此处 aa 是一个字典与列表的嵌套结构,代表一条记录。使用字典的 keys 作为 index 名,而非默认的 columns 名,从而实现按 index 的多列匹配。由于 dict() 的存储顺序可能混乱,直接使用 dict() 且不指定 index 可能导致记录错乱,这一点需特别注意。

四、删除多列或多记录:

删除列

bb.drop(['new','hi'],axis=1)
Out[60]: 
 one two three hello ok
22 9 9 3 55 457
33 9 9 6 44 55
44 9 9 9 77 77

删除记录

bb.drop([22,33],axis=0)
Out[61]: 
 one two three new hi hello ok
44 9 9 9 4 657 77 77

此外,还有一篇关于 Python 中 Pandas DataFrame 对行与列求和及添加新行与列的示例文章,感兴趣的朋友可以参考。

DataFrame 的功能远不止于此,后续若涉及其他功能或阅读官网 API 后有新的发现,将继续分享。

总结

以上就是本文的全部内容,希望这些内容能对各位的学习或工作有所帮助。如有任何疑问,欢迎留言交流,感谢大家的支持。

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

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 算法库。