Pandas insert方法允许用户在数据帧或序列(1-D数据帧)中插入列。也可以通过以下方法在数据框中手动插入列,但这里没有太多自由度。 例如,即使是列位置也无法确定,因此插入的列始终插入到最后一个位置。 语法:
null
DataFrameName.insert(loc, column, value, allow_duplicates = False)
参数:
loc: loc是一个整数,它是我们要插入新列的列的位置。这将使该位置的现有柱向右移动。 专栏: column是一个字符串,它是要插入的列的名称。 价值: value就是要插入的值。它可以是int、string、float或任何东西,甚至可以是值的系列/列表。只提供一个值将为所有行设置相同的值。 允许_重复: allow_duplicates是一个布尔值,用于检查同名列是否已存在。
查找指向从中使用的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() |
传递每行具有不同值的序列:
在本例中,创建一个系列,并通过for循环将一些值传递给该系列。之后,将序列传递到pandas insert函数中,用传递的值将序列追加到数据帧中。
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() |
输出:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END