Q:

How to add a column to DataFrame with constant value?

belongs to collection: Python Pandas Programs

0

Columns are the different fields which contains their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Sometimes we need to add a column in our dataset and this creation depends upon some condition. Here, we are creating a new column in the DataFrame where all the values of the column are same i.e., constant.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Let us understand with the help of an example:

# Importing Pandas package as pd
import pandas as pd

# Creating a dictionary
d = {
    'A':[1,2,3,4],
    'B':[1,2,3,4]
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Creating a new column with similar/ constant value
df['C'] = pd.Series(['Hello, This is a new column' for i in range(len(df.index))])

# Display modified DataFrame
print("Modified DataFrame\n",df)

Output:

Example: Add a column to DataFrame with constant value

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Split (explode) pandas DataFrame string entry to s... >>
<< How to drop infinite values from DataFrames in Pan...