Append column to pandas DataFrame without mutating the original

Viewed 1160

When we need add a column to a DataFrame often we write:

df['newcol'] = 123

This changes (mutates) the original df object, which is not always desired.

What would be a fast and idiomatic way to do it? Here's one option, but it is about 10 slower than the above assignment.

df2 = concat([df, DataFrame(123, index=df.index, columns=['newcol'])], axis=1)
2 Answers

You can do it with assign:

df2 = df.assign(newcol=123)
Related