为Pandas数据框架添加零列
这里的任务是使用Pandas模块生成一个Python程序,该程序可以在现有的数据框架中增加一个所有条目为0的列。
数据框架是一个二维的、大小可调整的、可能是异质的表格数据。它被用来以表格的形式表示数据,就像Excel文件格式一样。下面是在pandas中创建一个数据框架的语法。它可以被想象成一个像字典一样的系列对象的容器。
语法:
DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
步骤
- 导入所需的库
- 创建或导入数据
- 增加一个新的列,全部为零。
示例 1:
# 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)
输出:
示例 2:
# 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)
输出: