Add column to dataframe with default value

I have an existing data framework that needs to add an extra column that will contain the same value for each 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 add an existing series column / dataframe. But this is a completely different situation, because all I need to do is add a column β€œName” and set each row to the same value, in this case β€œabc”.

I'm not quite sure how to do this.

+42
python pandas
Apr 08 '15 at 14:09
source share
3 answers

df['Name']='abc' will add a new column and set all rows to this 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 
+59
Apr 08 '15 at 14:09
source share

Work with one liner

 df['Name'] = 'abc' 

Creates a Name column and sets all rows to abc

+15
Apr 08 '15 at 14:10
source share

You can use insert to indicate where you want to use the new column. In this case, I use 0 to put the new column on the left.

 df.insert(0, 'Name', 'abc') Name Date Open High Low Close 0 abc 01-01-2015 565 600 400 450 
+7
Jun 20 '17 at 15:42
source share



All Articles