Adding a Column to a Pandas DataFrame Without Altering Index

Sometimes, I don’t want to modify df in place, especially when I’m working with multiple transformations. How do I handle that?

The assign() method is a great choice:

df = df.assign(e=[-0.335485, -1.166658, -0.385571])

:white_check_mark: Why this?

  • It returns a new DataFrame instead of modifying df directly.
  • Useful when you’re working in pipelines or want to preserve the original DataFrame while using pandas add column to dataframe.