agilevic agilevic - 1 year ago 125
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)

Answer Source

what about copy():

df2 = df.copy()
df2['newcol'] = 123
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download