在Pandas数据框架的特定位置插入一个指定的列

在Pandas数据框架的特定位置插入一个指定的列

在这篇文章中,我们将使用Pandas的Dataframe.insert()方法,在数据框架的特定列索引处插入一个新的列。

语法: DataFrame.insert(loc, column, value, allow_duplicates = False)

参数:

  • loc:我们想要放置新列的位置。
  • column:列的名称
  • value:我们需要保留在该列中的值
  • allow_duplicates:一个参数,允许我们在数据框架中保留重复的列。

返回: None

创建一个数据框架

# Importing pandas library
import pandas as pd
 
# dictionary
values = {'col2': [6, 7, 8,
                   9, 10],
          'col3': [11, 12, 13,
                   14, 15]}
 
# Creating dataframe
df = pd.DataFrame(values)
 
# show the dataframe
df
Python

输出:

在Pandas数据框架的特定位置插入一个指定的列

在一个特定的位置插入一个指定的列

用天真的方法插入一个列并进行相应的排列

这里我们在数据框架中添加一个新的列,然后按照我们想要获得列的相同顺序定义一个列表。

# adding a new column
 
df['col1']=0
 
# show the dataframe
df = df[list(('col1','col2','col3'))]
 
# show the dataframe
df
Python

输出:

在Pandas数据框架的特定位置插入一个指定的列

在一个特定的位置插入一个指定的列

使用insert()方法来插入一个列

例子1:在数据框架的开头插入一个列。

# New column to be added
new_col = [1, 2, 3, 4, 5]
 
# Inserting the column at the
# beginning in the DataFrame
df.insert(loc = 0,
          column = 'col1',
          value = new_col)
# show the dataframe
df
Python

输出:

在Pandas数据框架的特定位置插入一个指定的列

在一个特定的位置插入一个指定的列

例子2:在数据框架的中间插入列

# New column to be added
new_col = [1, 2, 3, 4, 5]
 
# Inserting the column at the
# middle of the DataFrame
df.insert(loc = 1,
          column = 'col1',
          value = new_col)
# show the dataframe
df
Python

输出:

在Pandas数据框架的特定位置插入一个指定的列

在一个特定的位置插入一个指定的列

例子3:在数据框架的末端插入列

# New column to be added
new_col = [1, 2, 3, 4, 5]
 
# Inserting the column at the
# end of the DataFrame
# df.columns gives index array
# of column names
df.insert(loc = len(df.columns),
          column = 'col1',
          value = new_col)
# show the dataframe
df
Python

输出:

在Pandas数据框架的特定位置插入一个指定的列

在一个特定的位置插入一个指定的列

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册