agilevic agilevic - 1 month ago 4x
Python Question

Append column to pandas DataFrame without mutating the original

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)


what about copy():

df2 = df.copy()
df2['newcol'] = 123