Skip to content

Commit 42f912e

Browse files
committed
BUG: pd.read_json May Not Maintain Numeric String Index
1 parent 6e18023 commit 42f912e

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

pandas/io/json/_json.py

+20
Original file line numberDiff line numberDiff line change
@@ -850,6 +850,26 @@ def _convert_axes(self):
850850
obj = self.obj
851851
assert obj is not None # for mypy
852852
for axis_name in obj._AXIS_ORDERS:
853+
if (
854+
self.orient == "split"
855+
and axis_name == "index"
856+
and obj._get_axis(axis_name).dtype == "object"
857+
and obj.index.inferred_type == "string"
858+
):
859+
index_list = list(obj._get_axis(axis_name).values)
860+
are_all_strings = all(type(element) == str for element in index_list)
861+
are_int_or_floats = [
862+
True
863+
for element in index_list
864+
if isinstance(element, int) or isinstance(element, float)
865+
]
866+
are_all_int_or_floats = all(
867+
are_int_or_floats for element in are_int_or_floats
868+
)
869+
if are_all_int_or_floats and are_all_strings:
870+
setattr(self.obj, axis_name, obj._get_axis(axis_name))
871+
continue
872+
853873
new_axis, result = self._try_convert_data(
854874
name=axis_name,
855875
data=obj._get_axis(axis_name),

pandas/tests/io/json/test_pandas.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -192,11 +192,14 @@ def test_roundtrip_str_axes(self, orient, convert_axes, numpy, dtype):
192192
# to disambiguate whether those keys actually were strings or numeric
193193
# beforehand and numeric wins out.
194194
# TODO: Split should be able to support this
195-
if convert_axes and (orient in ("split", "index", "columns")):
195+
if convert_axes and (orient in ("index", "columns")):
196196
expected.columns = expected.columns.astype(np.int64)
197197
expected.index = expected.index.astype(np.int64)
198198
elif orient == "records" and convert_axes:
199199
expected.columns = expected.columns.astype(np.int64)
200+
elif convert_axes and orient == "split":
201+
expected.columns = expected.columns.astype(np.int64)
202+
expected.index = expected.index.astype(str)
200203

201204
assert_json_roundtrip_equal(result, expected, orient)
202205

0 commit comments

Comments
 (0)