Skip to content

Commit e70f475

Browse files
sakarpantayhaque1213
authored andcommitted
BUG: Display precision doesn't affect complex float numbers pandas-dev#25514 (pandas-dev#25745)
1 parent a9a4ea1 commit e70f475

File tree

4 files changed

+45
-12
lines changed

4 files changed

+45
-12
lines changed

doc/source/whatsnew/v0.25.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,7 @@ Numeric
293293

294294
- Bug in :meth:`to_numeric` in which large negative numbers were being improperly handled (:issue:`24910`)
295295
- Bug in :meth:`to_numeric` in which numbers were being coerced to float, even though ``errors`` was not ``coerce`` (:issue:`24910`)
296+
- Bug in :class:`format` in which floating point complex numbers were not being formatted to proper display precision and trimming (:issue:`25514`)
296297
- Bug in error messages in :meth:`DataFrame.corr` and :meth:`Series.corr`. Added the possibility of using a callable. (:issue:`25729`)
297298
- Bug in :meth:`Series.divmod` and :meth:`Series.rdivmod` which would raise an (incorrect) ``ValueError`` rather than return a pair of :class:`Series` objects as result (:issue:`25557`)
298299
- Raises a helpful exception when a non-numeric index is sent to :meth:`interpolate` with methods which require numeric index. (:issue:`21662`)

pandas/core/frame.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -2497,12 +2497,12 @@ def memory_usage(self, index=True, deep=False):
24972497
... for t in dtypes])
24982498
>>> df = pd.DataFrame(data)
24992499
>>> df.head()
2500-
int64 float64 complex128 object bool
2501-
0 1 1.0 (1+0j) 1 True
2502-
1 1 1.0 (1+0j) 1 True
2503-
2 1 1.0 (1+0j) 1 True
2504-
3 1 1.0 (1+0j) 1 True
2505-
4 1 1.0 (1+0j) 1 True
2500+
int64 float64 complex128 object bool
2501+
0 1 1.0 1.0+0.0j 1 True
2502+
1 1 1.0 1.0+0.0j 1 True
2503+
2 1 1.0 1.0+0.0j 1 True
2504+
3 1 1.0 1.0+0.0j 1 True
2505+
4 1 1.0 1.0+0.0j 1 True
25062506
25072507
>>> df.memory_usage()
25082508
Index 80

pandas/io/formats/format.py

+25-6
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@
1919
from pandas.compat import lzip
2020

2121
from pandas.core.dtypes.common import (
22-
is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype,
23-
is_extension_array_dtype, is_float, is_float_dtype, is_integer,
24-
is_integer_dtype, is_list_like, is_numeric_dtype, is_scalar,
22+
is_categorical_dtype, is_complex_dtype, is_datetime64_dtype,
23+
is_datetime64tz_dtype, is_extension_array_dtype, is_float, is_float_dtype,
24+
is_integer, is_integer_dtype, is_list_like, is_numeric_dtype, is_scalar,
2525
is_timedelta64_dtype)
2626
from pandas.core.dtypes.generic import (
2727
ABCIndexClass, ABCMultiIndex, ABCSeries, ABCSparseArray)
@@ -892,7 +892,7 @@ def format_array(values, formatter, float_format=None, na_rep='NaN',
892892
fmt_klass = Timedelta64Formatter
893893
elif is_extension_array_dtype(values.dtype):
894894
fmt_klass = ExtensionArrayFormatter
895-
elif is_float_dtype(values.dtype):
895+
elif is_float_dtype(values.dtype) or is_complex_dtype(values.dtype):
896896
fmt_klass = FloatArrayFormatter
897897
elif is_integer_dtype(values.dtype):
898898
fmt_klass = IntArrayFormatter
@@ -1084,6 +1084,7 @@ def format_values_with(float_format):
10841084

10851085
# separate the wheat from the chaff
10861086
values = self.values
1087+
is_complex = is_complex_dtype(values)
10871088
mask = isna(values)
10881089
if hasattr(values, 'to_dense'): # sparse numpy ndarray
10891090
values = values.to_dense()
@@ -1094,7 +1095,10 @@ def format_values_with(float_format):
10941095
for val in values.ravel()[imask]])
10951096

10961097
if self.fixed_width:
1097-
return _trim_zeros(values, na_rep)
1098+
if is_complex:
1099+
return _trim_zeros_complex(values, na_rep)
1100+
else:
1101+
return _trim_zeros_float(values, na_rep)
10981102

10991103
return values
11001104

@@ -1424,7 +1428,22 @@ def just(x):
14241428
return result
14251429

14261430

1427-
def _trim_zeros(str_floats, na_rep='NaN'):
1431+
def _trim_zeros_complex(str_complexes, na_rep='NaN'):
1432+
"""
1433+
Separates the real and imaginary parts from the complex number, and
1434+
executes the _trim_zeros_float method on each of those.
1435+
"""
1436+
def separate_and_trim(str_complex, na_rep):
1437+
num_arr = str_complex.split('+')
1438+
return (_trim_zeros_float([num_arr[0]], na_rep) +
1439+
['+'] +
1440+
_trim_zeros_float([num_arr[1][:-1]], na_rep) +
1441+
['j'])
1442+
1443+
return [''.join(separate_and_trim(x, na_rep)) for x in str_complexes]
1444+
1445+
1446+
def _trim_zeros_float(str_floats, na_rep='NaN'):
14281447
"""
14291448
Trims zeros, leaving just one before the decimal points if need be.
14301449
"""

pandas/tests/io/formats/test_format.py

+13
Original file line numberDiff line numberDiff line change
@@ -1370,6 +1370,19 @@ def test_to_string_float_index(self):
13701370
'5.0 4')
13711371
assert result == expected
13721372

1373+
def test_to_string_complex_float_formatting(self):
1374+
# GH #25514
1375+
with pd.option_context('display.precision', 5):
1376+
df = DataFrame({'x': [
1377+
(0.4467846931321966 + 0.0715185102060818j),
1378+
(0.2739442392974528 + 0.23515228785438969j),
1379+
(0.26974928742135185 + 0.3250604054898979j)]})
1380+
result = df.to_string()
1381+
expected = (' x\n0 0.44678+0.07152j\n'
1382+
'1 0.27394+0.23515j\n'
1383+
'2 0.26975+0.32506j')
1384+
assert result == expected
1385+
13731386
def test_to_string_ascii_error(self):
13741387
data = [('0 ', ' .gitignore ', ' 5 ',
13751388
' \xe2\x80\xa2\xe2\x80\xa2\xe2\x80'

0 commit comments

Comments
 (0)