313

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

cs95
  • 330,695
  • 80
  • 606
  • 657
darkpool
  • 11,767
  • 12
  • 48
  • 77

6 Answers6

469

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
EdChum
  • 339,461
  • 188
  • 752
  • 538
101

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
piRSquared
  • 265,629
  • 48
  • 427
  • 571
76

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

Jolta
  • 2,578
  • 1
  • 29
  • 41
Michele Piccolini
  • 2,175
  • 11
  • 27
57

Single liner works

df['Name'] = 'abc'

Creates a Name column and sets all rows to abc value

Zero
  • 66,763
  • 15
  • 141
  • 151
10

One Line did the job for me.

df['New Column'] = 'Constant Value'
df['New Column'] = 123
Zachary
  • 109
  • 1
  • 6
7

You can Simply do the following:

df['New Col'] = pd.Series(["abc" for x in range(len(df.index))])
Imam_AI
  • 101
  • 1
  • 6
  • 1
    Thanks, that was specially good to avoid the damn chained indexing warning. – Roni Antonio Sep 16 '21 at 01:13
  • 1
    Thank you, this worked perfectly for assigning a dataframe to a column, aka `df['date'] = pd.Series([pd.date_range('2020-01-01', '2023-12-31') for x in range(len(df.index))])` – BeRT2me Apr 14 '22 at 04:24