Skip to content

PERF: PeriodArray._format_native_types #51793

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 7, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions pandas/_libs/tslibs/period.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ def extract_ordinals(
def extract_freq(
values: npt.NDArray[np.object_],
) -> BaseOffset: ...
def period_array_strftime(
values: npt.NDArray[np.int64],
dtype_code: int,
na_rep,
date_format: str | None,
) -> npt.NDArray[np.object_]: ...

# exposed for tests
def period_asfreq(ordinal: int, freq1: int, freq2: int, end: bool) -> int: ...
Expand Down
48 changes: 48 additions & 0 deletions pandas/_libs/tslibs/period.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1268,6 +1268,54 @@ cdef str _period_strftime(int64_t value, int freq, bytes fmt):
return result


def period_array_strftime(
ndarray values, int dtype_code, object na_rep, str date_format
):
"""
Vectorized Period.strftime used for PeriodArray._format_native_types.

Parameters
----------
values : ndarray[int64_t], ndim unrestricted
dtype_code : int
Corresponds to PeriodDtype._dtype_code
na_rep : any
date_format : str or None
"""
cdef:
Py_ssize_t i, n = values.size
int64_t ordinal
object item_repr
Copy link
Member

Choose a reason for hiding this comment

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

This can't be a str?

Copy link
Member Author

Choose a reason for hiding this comment

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

In _format_native_types it is annotated as str | float

Copy link
Member Author

Choose a reason for hiding this comment

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

woops, thought you were referring to na_rep. this can't be str bc na_rep isn't str

Copy link
Member

Choose a reason for hiding this comment

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

Darn, (odd na_rep can be a float but okay)

ndarray out = cnp.PyArray_EMPTY(
values.ndim, values.shape, cnp.NPY_OBJECT, 0
)
object[::1] out_flat = out.ravel()
cnp.broadcast mi = cnp.PyArray_MultiIterNew2(out, values)

for i in range(n):
# Analogous to: ordinal = values[i]
ordinal = (<int64_t*>cnp.PyArray_MultiIter_DATA(mi, 1))[0]

if ordinal == NPY_NAT:
item_repr = na_rep
else:
# This is equivalent to
# freq = frequency_corresponding_to_dtype_code(dtype_code)
# per = Period(ordinal, freq=freq)
# if date_format:
# item_repr = per.strftime(date_format)
# else:
# item_repr = str(per)
item_repr = period_format(ordinal, dtype_code, date_format)

# Analogous to: ordinals[i] = ordinal
out_flat[i] = item_repr

cnp.PyArray_MultiIter_NEXT(mi)

return out


# ----------------------------------------------------------------------
# period accessors

Expand Down
22 changes: 3 additions & 19 deletions pandas/core/arrays/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,31 +616,15 @@ def _formatter(self, boxed: bool = False):
return str
return "'{}'".format

@dtl.ravel_compat
def _format_native_types(
self, *, na_rep: str | float = "NaT", date_format=None, **kwargs
) -> npt.NDArray[np.object_]:
"""
actually format my specific types
"""
values = self.astype(object)

# Create the formatter function
if date_format:
formatter = lambda per: per.strftime(date_format)
else:
# Uses `_Period.str` which in turn uses `format_period`
formatter = lambda per: str(per)

# Apply the formatter to all values in the array, possibly with a mask
if self._hasna:
mask = self._isnan
values[mask] = na_rep
imask = ~mask
values[imask] = np.array([formatter(per) for per in values[imask]])
else:
values = np.array([formatter(per) for per in values])
return values
return libperiod.period_array_strftime(
self.asi8, self.dtype._dtype_code, na_rep, date_format
)

# ------------------------------------------------------------------

Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/indexes/period/test_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def test_to_native_types():
index = PeriodIndex(["2017-01-01", "2017-01-02", "2017-01-03"], freq="D")

# First, with no arguments.
expected = np.array(["2017-01-01", "2017-01-02", "2017-01-03"], dtype="=U10")
expected = np.array(["2017-01-01", "2017-01-02", "2017-01-03"], dtype=object)

result = index._format_native_types()
tm.assert_numpy_array_equal(result, expected)
Expand All @@ -23,7 +23,7 @@ def test_to_native_types():
tm.assert_numpy_array_equal(result, expected)

# Make sure date formatting works
expected = np.array(["01-2017-01", "01-2017-02", "01-2017-03"], dtype="=U10")
expected = np.array(["01-2017-01", "01-2017-02", "01-2017-03"], dtype=object)

result = index._format_native_types(date_format="%m-%Y-%d")
tm.assert_numpy_array_equal(result, expected)
Expand Down