Super simple: direct assignment
For on-site modification, perform a direct assignment. This assignment is broadcast by pandas for each row.
df = pd.DataFrame('x', index=range(4), columns=list('ABC')) df ABC 0 xxx 1 xxx 2 xxx 3 xxx
df['new'] = 'y'
Create Copy: DataFrame.assign
If you need a copy, use DataFrame.assign :
df.assign(new='y') ABC new 0 xxxy 1 xxxy 2 xxxy 3 xxxy
And if you need to assign several such columns with the same value, it is as simple as,
c = ['new1', 'new2', ...] df.assign(**dict.fromkeys(c, 'y')) ABC new1 new2 0 xxxyy 1 xxxyy 2 xxxyy 3 xxxyy
Multiple Column Assignment
Finally, if you need to assign multiple columns with different values, you can use assign with a dictionary.
c = {'new1': 'w', 'new2': 'y', 'new3': 'z'} df.assign(**c) ABC new1 new2 new3 0 xxxwyz 1 xxxwyz 2 xxxwyz 3 xxxwyz
cs95 Jan 24 '19 at 11:47 2019-01-24 11:47
source share