Skip to main content
v2026.11,986 entries · CC-BY 4.0

pandas round: Columns, Decimals and Examples

Use pandas round for numeric research tables, with per-column precision, half-to-even ties, and separate display and CSV formatting.

Written and maintained by CASRAI Editorial Board

Published

On this page

Use pandas df.round(2) to round numeric DataFrame columns to two decimal places, or df.round({'signal': 2}) to target a named column. For one Series, use s.round(2). Keep numeric rounding separate from display formatting: a research results table can show fewer digits without replacing the values used in analysis.

What it is used for in research

Rounding is useful when preparing a reporting copy of a results table containing measurements, estimates or computed summaries. A precision mapping makes the intended treatment explicit for each column. For example, an analyst might prepare a synthetic sensor table with one decimal place for temperature and two for signal strength. These are illustrative reporting choices, not measurement standards or recommendations about instrument accuracy.

The pandas DataFrame API accepts an integer, dictionary or Series as its decimals argument. A Series of observations instead takes one integer precision. This distinction matters when a table mixes variables with different units. Selecting the reporting columns and their precision is a separate task from cleaning their input; the research data wrangling workflow provides that wider context.

The walkthrough below keeps the source table and reporting table under different names. It also demonstrates a misspelled precision key, a case that can silently leave a column unchanged. The downloadable data table after the sources compares precision selectors and their scope across the relevant APIs.

Install or access

The pandas installation guide identifies PyPI, conda-forge and the project’s source repository as its official distribution routes. Its pip command is:

pip install pandas

For an existing Conda environment, the documented command is:

conda install -c conda-forge pandas

Choose the command for the environment in which the analysis runs. The installation guide recommends an isolated environment; installing into one environment while running a notebook from another can leave the notebook without the package. For a shared research project, record the environment alongside the script so collaborators can identify the package versions used.

The examples use the pandas 3.1.1 API documentation. They require pandas and use the conventional import shown below. NumPy and Python’s decimal module appear later only to explain alternative operations; neither changes the pandas method’s argument structure.

Step-by-step task: round pandas research columns

1. Create an illustrative input table

This is a synthetic research-data example, an illustrative composite rather than observations from a real study. The sample labels identify rows; the measurement columns contain ordinary floating-point numbers. Starting with an explicit table makes it possible to inspect every transformation.

import pandas as pd

raw = pd.DataFrame({
    'sample': ['S01', 'S02', 'S03'],
    'temperature': [21.236, 20.874, 22.018],
    'signal': [0.1264, 0.2386, 0.3042],
    'count': [147, 253, 386],
})
print(raw)

2. Apply one precision to numeric columns

Use an integer when the same number of decimal places is appropriate across numeric columns. Keep the returned table in a new variable:

uniform = raw.round(2)
print(uniform)

In this example, the first temperature becomes 21.24 and the first signal becomes 0.13. The text labels remain text. Integer counts do not acquire extra meaningful digits merely because the precision argument is positive. A whole-table call is convenient, but a column mapping makes a mixed measurement table’s reporting choices easier to inspect.

3. Give each column its own decimal places

Use column names as dictionary keys and integer decimal places as values. The mapping below intentionally omits count and sample, leaving them outside the rounding selection.

precision = {'temperature': 1, 'signal': 2}
report = raw.round(precision)
print(report)

An indexed Series can supply the same mapping. Its index contains column names; it does not specify a different precision for each observation:

precision_series = pd.Series({
    'temperature': 1,
    'signal': 2,
})
report_from_series = raw.round(precision_series)

4. Round one Series or round to tens

A single selected column uses Series.round. Assign the returned Series when you want to retain it. Negative decimals refer to positions left of the decimal point: minus one rounds to tens, while minus two rounds to hundreds.

signal_report = raw['signal'].round(2)
counts_to_tens = raw['count'].round(-1)
print(signal_report.tolist())
print(counts_to_tens.tolist())

The two lists are [0.13, 0.24, 0.3] and [150, 250, 390]. The count example illustrates a numerical transformation, not a disclosure-control method. It should not be interpreted as an assurance that rounding makes research records anonymous.

Output and how to read it

The reporting copy from step 3 is:

  sample  temperature  signal  count
0    S01         21.2    0.13    147
1    S02         20.9    0.24    253
2    S03         22.0    0.30    386

Read the named measurement columns against the precision dictionary. The row labels and sample identifiers still describe the same three records. The first temperature has changed from 21.236 to 21.2 in the reporting copy. The count column stays at its original values because the dictionary did not include it. A displayed 0.30 represents the numeric value 0.3; it does not establish how many significant figures the underlying instrument justified.

For a reproducible check, compare selected cells and columns directly rather than relying on how a notebook aligns a table:

assert raw.loc[0, 'temperature'] == 21.236
assert report.loc[0, 'temperature'] == 21.2
assert report['count'].equals(raw['count'])
assert report_from_series.equals(report)

These assertions describe the example’s intended behavior. They do not assess the scientific appropriateness of its reporting precision. That decision depends on the analysis and reporting requirements; the software argument alone cannot supply it.

Half-to-even ties and floating-point limits

The Series documentation specifies nearest-even treatment for exact halfway values. Thus 2.5 rounds to 2.0 and 3.5 to 4.0 when decimals is zero. Negative ties follow the same rule: minus 2.5 becomes minus 2.0.

ties = pd.Series([-3.5, -2.5, 2.5, 3.5])
print(ties.round().tolist())
# [-4.0, -2.0, 2.0, 4.0]

Decimal-looking floats also have representation limits. NumPy documents both inexact decimal representation and errors introduced by scaling in its rounding algorithm. Do not diagnose every unexpected final digit as a different tie-breaking rule. For array-specific behavior and comparisons with Python’s built-in function, see NumPy round and floating-point examples.

Troubleshooting

A mapped column did not change

Check the key before changing the data. DataFrame.round ignores mapping entries that do not match an input column. A typo such as 'temprature' therefore does not reliably expose itself as a missing-column error. This explicit guard makes that assumption visible:

unexpected = set(precision).difference(raw.columns)
if unexpected:
    raise ValueError(f'Unknown precision keys: {unexpected}')

Keep precision values as integers. The dictionary describes decimal places, not a target numeric value or a separate precision for each row. Inspecting the mapping alongside the column names is especially useful after renaming variables or importing a revised instrument export.

The values are numeric text

A column containing strings such as '0.1264' needs a deliberate numeric-conversion step. DataFrame.round leaves nonnumeric columns unchanged. The pandas to_numeric API offers strict parsing and an explicit coercion mode:

text_signal = pd.Series(['0.1264', 'not recorded', '0.3042'])
numeric_signal = pd.to_numeric(text_signal, errors='coerce')
print(numeric_signal.round(2).tolist())
# [0.13, nan, 0.3]

Here, the middle string becomes a missing numeric value because coercion was requested. With errors='raise', invalid parsing raises an exception instead. Choose that policy explicitly: silently treating an unexpected label as missing may conceal a data-entry issue. Keep the original text available when investigating which records failed conversion. Conversion and rounding solve different problems.

The result does not show trailing zeros

For a table’s appearance, use Styler.format. Its formatter controls displayed cell text and accepts format strings or a dictionary by column. The numeric input can stay available for subsequent calculations:

styled = raw.style.format({
    'temperature': '{:.1f}',
    'signal': '{:.2f}',
})

Display styled in a notebook that renders pandas Styler objects. This instruction prepares the presentation layer; it does not create a newly rounded analytical DataFrame. A formatted cell is also not evidence that the stored number has the displayed precision. Keep this distinction explicit when collaborators compare notebook output with exported data.

The CSV does not match the styled table

Styling a notebook table and exporting CSV are separate operations. DataFrame.to_csv has its own float_format option; a uniform two-decimal export can be prepared without replacing raw:

csv_text = raw.to_csv(index=False, float_format='%.2f')
print(csv_text)

