Pandas add column with repeated value

The pandas library in Python provides a convenient way to add a column with repeated values to a DataFrame.
We can achieve this using the assign() method and passing the desired column name and the repeated value as an argument.

Here’s an example of how to do it:


import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4]})

# Add a column with repeated value
df = df.assign(B='Repeated value')

print(df)

Output:


   A                B
0  1  Repeated value
1  2  Repeated value
2  3  Repeated value
3  4  Repeated value

In the above example, we created a DataFrame with a column ‘A’ having some values.
Then, we used the assign() method to add a new column ‘B’ with a repeated value ‘Repeated value’ to the DataFrame.
Finally, we printed the updated DataFrame.

You can replace ‘Repeated value’ with any other value of your choice.
Additionally, you can also assign a series of repeated values or use other methods such as pd.repeat() to achieve the same result.

Leave a comment