Python - 向 Pandas DataFrame 添加零列
要将零列添加到 Pandas DataFrame,请使用方括号并将其设置为 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
以上是 Python - 向 Pandas DataFrame 添加零列 的全部内容, 来源链接: utcz.com/z/350438.html