With no file path, this returns CSV text. Passing index=False excludes the DataFrame’s row index. The format applies to floating-point output, so it is not the per-column temperature-and-signal mapping used earlier. A later reader receives the digits actually written to the CSV; retaining raw in the running session does not restore omitted digits in that exported file.

If an analysis is being translated between languages, compare the rounding rule and input representation explicitly. The rounding in R guide covers the corresponding R operations; matching the printed number of decimal places alone is not a cross-language validation.

Free alternatives

The task may call for an array operation, an explicit decimal rule or display formatting rather than another DataFrame-wide round call. The following alternatives are documented in the NumPy, Python and pandas references. They operate at different layers, so choose according to the object and output required.

Alternative Documented role Distinction from DataFrame.round
NumPy round Round array-like input with one decimals argument and an optional output array. The API does not take a dictionary keyed by DataFrame column names.
Python Decimal.quantize Round a decimal value to a specified exponent with an explicit rounding mode. Useful when the task specifies decimal arithmetic and a tie rule.
pandas Styler.format Set the displayed representation of table cells. Formats presentation rather than returning a rounded numeric DataFrame.

For example, the decimal module documents ROUND_HALF_UP as nearest rounding with ties away from zero. Constructing Decimal from a string avoids first importing a binary float’s exact representation into the decimal value:

from decimal import Decimal, ROUND_HALF_UP

value = Decimal('2.5')
rounded = value.quantize(Decimal('1'), rounding=ROUND_HALF_UP)
print(rounded)
# 3

This is a separate arithmetic choice, not an argument to pandas round. Use it only when that is the rule the task requires. State the rule in the transformation script so another analyst can distinguish a deliberate half-up calculation from the nearest-even Series example above.

Check rounding order before reporting

Rounding each observation before computing a total can produce a different answer from rounding the total. The distinction can be checked with another synthetic illustration. Three values of 0.14 add to 0.42; rounding that total to one decimal place produces 0.4. Rounding each value to one decimal place first produces three values of 0.1, whose total rounds to 0.3.

observations = pd.Series([0.14, 0.14, 0.14])
total_then_round = pd.Series([sum(observations)]).round(1).iloc[0]
round_then_total = pd.Series([sum(observations.round(1))]).round(1).iloc[0]
assert total_then_round == 0.4
assert round_then_total == 0.3

This arithmetic example is not a claim about the size of rounding effects in a particular study. It shows why a reporting script should make the order of operations inspectable. If the intended output is a rounded total, calculate from the analytical values and then apply the reporting precision. If a protocol explicitly defines rounded observations as inputs, implement that different rule and preserve its definition with the analysis.

The same audit can include the returned object’s type and the precision mapping. A whole-number-looking result is not automatically an integer storage conversion, and decimal places are not a universal significant-figure rule. Keeping the input, transformation and presentation as named objects makes each of these assumptions easier to check independently.

Sources

Data: pandas precision selectors and their scope

Original compilation of precision-selection behavior from the pandas DataFrame.round, Series.round, Styler.format and DataFrame.to_csv documentation. It distinguishes column selection, numeric transformation and output formatting; no synthetic measurements are included.

pandas precision selectors and their scope
API and selectorPrecision inputScopeReturn objectSource URL
DataFrame.round: integerOne integerAll numeric columns use the same decimal places; nonnumeric columns unchangedDataFramehttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.round.html
DataFrame.round: dictionaryColumn names as keys, integer decimal places as valuesListed columns only; omitted columns unchanged; unknown keys ignoredDataFramehttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.round.html
DataFrame.round: SeriesColumn names in the index, integer decimal places as valuesMatches precision entries to column labelsDataFramehttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.round.html
Series.roundOne integer, default 0All values in the Series; negative decimals specify positions left of the pointSerieshttps://pandas.pydata.org/docs/reference/api/pandas.Series.round.html
Styler.formatFormat string, callable, dictionary or precision integerDisplayed cell text; optional subset limits the regionStylerhttps://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.format.html
DataFrame.to_csv: float_formatFormat string or callableFloating-point representation in CSV outputString when path_or_buf is None; otherwise Nonehttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about pandas round: Columns, Decimals and Examples

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →