📜  Python|熊猫 dataframe.insert()

📅  最后修改于: 2022-05-13 01:55:04.431000             🧑  作者: Mango

Python|熊猫 dataframe.insert()

Pandas 插入方法允许用户在数据框或系列(一维数据框)中插入一列。也可以通过下面的方法在数据框中手动插入一列,但是这里没有太大的自由度。
例如,即使列位置也无法确定,因此插入的列总是插入到最后一个位置。
句法:

DataFrameName.insert(loc, column, value, allow_duplicates = False)

参数:

从此处找到使用的 csv 文件的链接。

插入具有静态值的列:

Python3
# importing pandas module
import pandas as pd
  
# reading csv file
data = pd.read_csv("pokemon.csv")
  
# displaying  dataframe - Output 1
data.head()


Python3
# importing pandas module
import pandas as pd
 
# reading csv file
data = pd.read_csv("pokemon.csv")
 
# displaying  dataframe - Output 1
data.head()
 
# inserting column with static value in data frame
data.insert(2, "Team", "Any")
 
# displaying data frame again - Output 2
data.head()


Python
# importing pandas module
import pandas as pd
 
# creating a blank series
Type_new = pd.Series([])
 
# reading csv file
data = pd.read_csv("pokemon.csv")
 
 
# running a for loop and assigning some values to series
for i in range(len(data)):
    if data["Type"][i] == "Grass":
        Type_new[i]="Green"
 
    elif data["Type"][i] == "Fire":
        Type_new[i]="Orange"
 
    elif data["Type"][i] == "Water":
        Type_new[i]="Blue"
 
    else:
        Type_new[i]= data["Type"][i]
 
         
# inserting new column with values of list made above       
data.insert(2, "Type New", Type_new)
 
# list output
data.head()


输出:

插入列后:

Python3

# importing pandas module
import pandas as pd
 
# reading csv file
data = pd.read_csv("pokemon.csv")
 
# displaying  dataframe - Output 1
data.head()
 
# inserting column with static value in data frame
data.insert(2, "Team", "Any")
 
# displaying data frame again - Output 2
data.head()

为每一行传递具有不同值的系列:

在此示例中,创建了一个系列,并通过 for 循环将一些值传递给该系列。之后,将系列传递给 pandas 插入函数,以将系列附加到数据框中并传递值。

Python

# importing pandas module
import pandas as pd
 
# creating a blank series
Type_new = pd.Series([])
 
# reading csv file
data = pd.read_csv("pokemon.csv")
 
 
# running a for loop and assigning some values to series
for i in range(len(data)):
    if data["Type"][i] == "Grass":
        Type_new[i]="Green"
 
    elif data["Type"][i] == "Fire":
        Type_new[i]="Orange"
 
    elif data["Type"][i] == "Water":
        Type_new[i]="Blue"
 
    else:
        Type_new[i]= data["Type"][i]
 
         
# inserting new column with values of list made above       
data.insert(2, "Type New", Type_new)
 
# list output
data.head()

输出: