Summing rows in pandas is a core operation for data cleaning, aggregation, and reporting. This guide shows how to use DataFrame.sum(), groupby().sum(), and axis parameters to add values across rows or columns, handle missing data, and control numeric dtypes. You will learn common patterns, options like skipna and min_count, and how to manage categorical and datetime columns. The methods below are stable across recent pandas versions and designed for reproducible, maintainable workflows.
Basics of DataFrame sum
sum() computes sums along an axis, with numeric_only controlling column types and skipna handling missing values. It is available on Series and DataFrame and is optimized for performance on large tables.
How sum works on a DataFrame
By default, DataFrame.sum() skips missing values and returns the sum of each numeric column. Non-numeric columns are excluded unless dtype is explicitly object or datetime, and numeric_only=True enforces numeric types only.
Using axis to switch direction
Set axis=1 (or axis='columns') to sum across rows, producing a Series of row totals. Use axis=0 (or axis='index') to sum down each column, which is the default behavior.
Summing rows with axis=1
Summing rows returns one total per observation and is useful for scoring, metrics, or feature engineering. You can select subsets of columns and control how missing data is treated.
Basic row sum example
- Create a DataFrame with numeric columns.
- Apply df.sum(axis=1) to compute per-row totals.
- Assign the result to a new column to enrich the table.
Selecting specific columns for row sums
Pass a list of column names to sum only those columns across rows, for example df[['q1', 'q2', 'q3']].sum(axis=1). This avoids numeric columns that should be excluded from aggregation.
Handling missing values in row sums
- skipna=True ignores NaN values when computing each row sum.
- skipna=False returns NaN for any row that contains at least one missing value.
- Use min_count to require a minimum number of valid values per row.
Grouped sums with groupby
Grouped aggregation reshapes data by category and is foundational for summary reporting. Combine groupby with sum() to produce subtotals and hierarchical indexes.
Single-level groupby sum
Call df.groupby('category')['amount'].sum() to sum the amount column for each category. The result is a Series indexed by category.
Multiple columns and multiple keys
Pass a list of columns to aggregate several metrics at once, and supply a list of keys to group by compound segments. This supports concise cross-tabulation style summaries.
Resetting the index after groupby
Use .reset_index() to convert the grouped index back into columns, which is convenient for joins, sorting, and downstream visualization tools.
Performance and memory considerations
Row-wise operations with axis=1 can be slower than column-wise sums because of per-row iteration. Prefer column aggregations when possible, reduce object overhead, and consider downcasting numeric types to lower memory use.
Speed comparison table
| Method | Use case | Relative speed | When to use |
|---|---|---|---|
| df.sum(numeric_only=True) | Column totals | Fast | Standard aggregation |
| df.sum(axis=1) | Row totals | Moderate | Scoring and row metrics |
| df.groupby(...).sum() | Category subtotals | Fast | Reports and segmentation |
Data types and edge cases
sum() behaves differently depending on column dtype. Boolean columns are treated as 1/0, datetime columns raise TypeError unless handled explicitly, and categorical columns must be converted before summing.
Boolean and integer columns
Boolean values sum as True=1, False=0. Ensure nullable integer columns retain correct null semantics; convert to float if needed to avoid unwanted coercion.
Datetime and timedelta handling
Summing datetime columns is not allowed by default, but timedelta columns can be summed to produce meaningful durations. Use .astype('timedelta64[ns]') when working with offsets.
Controlling output dtype
Use the dtype parameter or .astype() to manage result types, and apply round() or custom formatting when presenting financial or scaled metrics.
Common patterns and gotchas
Always inspect column dtypes before summing to avoid surprises. Chain sum with round, clip, or clip_upper as needed, and validate totals against external benchmarks when accuracy is critical.
- Verify that axis is set correctly for row versus column sums.
- Check that numeric_only aligns with your intended column set.
- Test edge cases such as all-NA rows and zero-weight scenarios.
Next steps
Build reusable functions for row totals, integrate them into pipelines with .assign(), and combine groupby sums with pivot tables for dashboards. Consistent use of skipna and min_count improves reproducibility across datasets.