HomeLanguagesAdd zero columns to Pandas Dataframe

Add zero columns to Pandas Dataframe

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 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)


Output:

Example 2:

Python3




# import pandas library
import pandas as pd
  
# create data
data = [["Lazyroar", 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)


Output:

RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32738 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7124 POSTS0 COMMENTS
Nicole Veronica
12254 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12337 POSTS0 COMMENTS
Shaida Kate Naidoo
7235 POSTS0 COMMENTS
Ted Musemwa
7497 POSTS0 COMMENTS
Thapelo Manthata
7215 POSTS0 COMMENTS
Umr Jansen
7185 POSTS0 COMMENTS