Add column to dataframe with constant value

PythonPandasDataframe

Python Problem Overview


I have an existing dataframe which I need to add an additional column to which will contain the same value for every row.

Existing df:

Date, Open, High, Low, Close
01-01-2015, 565, 600, 400, 450

New df:

Name, Date, Open, High, Low, Close
abc, 01-01-2015, 565, 600, 400, 450

I know how to append an existing series / dataframe column. But this is a different situation, because all I need is to add the 'Name' column and set every row to the same value, in this case 'abc'.

Python Solutions


Solution 1 - Python

df['Name']='abc' will add the new column and set all rows to that value:

In [79]:

df
Out[79]:
         Date, Open, High,  Low,  Close
0  01-01-2015,  565,  600,  400,    450
In [80]:

df['Name'] = 'abc'
df
Out[80]:
         Date, Open, High,  Low,  Close Name
0  01-01-2015,  565,  600,  400,    450  abc

Solution 2 - Python

You can use insert to specify where you want to new column to be. In this case, I use 0 to place the new column at the left.

df.insert(0, 'Name', 'abc')

  Name        Date  Open  High  Low  Close
0  abc  01-01-2015   565   600  400    450

Solution 3 - Python

Summing up what the others have suggested, and adding a third way

You can:

where the argument loc ( 0 <= loc <= len(columns) ) allows you to insert the column where you want.

'loc' gives you the index that your column will be at after the insertion. For example, the code above inserts the column Name as the 0-th column, i.e. it will be inserted before the first column, becoming the new first column. (Indexing starts from 0).

All these methods allow you to add a new column from a Series as well (just substitute the 'abc' default argument above with the series).

Solution 4 - Python

Single liner works

df['Name'] = 'abc'

Creates a Name column and sets all rows to abc value

Solution 5 - Python

One Line did the job for me.

df['New Column'] = 'Constant Value'
df['New Column'] = 123

Solution 6 - Python

You can Simply do the following:

df['New Col'] = pd.Series(["abc" for x in range(len(df.index))])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondarkpoolView Question on Stackoverflow
Solution 1 - PythonEdChumView Answer on Stackoverflow
Solution 2 - PythonpiRSquaredView Answer on Stackoverflow
Solution 3 - PythonMichele PiccoliniView Answer on Stackoverflow
Solution 4 - PythonZeroView Answer on Stackoverflow
Solution 5 - PythonZacharyView Answer on Stackoverflow
Solution 6 - PythonImam_AIView Answer on Stackoverflow