Skip to content

BUG: Unexpected output of to_json for complex data #41174

Closed
@karalekas

Description

@karalekas
  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

import pandas as pd
s = pd.Series({0: 0+2j, 1: 3+4j, 2: 5+6j})
s.to_json()

Problem description

Calling to_json() on a DataFrame or Series with complex data gives unexpected results. Running the above Code Sample gives the following output:

'{"0":{"imag":2.0},"1":{"imag":4.0},"2":{"imag":6.0}}'

This is a problem both because (1) the output is not terribly useful (the real part is just dropped), and (2) according to the docs this should raise an error (see the following snippet copied from the linked docs page):

>>> DataFrame([1.0, 2.0, complex(1.0, 2.0)]).to_json()  # raises
RuntimeError: Unhandled numpy dtype 15

Expected Output

According to the docs, this should at least raise a RuntimeError. However, it would be nice for this to actually be supported.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 0158382
python : 3.8.5.final.0
python-bits : 64
OS : Darwin
OS-release : 20.1.0
Version : Darwin Kernel Version 20.1.0: Sat Oct 31 00:07:11 PDT 2020; root:xnu-7195.50.7~2/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.3.0.dev0+1441.g0158382ac8
numpy : 1.20.2
pytz : 2021.1
dateutil : 2.8.1
pip : 20.1.1
setuptools : 47.1.0
Cython : 0.29.23
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : 7.22.0
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    ComplexComplex NumbersIO JSONread_json, to_json, json_normalizeNeeds TestsUnit test(s) needed to prevent regressionsgood first issue

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions