Pandas 数据帧insert()
方法
原文:https://www.studytonight.com/pandas/pandas-dataframe-insert-method
在本教程中,我们将学习 PandasDataFrame.insert()
的方法。此方法将列插入到指定位置的数据帧中。如果该列已经包含在数据帧中,它将引发ValueError
,除非 allow_duplicates 设置为 True。
下图显示了DataFrame.insert()
方法的语法。
句法
DataFrame.insert(loc, column, value, allow_duplicates=False)
因素
loc: int。插入索引。必须验证 0 < = loc < = len(列)。
列:字符串、数字或散列对象。插入列的标签。
值: int、Series 或类似数组
允许重复: bool,可选
示例 1:在数据帧中插入新列
我们可以使用DataFrame.insert()
方法向数据帧中插入一个新列。看,在下面的例子中它是如何工作的。
#importing pandas as pd
import pandas as pd
df=pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8]})
print("The DataFrame is")
print(df)
print("Adding column to the DataFrame")
df.insert(2,'C',1)
print(df)
一旦我们运行该程序,我们将获得以下输出。
数据帧为 A B 0 1 5 1 2 6 2 3 7 3 4 8 在数据帧中添加列 A B C 0 1 5 1 1 2 6 1 2 3 7 1 3 4 8 1
示例 2:在数据帧中插入新列
我们可以使用DataFrame.insert()
方法插入Series
作为数据帧的一列。它将在添加列后返回一个新的数据帧。
#importing pandas as pd
import pandas as pd
df=pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8]})
print("The DataFrame is")
print(df)
print("Adding column to the DataFrame")
df.insert(0,'C',1)
print(df)
一旦我们运行该程序,我们将获得以下输出。
数据帧为 A B 0 1 5 1 2 6 2 3 7 3 4 8 在数据帧中添加列 C A B 0 1 5 1 1 2 6 2 1 3 7 3 1 4 8
示例:将列插入数据帧时出错
如果列已经包含在数据帧中,则DataFrame.insert()
方法会引发ValueError
。
#importing pandas as pd
import pandas as pd
df=pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8]})
print("Adding column to the DataFrame")
df.insert(2,'A',1)
print(df)
一旦我们运行该程序,我们将获得以下输出。
值错误:不能插入 A,已经存在
结论
在本教程中,我们学习了 PandasDataFrame.insert()
方法。我们学习了语法,并在示例中应用了该方法。