Use DataFrame.assign to create or replace columns while returning a new DataFrame instead of modifying the original. Each keyword names a column; its value supplies that column’s data. Series, arrays, and lists must match the existing column length, while a scalar fills every row. section 2.6
The method becomes especially useful when:
- You want to preserve the input DataFrame while adding a calculated result such as net sales. section 2.6
- You are building a readable method chain, such as importing weather data and adding city and state columns. section 7.2
- You need a temporary calculated column for later filtering or plotting without permanently adding it to the original data. section 11.10
Calculate and filter taxi tips
A chained expression can keep only valid fares, calculate tip_percentage with a row-wise lambda, filter values at or below 50 percent, and plot the resulting histogram: df.loc[lambda df_: df_['fare_amount'] > 0].assign(tip_percentage=lambda df_: df_['tip_amount'] / df_['fare_amount']).loc[lambda df_: df_['tip_percentage'] <= 0.5, 'tip_percentage'].plot.hist(). The assigned column belongs to the intermediate DataFrame created by the chain, not the original df. section 11.10
df.assign(current_net = (df['retail_price'] - df['wholesale_price']) *
df['sales'])
Compare direct column assignment with assign: the latter creates current_net while supporting continued method chaining. section 2.6
