Python - 向 Pandas DataFrame 添加零列
要将零列添加到PandasDataFrame,请使用方括号并将其设置为0。首先,导入所需的库-
import pandas as pd
创建一个包含3列的DataFrame-
dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],"Roll Number": [ 5, 10, 3, 8, 2, 9, 6] } )
创建一个零条目的新列-
dataFrame['ZeroColumn'] = 0
示例
以下是代码-
import pandas as pd #创建数据帧 dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],"Roll Number": [ 5, 10, 3, 8, 2, 9, 6] } ) print"DataFrame ...\n",dataFrame dataFrame['ZeroColumn'] = 0 print"\nUpdated DataFrame ...\n",dataFrame输出结果
这将产生以下输出-
DataFrame ... Result Roll Number Student 0 Pass 5 Jack 1 Fail 10 Robin 2 Pass 3 Ted 3 Fail 8 Marc 4 Pass 2 Scarlett 5 Pass 9 Kat 6 Pass 6 John Updated DataFrame ... Result Roll Number Student ZeroColumn 0 Pass 5 Jack 0 1 Fail 10 Robin 0 2 Pass 3 Ted 0 3 Fail 8 Marc 0 4 Pass 2 Scarlett 0 5 Pass 9 Kat 0 6 Pass 6 John 0