Add zero columns to Pandas Dataframe
Last Updated :
11 Dec, 2020
Prerequisites: Pandas
The task here is to generate a Python program using its Pandas module that can add a column with all entries as zero to an existing dataframe.
A Dataframe is a two-dimensional, size-mutable, potentially heterogeneous tabular data.It is used to represent data in tabular form like an Excel file format. Below is the syntax for creating a dataframe in pandas. It can be imagines as a dictionary like container for series object.
Syntax:
DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
Approach
- Import required libraries
- Create or import data
- Add a new column with all zeroes.
Example 1:
Python3
import pandas as pd
dict = { 'name' : [ "sohom" , "rakesh" , "rajshekhar" , "sumit" ],
'department' : [ "ECE" , "CSE" , "EE" , "MCA" ],
'CGPA' : [ 9.2 , 8.7 , 8.6 , 7.7 ]}
df = pd.DataFrame( dict )
print ( "data frame before adding the column:" )
display(df)
df[ 'new' ] = 0
print ( "data frame after adding the column:" )
display(df)
|
Output:
Example 2:
Python3
import pandas as pd
data = [[ "geeks" , 1 ], [ "for" , 2 ], [ "best" , 3 ]]
df = pd.DataFrame(data, columns = [ 'col1' , 'col2' ])
print ( "data frame before adding the column:" )
display(df)
df[ 'col3' ] = 0
print ( "data frame after adding the column:" )
display(df)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...