在本教程中,我们将讨论向 pandas 数据框添加新列的不同方法。
什么是 pandas 数据框?
Pandas 数据框架 是一种二维异构数据结构,它以带有标记索引(即行和列)的表格形式存储数据。
通常,当我们必须处理大型数据集时,会使用数据框,然后我们可以通过将其加载到 pandas 数据框并查看数据框的摘要来简单地查看该大数据集的摘要。
在现实场景中,pandas 数据框是通过从现有的 CSV 文件、Excel 文件等加载数据集来创建的。
但是 pandas 数据框也可以从list、dictionary、列表列表、字典列表、ndarray/lists 字典等创建。在我们开始讨论如何向现有数据框添加新列之前,我们需要一个 pandas数据框架。
安装并导入 pandas
我们需要Python的Pandas库来处理数据框,因此我们必须首先安装Pandas库,然后将其导入Python程序。以下是安装和导入 pandas 的命令:
# Installing pandas Python library pip install pandas |
# Importing pandas into the program import pandas as pd |
在我们开始讨论如何向现有 pandas 数据框添加新列之前,我们需要一个 pandas 数据框。
从列表字典创建数据框
# Creating a dictionary of lists data = { 'name' : [ 'Sanjay' , 'Ravi' , 'Shreya' , 'Abhishek' , 'Shantanu' ], 'roll' : [ 55 , 65 , 75 , 85 , 95 ]} # Creating a pandas data frame from the above data df = pd.DataFrame(data) print (df) |
输出:
现在让我们讨论向上面创建的现有数据框添加新列的不同方法。有多种方法可以向现有数据框架添加新列,但在这里我们将仅讨论三种主要的稳健且强大的方法。
使用 DataFrame 索引添加新列
这是向现有 pandas 数据框添加新列的最简单方法,我们只需使用新列的名称对现有数据框进行索引,并分配要存储在相应行的列中的值列表:
# Adding a new column named 'cgpa' to the data frame # Using DataFrame indexing df[ 'cgpa' ] = [ 8.1 , 9.3 , 8.2 , 7.9 , 7.5 ] print (df) |
输出:
使用 allocate() 将新列添加到 pandas 数据框
这是使用 pandas 内置assign()
方法向现有数据框添加新列的第二种可靠方法。这会向现有数据框添加一个新列,然后返回包含添加列的新数据框。让我们看看使用它的 Python 代码:
# Adding a new column named 'address' to the data frame # Using the assign() method # And saving the new returned data frame df2 = df.assign(address = [ 'Bihar' , 'Bihar' , 'Jharkhand' , 'UP' , 'UP' ]) print (df2) |
输出:
使用 insert() 方法添加新列
这是向现有数据框添加新列的第三种强大方法。与以前向数据框中添加列的方法不同,该方法只是将新列添加到数据框的末尾作为最后一列,该方法允许我们在insert()
现有数据框中的任何指定位置添加新列。让我们看看使用它的 Python 代码:
# Adding a column named 'branch'to the data frame # Using the insert() method # First argument is the column position # Second argument is the column name # And third argument is the column value df2.insert( 3 , 'branch' , [ 'ECE' , 'CSE' , 'ECE' , 'EE' , 'ECE' ]) print (df2) |
输出:
在输出中,可以清楚地看到名为branch的新列已添加到Python 代码中指定的第三列索引处。
结论
因此,在本教程中,我们学习了什么是 pandas 数据框、如何从列表字典创建新数据框,以及向现有数据框添加新列的三种可靠方法:索引、方法DataFrame
和assign()
方法insert()
。