如何格式化Pandas DataFrame并保留原始浮点精度值
It looks like you're trying to get Pandas to show floating-point numbers in a clean, non-scientific notation without truncating small values—and the default formatting options aren't delivering what you need. Let's break down why your current code isn't working, then fix it.
Why Your Current Approach Falls Short
- When you use
pd.options.display.float_format = '{:f}'.format, this enforces a fixed 6-decimal-place format. Your value2.5e-07(which equals0.00000025) gets rounded to 6 decimals, resulting in0.000000—that's why you lose the tiny trailing digits. - Switching to
pd.set_option('display.float_format', str)lets Pandas use its default logic, which reverts to scientific notation for very small numbers (like2.5e-07), which isn't what you want either.
Solution 1: Universal Non-Scientific Notation (Preserve All Significant Digits)
If you want to display all floats in standard decimal form without scientific notation, use numpy.format_float_positional to convert numbers to their full positional representation. This keeps all relevant digits and avoids scientific notation:
import pandas as pd import numpy as np # Your original DataFrame df = pd.DataFrame([{'A': 2.5e-07, 'B': 2.5e-05, 'C': 2.5e-04, 'D': 0.0001, 'E': 0.01}]) # Custom formatter to avoid scientific notation and trim trailing zeros def format_float(x): return np.format_float_positional(x, trim='-') # Apply the formatter globally pd.options.display.float_format = format_float # Print the cleaned output print(df.to_string())
Output:
A B C D E 0 0.00000025 0.000025 0.00025 0.0001 0.01
Solution 2: Column-Specific Formatting (Match Your Exact Expected Output)
If you want precise control over each column's decimal places (like your expected output where A shows 0.0000025—note this corresponds to 2.5e-06 instead of your original 2.5e-07), use the formatters parameter in to_string() to set per-column rules:
import pandas as pd # Adjusted DataFrame to match your expected A value df = pd.DataFrame([{'A': 2.5e-06, 'B': 2.5e-05, 'C': 2.5e-04, 'D': 0.0001, 'E': 0.01}]) # Define formatters for each column column_formatters = { 'A': '{:.7f}'.format, # 7 decimal places to show 0.0000025 'B': '{:.6f}'.format, 'C': '{:.5f}'.format, 'D': '{:.4f}'.format, 'E': '{:.2f}'.format } # Print with column-specific formatting print(df.to_string(formatters=column_formatters))
Output:
A B C D E 0 0.0000025 0.000025 0.00025 0.0001 0.01
Quick Note
- If your original
Avalue is indeed2.5e-07(0.00000025), Solution 1 will display it accurately. If you intended0.0000025, adjust the input value to2.5e-06and use Solution 2 for tight control.
内容的提问来源于stack exchange,提问作者xarc

