概述
在上一节,我们介绍了Python的numpy模块,包括:多维数组、数组索引、数组操作、数学函数、线性代数、随机数生成等内容。在这一节,我们将介绍Python的pandas模块。pandas模块是Python编程语言中用于数据处理和分析的强大模块,它提供了许多用于数据操作和清洗的函数,使得数据处理和分析变得更为简单和直观。
在Python中使用pandas模块,需要先安装pandas库。可以通过pip命令进行安装:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas。安装完成后,就可以在Python脚本中导入pandas模块,并使用其函数和方法了。
Series
Series是一个一维数组,它不仅包含数据,还包含索引。Series可以被看作是一个字典,其中的索引是键,值是数据。每个索引只有一个对应的值,因此Series可以被看作是具有标签化的数值数据。
上面的示例代码创建了一个包含五个整数的Series,默认情况下,它的索引是从0开始的整数。
当然,我们也可以提供一个列表作为Series的索引和值。
我们还可以直接使用字典创建带有自定义数据标签的数据,pandas会自动把字典的键作为数据标签,字典的值作为相对应的数据。
如果想访问Series里的数据,也非常简单,直接使用中括号加数据标签的方式即可。
使用Series,结合pandas强大的数据对齐功能,可以让我们快速对数据进行分析和处理。
DataFrame
DataFrame是一个二维的表格型数据结构,类似于Excel或数据库中的表。DataFrame中的数据可以是不同的数据类型,比如:整数、浮点数、字符串、布尔值等。
使用DataFrame,我们可以很方便地对表中的行、列进行增删改查等操作。使用df['column_name']可以查看指定列的数据;使用df.iloc[row_number]可以查看指定行的数据;使用df.loc[row_label]可以基于标签访问指定行的数据;使用df[condition]可以筛选出满足条件的数据:使用df['new_column'] = values可以添加一个新列;使用del df['column_name']可以删除一列。
数据读取和写入
使用pandas,可以方便地读取和写入各种数据格式,比如:CSV、Excel、SQL数据库等。我们以CSV文件的读写为例,来理解CSV表格数据的读取和写入。
在上面的示例代码中,我们首先创建了一个名为df的DataFrame,然后使用to_csv函数将其写入一个名为output.csv的CSV文件中。我们将index参数设置为False,以避免将DataFrame的索引写入CSV文件。
to_csv函数还有其他一些可选参数,包括:
sep:用于指定CSV文件中的分隔符,默认是逗号。
header:用于指定是否将DataFrame的列名写入CSV文件中,默认为True。
encoding:用于指定文件的编码格式,默认为UTF-8。
compression:用于指定文件的压缩格式,默认为None。
在下面的示例代码中,我们读取了上面保存的名为output.csv的CSV文件,并将其转化为一个pandas DataFrame。
read_csv函数还有其他一些可选参数,包括:
sep:指定分隔符,默认为逗号。
header:指定行号作为列名,默认为0。
index_col:将一列或多列设为DataFrame的索引。
usecols:返回的列的子集,可以是一个列表或函数。
dtype:为每一列设置数据类型。
skiprows:跳过指定的行数或行号。
na_values:用于识别空值的字符串或字符串列表。
keep_default_na:是否保留默认的识别空值的字符串。
💡 如果想阅读最新的文章,或者有技术问题需要交流和沟通,可搜索并关注微信公众号“希望睿智”。