📜  将零列添加到 Pandas Dataframe

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

将零列添加到 Pandas Dataframe

先决条件:熊猫

这里的任务是使用其 Pandas 模块生成一个Python程序,该模块可以将所有条目为零的列添加到现有数据帧。

Dataframe 是二维的、大小可变的、潜在异构的表格数据。它用于像 Excel 文件格式一样以表格形式表示数据。以下是在 Pandas 中创建数据框的语法。它可以被想象成一个字典,就像系列对象的容器。

句法:

方法

  • 导入所需的库
  • 创建或导入数据
  • 添加一个全为零的新列。

示例 1:

Python3
# import pandas library
import pandas as pd
  
# creating dictionary of lists
dict = {'name': ["sohom", "rakesh", "rajshekhar", "sumit"],
        'department': ["ECE", "CSE", "EE", "MCA"],
        'CGPA': [9.2, 8.7, 8.6, 7.7]}
  
# creating a dataframe
df = pd.DataFrame(dict)
  
print("data frame before adding the column:")
display(df)
  
# creating a new column
# of zeroes to the
# dataframe
df['new'] = 0
  
# showing the dataframe
print("data frame after adding the column:")
display(df)


Python3
# import pandas library
import pandas as pd
  
# create data
data = [["geeks", 1], ["for", 2], ["best", 3]]
  
# creating a dataframe
df = pd.DataFrame(data, columns=['col1', 'col2'])
  
print("data frame before adding the column:")
display(df)
  
# creating a new column with all zero entries
df['col3'] = 0
  
# showing the dataframe
print("data frame after adding the column:")
display(df)


输出:

示例 2:

蟒蛇3

# import pandas library
import pandas as pd
  
# create data
data = [["geeks", 1], ["for", 2], ["best", 3]]
  
# creating a dataframe
df = pd.DataFrame(data, columns=['col1', 'col2'])
  
print("data frame before adding the column:")
display(df)
  
# creating a new column with all zero entries
df['col3'] = 0
  
# showing the dataframe
print("data frame after adding the column:")
display(df)

输出: