liveBook · Manning

Assign

As explained in Pandas Workout: 200 exercises to make you a stronger data analyst

The pandas DataFrame.assign method returns a new DataFrame with columns created or replaced from keyword arguments without modifying the original DataFrame.

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

How Pandas Workout: 200 exercises to make you a stronger data analyst covers it

How deep it goes
Explains keyword columns, scalar broadcasting, replacement, and lambda-based chaining through worked data tasks.
Examples
Uses net-sales calculations, weather-file metadata, and taxi tip-percentage histograms as concrete applications.
What it assumes
Assumes familiarity with DataFrames, columns, Series arithmetic, indexing, and basic method chaining.
What you can do after
Apply it via pandas to construct temporary or persistent column transformations in chained DataFrame analyses.
How it connects
Connects DataFrame.assign with method chaining, lambda functions, loc filtering, read_csv, and data visualization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pandas Workout: 200 exercises to make you a stronger data analyst. The section links point to the parts of the book it draws on.