Skip to content

ENH: How about let pprint_thing print Real instance according to display.precision #60503

Open
aydinomer00/pandas
#1
@miba2020

Description

@miba2020

Feature Type

  • Adding new functionality to pandas

  • Changing existing functionality in pandas

  • Removing existing functionality in pandas

Problem Description

I use pandas inside ipython. Sometimes I want all float items are printted with 3 digits. But pd.DataFrame({"seq": [[pi] * 5], "foo": [pi]}) got displayed like this:

                                                 seq    foo
0  [3.141592653589793, 3.141592653589793, 3.14159...  3.142

i.e. "foo" in 3 digits but items of "seq" lots digits.

Feature Description

I want pd.DataFrame({"seq": [[pi] * 5], "foo": [pi]}) as

                                   seq    foo
0  [3.142, 3.142, 3.142, 3.142, 3.142]  3.142

in one line and all 5 items shown.

Alternative Solutions

I tried to define a str method for that sequence, but in like this issue customized representation method is not called. So I proposed to patch pprint_thing like this:

diff -u /home/renlifeng/ve3/lib/python3.12/site-packages/pandas/io/formats/printing.py.\~orig\~ /home/renlifeng/ve3/lib/python3.12/site-packages/pandas/io/formats/printing.py
--- /home/renlifeng/ve3/lib/python3.12/site-packages/pandas/io/formats/printing.py.~orig~	2024-10-06 06:11:00.000000000 +0800
+++ /home/renlifeng/ve3/lib/python3.12/site-packages/pandas/io/formats/printing.py	2024-12-04 15:47:37.481159765 +0800
@@ -8,6 +8,10 @@
     Mapping,
     Sequence,
 )
+from numbers import (
+    Integral,
+    Real,
+)
 import sys
 from typing import (
     Any,
@@ -206,7 +210,10 @@
         else:
             escape_chars = escape_chars or ()
 
-        result = str(thing)
+        if isinstance(thing, Real) and not isinstance(thing, Integral):
+            result = f"%.{get_option('display.precision')}f" % thing
+        else:
+            result = str(thing)
         for c in escape_chars:
             result = result.replace(c, translate[c])
         return result

Diff finished.  Wed Dec  4 15:48:27 2024

Additional Context

I use pandas inside ipython. Sometimes I want all float items are printted with 3 digits.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions