Add column to dataframe with constant value Add column to dataframe with constant value python python

Add column to dataframe with constant value

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

In [79]:dfOut[79]:         Date, Open, High,  Low,  Close0  01-01-2015,  565,  600,  400,    450In [80]:df['Name'] = 'abc'dfOut[80]:         Date, Open, High,  Low,  Close Name0  01-01-2015,  565,  600,  400,    450  abc

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  Close0  abc  01-01-2015   565   600  400    450

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