Skip to content

Commit 7ab8b1a

Browse files
committed
BUG:pandas-dev#29928 Fix to_json output with 'table' orient for single level MultiIndex.
Index field name in written json was incorrect, so applying read_json resulted in NaN index values. Dataframe to_json with 'table' orient now treats single level MultiIndex like single index.
1 parent 42a5c1c commit 7ab8b1a

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -793,6 +793,7 @@ I/O
793793
- Bug in :meth:`~DataFrame.read_feather` was raising an `ArrowIOError` when reading an s3 or http file path (:issue:`29055`)
794794
- Bug in :meth:`read_parquet` was raising a ``FileNotFoundError`` when passed an s3 directory path. (:issue:`26388`)
795795
- Bug in :meth:`~DataFrame.to_parquet` was throwing an ``AttributeError`` when writing a partitioned parquet file to s3 (:issue:`27596`)
796+
- Bug in :meth:`~DataFrame.to_json` with 'table' orient was writting wrong index field name for MultiIndex Dataframe with a single level. (:issue:`29928`)
796797

797798
Plotting
798799
^^^^^^^^

pandas/io/json/_json.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
from pandas.core.dtypes.common import ensure_str, is_period_dtype
1717

18-
from pandas import DataFrame, MultiIndex, Series, isna, to_datetime
18+
from pandas import DataFrame, Index, MultiIndex, Series, isna, to_datetime
1919
from pandas.core.construction import create_series_with_explicit_dtype
2020
from pandas.core.reshape.concat import concat
2121

@@ -286,6 +286,9 @@ def __init__(
286286
)
287287
raise ValueError(msg)
288288

289+
if obj.index.nlevels == 1 and isinstance(obj.index, MultiIndex):
290+
obj.index = obj.index.get_level_values(0)
291+
289292
self.schema = build_table_schema(obj, index=self.index)
290293

291294
# NotImplemented on a column MultiIndex

pandas/tests/io/json/test_json_table_schema.py

+15
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,21 @@ def test_to_json_categorical_index(self):
435435

436436
assert result == expected
437437

438+
@pytest.mark.parametrize("name", [None, "foo"])
439+
def test_multiindex_single_level(self, name):
440+
# GH29928
441+
index = pd.Index([1,2,3,4], name=name)
442+
df = pd.DataFrame(data=[[1,1],[2,2],[3,3],[4,4]], columns=['A','B'],
443+
index=index)
444+
expected = df.to_json(orient='table')
445+
446+
index = pd.MultiIndex.from_tuples([(1,),(2,),(3,),(4,)], names=[name])
447+
df = pd.DataFrame(data=[[1,1],[2,2],[3,3],[4,4]],columns=['A','B'],
448+
index=index)
449+
result = df.to_json(orient='table')
450+
451+
assert result == expected
452+
438453
def test_date_format_raises(self):
439454
with pytest.raises(ValueError):
440455
self.df.to_json(orient="table", date_format="epoch")

0 commit comments

Comments
 (0)