Add column to dataframe with constant value
--
Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping
--
Chapters
00:00 Question
00:50 Accepted answer (Score 522)
01:10 Answer 2 (Score 113)
01:31 Answer 3 (Score 89)
02:46 Answer 4 (Score 65)
03:03 Thank you
--
Full question
https://stackoverflow.com/questions/2951...
Answer 1 links:
[insert]: http://pandas.pydata.org/pandas-docs/sta...
Answer 2 links:
[assign]: https://pandas.pydata.org/pandas-docs/st...
[insert]: https://pandas.pydata.org/pandas-docs/st...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
ACCEPTED ANSWER
Score 557
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
ANSWER 2
Score 118
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
ANSWER 3
Score 95
Summing up what the others have suggested, and adding a third way
You can:
-
df.assign(Name='abc') access the new column series (it will be created) and set it:
df['Name'] = 'abc'insert(loc, column, value, allow_duplicates=False)
df.insert(0, 'Name', 'abc')
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).
ANSWER 4
Score 67
Single liner works
df['Name'] = 'abc'
Creates a Name column and sets all rows to abc value