liveBook · Manning

Axis parameter

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

An axis parameter specifies which pandas dimension, such as rows or columns, an operation should use.

Think of axis as choosing a direction through a spreadsheet: an operation can work across rows or across columns. In pandas, the choice changes which dimension is reduced and what shape comes back. section 7.6

Compare income brackets across each row

Suppose each row contains several income-bracket scores. The default axis='rows' produces one mean for each column. Passing axis='columns' instead produces one mean per row, preserving the data frame's index: df.mean(axis='columns'). Transposing twice can express the same change of direction, but axis is often clearer and can avoid extra time or memory. section 7.6

When choosing an axis, check both the direction of aggregation and the returned object:

  • Use axis='columns' when each row should collapse into one result, such as an average across income brackets. section 7.6
  • Use axis='columns' with xs when selecting from a multi-index on columns; xs otherwise assumes the multi-index is on rows. section 4.11
df.mean(axis='columns')

Inspect the compact row-wise mean example and compare its result with the default column-wise behavior. section 7.6

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

How deep it goes
Works through default behavior, returned shapes, transposition, and multi-index selection without developing pandas internals.
Examples
Uses income-bracket SAT scores and Olympic multi-index columns to demonstrate row-wise means and column-oriented cross-sections.
What you can do after
Apply it via pandas to choose aggregation direction and predict whether results return a Series or a reduced data frame.
How it connects
Connects axis to mean, transpose, groupby, pct_change, multi-index selection, and xs.

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.