Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pandas/io/json/_table_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""
from __future__ import annotations

import re
from typing import (
TYPE_CHECKING,
Any,
Expand All @@ -15,6 +16,7 @@
from pandas._libs import lib
from pandas._libs.json import ujson_loads
from pandas._libs.tslibs import timezones
from pandas._libs.tslibs.dtypes import freq_to_period_freqstr
from pandas.util._exceptions import find_stack_level

from pandas.core.dtypes.base import _registry as registry
Expand Down Expand Up @@ -207,8 +209,12 @@ def convert_json_field_to_pandas_type(field) -> str | CategoricalDtype:
if field.get("tz"):
return f"datetime64[ns, {field['tz']}]"
elif field.get("freq"):
# GH#9586 rename frequency M to ME for offsets
freq_name = re.split("[0-9]*", field["freq"], maxsplit=1)[1]
freq_n = field["freq"][: field["freq"].index(freq_name)]
freq = freq_to_period_freqstr(freq_n, freq_name)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

having a regular expression here looks a bit complex - would it work to do

offset = to_offset(field['freq'])
freq_n, freq_name = offset.n, offset.name
freq = freq_to_period_freqstr(freq_n, freq_name)

instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thank you, it works very well. I replaced the regular expression with to_offset and updated my PR.

# GH#47747 using datetime over period to minimize the change surface
return f"period[{field['freq']}]"
return f"period[{freq}]"
else:
return "datetime64[ns]"
elif typ == "any":
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/io/json/test_json_table_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -845,3 +845,14 @@ def test_read_json_orient_table_old_schema_version(self):
expected = DataFrame({"a": [1, 2.0, "s"]})
result = pd.read_json(StringIO(df_json), orient="table")
tm.assert_frame_equal(expected, result)

@pytest.mark.parametrize("freq", ["M", "2M"])
def test_read_json_table_orient_period_depr_freq(self, freq, recwarn):
# GH#9586
df = DataFrame(
{"ints": [1, 2]},
index=pd.PeriodIndex(["2020-01", "2020-06"], freq=freq),
)
out = df.to_json(orient="table")
result = pd.read_json(out, orient="table")
tm.assert_frame_equal(df, result)