Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column to dataframe with constant value

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

like image 451
darkpool Avatar asked Apr 08 '15 14:04

darkpool


People also ask

How do I add a column to a DataFrame with a constant value?

To add anew column with constant value, use the square bracket i.e. the index operator and set that value.

How do you add an existing column to a DataFrame?

In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.


1 Answers

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 
like image 55
EdChum Avatar answered Oct 06 '22 14:10

EdChum