pythonbeginner

Pandas .assign() for Immutable Chaining

Use DataFrame.assign() to add computed columns without mutating the original DataFrame.

python
import pandas as pd

df = pd.DataFrame({'price': [10.0, 20.0, 30.0], 'qty': [3, 1, 5]})

result = (
    df.assign(
        revenue=lambda x: x['price'] * x['qty'],
        discount=lambda x: x['revenue'] * 0.1,
        net=lambda x: x['revenue'] - x['discount'],
    )
)
print(result)

Use Cases

  • immutable transforms
  • readable pipelines
  • ETL preprocessing

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.