title stringlengths 1 185 | diff stringlengths 0 32.2M | body stringlengths 0 123k ⌀ | url stringlengths 57 58 | created_at stringlengths 20 20 | closed_at stringlengths 20 20 | merged_at stringlengths 20 20 ⌀ | updated_at stringlengths 20 20 |
|---|---|---|---|---|---|---|---|
[ArrowStringArray] PERF: small perf gain for object fallback | diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index a1278a129c40f..1e699e3a769b2 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -792,7 +792,8 @@ def _str_map(self, f, na_value=None, dtype: Dtype | None = None):
result = lib.map_infer_mask(
arr, f, mask.view("uint8"), convert=False, na_value=na_value
)
- return self._from_sequence(result)
+ result = pa.array(result, mask=mask, type=pa.string(), from_pandas=True)
+ return type(self)(result)
else:
# This is when the result type is object. We reach this when
# -> We know the result type is truly object (e.g. .encode returns bytes
| ```
before after ratio
[a43c42c3] [a5dd50ea]
<master> <small-perf>
- 26.8±0.05ms 26.1±0.1ms 0.97 strings.Methods.time_get('arrow_string')
- 21.2±0.1ms 20.3±0.1ms 0.96 strings.Methods.time_replace('arrow_string')
- 18.1±0.1ms 17.3±0.1ms 0.96 strings.Methods.time_lstrip('arrow_string')
- 18.5±0.1ms 17.7±0.2ms 0.95 strings.Methods.time_strip('arrow_string')
- 18.3±0.1ms 17.4±0.09ms 0.95 strings.Methods.time_rstrip('arrow_string')
- 28.0±0.3ms 26.6±0.07ms 0.95 strings.Methods.time_center('arrow_string')
- 21.2±0.2ms 20.1±0.1ms 0.95 strings.Methods.time_normalize('arrow_string')
- 28.1±0.2ms 26.5±0.2ms 0.94 strings.Methods.time_pad('arrow_string')
- 13.6±0.1ms 11.5±0.1ms 0.85 strings.Methods.time_isdigit('str')
- 13.6±0.2ms 11.3±0.04ms 0.83 strings.Methods.time_isnumeric('str')
SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.
PERFORMANCE INCREASED.
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/41338 | 2021-05-05T17:56:45Z | 2021-05-06T01:50:39Z | 2021-05-06T01:50:39Z | 2021-05-06T08:16:28Z |
DEP: bump pyarrow to 1.0.0 | diff --git a/ci/deps/actions-37-db-min.yaml b/ci/deps/actions-37-db-min.yaml
index 1d3794576220a..d103ca00a5503 100644
--- a/ci/deps/actions-37-db-min.yaml
+++ b/ci/deps/actions-37-db-min.yaml
@@ -31,7 +31,7 @@ dependencies:
- openpyxl
- pandas-gbq
- google-cloud-bigquery>=1.27.2 # GH 36436
- - pyarrow=0.17 # GH 38803
+ - pyarrow=1.0.0 # GH 38803
- pytables>=3.5.1
- scipy
- xarray=0.12.3
diff --git a/ci/deps/actions-37-db.yaml b/ci/deps/actions-37-db.yaml
index 8755e1a02c3cf..7c27ab8fb50d5 100644
--- a/ci/deps/actions-37-db.yaml
+++ b/ci/deps/actions-37-db.yaml
@@ -31,7 +31,7 @@ dependencies:
- pandas-gbq
- google-cloud-bigquery>=1.27.2 # GH 36436
- psycopg2
- - pyarrow>=0.15.0
+ - pyarrow>=1.0.0
- pymysql
- pytables
- python-snappy
diff --git a/ci/deps/actions-37-minimum_versions.yaml b/ci/deps/actions-37-minimum_versions.yaml
index 3237cf9770220..9431e63b1a1a9 100644
--- a/ci/deps/actions-37-minimum_versions.yaml
+++ b/ci/deps/actions-37-minimum_versions.yaml
@@ -23,7 +23,7 @@ dependencies:
- pytables=3.5.1
- python-dateutil=2.7.3
- pytz=2017.3
- - pyarrow=0.15
+ - pyarrow=1.0.0
- scipy=1.2
- xlrd=1.2.0
- xlsxwriter=1.0.2
diff --git a/ci/deps/actions-37.yaml b/ci/deps/actions-37.yaml
index f29830e9b3e79..b617a5c68f245 100644
--- a/ci/deps/actions-37.yaml
+++ b/ci/deps/actions-37.yaml
@@ -18,7 +18,7 @@ dependencies:
- numpy=1.19
- python-dateutil
- nomkl
- - pyarrow=0.15.1
+ - pyarrow=1.0.0
- pytz
- s3fs>=0.4.0
- moto>=1.3.14
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml
index 36e8bf528fc3e..790a9795bc6b2 100644
--- a/ci/deps/actions-39.yaml
+++ b/ci/deps/actions-39.yaml
@@ -19,4 +19,4 @@ dependencies:
# optional dependencies
- pytables
- scipy
- - pyarrow=1.0
+ - pyarrow=1.0.0
diff --git a/ci/deps/azure-macos-37.yaml b/ci/deps/azure-macos-37.yaml
index 8c8b49ff3df5b..5be7450901474 100644
--- a/ci/deps/azure-macos-37.yaml
+++ b/ci/deps/azure-macos-37.yaml
@@ -21,7 +21,7 @@ dependencies:
- numexpr
- numpy=1.17.3
- openpyxl
- - pyarrow=0.15.1
+ - pyarrow=1.0.0
- pytables
- python-dateutil==2.7.3
- pytz
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index c9d22ffbead45..f137065199d4a 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -26,7 +26,7 @@ dependencies:
- numexpr
- numpy=1.17.*
- openpyxl
- - pyarrow=0.15
+ - pyarrow=1.0.0
- pytables
- python-dateutil
- pytz
diff --git a/ci/deps/azure-windows-38.yaml b/ci/deps/azure-windows-38.yaml
index 661d8813d32d2..197e9db5e5de4 100644
--- a/ci/deps/azure-windows-38.yaml
+++ b/ci/deps/azure-windows-38.yaml
@@ -25,7 +25,7 @@ dependencies:
- numpy=1.18.*
- openpyxl
- jinja2
- - pyarrow>=0.15.0
+ - pyarrow>=1.0.0
- pytables
- python-dateutil
- pytz
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 69af8b500f790..4e2e69933e173 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -575,7 +575,7 @@ Optional libraries below the lowest tested version may still work, but are not c
+-----------------+-----------------+---------+
| openpyxl | 3.0.0 | X |
+-----------------+-----------------+---------+
-| pyarrow | 0.15.0 | |
+| pyarrow | 1.0.0 | X |
+-----------------+-----------------+---------+
| pymysql | 0.8.1 | X |
+-----------------+-----------------+---------+
diff --git a/environment.yml b/environment.yml
index 2e0228a15272e..b58024f2608db 100644
--- a/environment.yml
+++ b/environment.yml
@@ -100,7 +100,7 @@ dependencies:
- odfpy
- fastparquet>=0.3.2 # pandas.read_parquet, DataFrame.to_parquet
- - pyarrow>=0.15.0 # pandas.read_parquet, DataFrame.to_parquet, pandas.read_feather, DataFrame.to_feather
+ - pyarrow>=1.0.0 # pandas.read_parquet, DataFrame.to_parquet, pandas.read_feather, DataFrame.to_feather
- python-snappy # required by pyarrow
- pyqt>=5.9.2 # pandas.read_clipboard
diff --git a/requirements-dev.txt b/requirements-dev.txt
index ea7ca43742934..d4038d798e3de 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -65,7 +65,7 @@ xlsxwriter
xlwt
odfpy
fastparquet>=0.3.2
-pyarrow>=0.15.0
+pyarrow>=1.0.0
python-snappy
pyqt5>=5.9.2
tables>=3.5.1
| - [x] closes #41329
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41337 | 2021-05-05T17:51:20Z | 2021-05-07T19:05:51Z | null | 2021-05-12T12:05:07Z |
CI: Upgrade "actions/(checkout|cache)" to version 2 | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ca0c75f9de94f..a5a802c678e20 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -22,7 +22,9 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v1
+ uses: actions/checkout@v2
+ with:
+ fetch-depth: 0
- name: Looking for unwanted patterns
run: ci/code_checks.sh patterns
@@ -94,7 +96,9 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v1
+ uses: actions/checkout@v2
+ with:
+ fetch-depth: 0
- name: Set up pandas
uses: ./.github/actions/setup
@@ -147,7 +151,9 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v1
+ uses: actions/checkout@v2
+ with:
+ fetch-depth: 0
- name: Set up pandas
uses: ./.github/actions/setup
diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml
index a5aef7825c770..e119a26550e1c 100644
--- a/.github/workflows/database.yml
+++ b/.github/workflows/database.yml
@@ -56,10 +56,12 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v1
+ uses: actions/checkout@v2
+ with:
+ fetch-depth: 0
- name: Cache conda
- uses: actions/cache@v1
+ uses: actions/cache@v2
env:
CACHE_NUMBER: 0
with:
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index 34e6c2c9d94ce..3a4d3c106f851 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -44,10 +44,12 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v1
+ uses: actions/checkout@v2
+ with:
+ fetch-depth: 0
- name: Cache conda
- uses: actions/cache@v1
+ uses: actions/cache@v2
env:
CACHE_NUMBER: 0
with:
| According to the change log of both "checkout" and "cache" this should increase performance.
---
Fell free to close this PR if this was already discussed, I haven't saw any discussion about this topic. | https://api.github.com/repos/pandas-dev/pandas/pulls/41336 | 2021-05-05T17:21:32Z | 2021-05-24T06:02:23Z | 2021-05-24T06:02:23Z | 2021-08-26T13:52:29Z |
ENH: Add dropna argument to DataFrame.value_counts() | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 320912ec38890..cddaaa295af01 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -224,6 +224,7 @@ Other enhancements
- :meth:`.GroupBy.any` and :meth:`.GroupBy.all` return a ``BooleanDtype`` for columns with nullable data types (:issue:`33449`)
- Constructing a :class:`DataFrame` or :class:`Series` with the ``data`` argument being a Python iterable that is *not* a NumPy ``ndarray`` consisting of NumPy scalars will now result in a dtype with a precision the maximum of the NumPy scalars; this was already the case when ``data`` is a NumPy ``ndarray`` (:issue:`40908`)
- Add keyword ``sort`` to :func:`pivot_table` to allow non-sorting of the result (:issue:`39143`)
+- Add keyword ``dropna`` to :meth:`DataFrame.value_counts` to allow counting rows that include ``NA`` values (:issue:`41325`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 50837e1b3ed50..f3902b0a9d288 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -6380,6 +6380,7 @@ def value_counts(
normalize: bool = False,
sort: bool = True,
ascending: bool = False,
+ dropna: bool = True,
):
"""
Return a Series containing counts of unique rows in the DataFrame.
@@ -6396,6 +6397,10 @@ def value_counts(
Sort by frequencies.
ascending : bool, default False
Sort in ascending order.
+ dropna : bool, default True
+ Don’t include counts of rows that contain NA values.
+
+ .. versionadded:: 1.3.0
Returns
-------
@@ -6451,11 +6456,36 @@ def value_counts(
2 2 0.25
6 0 0.25
dtype: float64
+
+ With `dropna` set to `False` we can also count rows with NA values.
+
+ >>> df = pd.DataFrame({'first_name': ['John', 'Anne', 'John', 'Beth'],
+ ... 'middle_name': ['Smith', pd.NA, pd.NA, 'Louise']})
+ >>> df
+ first_name middle_name
+ 0 John Smith
+ 1 Anne <NA>
+ 2 John <NA>
+ 3 Beth Louise
+
+ >>> df.value_counts()
+ first_name middle_name
+ Beth Louise 1
+ John Smith 1
+ dtype: int64
+
+ >>> df.value_counts(dropna=False)
+ first_name middle_name
+ Anne NaN 1
+ Beth Louise 1
+ John Smith 1
+ NaN 1
+ dtype: int64
"""
if subset is None:
subset = self.columns.tolist()
- counts = self.groupby(subset).grouper.size()
+ counts = self.groupby(subset, dropna=dropna).grouper.size()
if sort:
counts = counts.sort_values(ascending=ascending)
diff --git a/pandas/tests/frame/methods/test_value_counts.py b/pandas/tests/frame/methods/test_value_counts.py
index 23f9ebdb4479d..6e8528845ea6b 100644
--- a/pandas/tests/frame/methods/test_value_counts.py
+++ b/pandas/tests/frame/methods/test_value_counts.py
@@ -100,3 +100,47 @@ def test_data_frame_value_counts_empty_normalize():
expected = pd.Series([], dtype=np.float64)
tm.assert_series_equal(result, expected)
+
+
+def test_data_frame_value_counts_dropna_true(nulls_fixture):
+ # GH 41334
+ df = pd.DataFrame(
+ {
+ "first_name": ["John", "Anne", "John", "Beth"],
+ "middle_name": ["Smith", nulls_fixture, nulls_fixture, "Louise"],
+ },
+ )
+ result = df.value_counts()
+ expected = pd.Series(
+ data=[1, 1],
+ index=pd.MultiIndex.from_arrays(
+ [("Beth", "John"), ("Louise", "Smith")], names=["first_name", "middle_name"]
+ ),
+ )
+
+ tm.assert_series_equal(result, expected)
+
+
+def test_data_frame_value_counts_dropna_false(nulls_fixture):
+ # GH 41334
+ df = pd.DataFrame(
+ {
+ "first_name": ["John", "Anne", "John", "Beth"],
+ "middle_name": ["Smith", nulls_fixture, nulls_fixture, "Louise"],
+ },
+ )
+
+ result = df.value_counts(dropna=False)
+ expected = pd.Series(
+ data=[1, 1, 1, 1],
+ index=pd.MultiIndex(
+ levels=[
+ pd.Index(["Anne", "Beth", "John"]),
+ pd.Index(["Louise", "Smith", nulls_fixture]),
+ ],
+ codes=[[0, 1, 2, 2], [2, 0, 1, 2]],
+ names=["first_name", "middle_name"],
+ ),
+ )
+
+ tm.assert_series_equal(result, expected)
| - [x] closes #41325
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41334 | 2021-05-05T16:18:56Z | 2021-05-10T14:39:30Z | 2021-05-10T14:39:30Z | 2022-09-08T08:15:31Z |
[ArrowStringArray] PERF: use pa.compute.match_substring_regex for str.fullmatch if available | diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py
index 0f68d1043b49d..2560d6726249e 100644
--- a/asv_bench/benchmarks/strings.py
+++ b/asv_bench/benchmarks/strings.py
@@ -83,6 +83,9 @@ def time_find(self, dtype):
def time_rfind(self, dtype):
self.s.str.rfind("[A-Z]+")
+ def time_fullmatch(self, dtype):
+ self.s.str.fullmatch("A")
+
def time_get(self, dtype):
self.s.str.get(0)
diff --git a/doc/redirects.csv b/doc/redirects.csv
index de69d0168835d..9b8a5a73dedff 100644
--- a/doc/redirects.csv
+++ b/doc/redirects.csv
@@ -1197,6 +1197,7 @@ generated/pandas.Series.str.extractall,../reference/api/pandas.Series.str.extrac
generated/pandas.Series.str.extract,../reference/api/pandas.Series.str.extract
generated/pandas.Series.str.findall,../reference/api/pandas.Series.str.findall
generated/pandas.Series.str.find,../reference/api/pandas.Series.str.find
+generated/pandas.Series.str.fullmatch,../reference/api/pandas.Series.str.fullmatch
generated/pandas.Series.str.get_dummies,../reference/api/pandas.Series.str.get_dummies
generated/pandas.Series.str.get,../reference/api/pandas.Series.str.get
generated/pandas.Series.str,../reference/api/pandas.Series.str
diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst
index cc2937695e80f..3ff3b2bb53fda 100644
--- a/doc/source/reference/series.rst
+++ b/doc/source/reference/series.rst
@@ -415,6 +415,7 @@ strings and apply several methods to it. These can be accessed like
Series.str.extractall
Series.str.find
Series.str.findall
+ Series.str.fullmatch
Series.str.get
Series.str.index
Series.str.join
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 252bc215869ac..d5ee28eb7017e 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -844,6 +844,14 @@ def _str_match(
pat = "^" + pat
return self._str_contains(pat, case, flags, na, regex=True)
+ def _str_fullmatch(self, pat, case: bool = True, flags: int = 0, na: Scalar = None):
+ if pa_version_under4p0:
+ return super()._str_fullmatch(pat, case, flags, na)
+
+ if not pat.endswith("$") or pat.endswith("//$"):
+ pat = pat + "$"
+ return self._str_match(pat, case, flags, na)
+
def _str_isalnum(self):
result = pc.utf8_is_alnum(self._data)
return BooleanDtype().__from_arrow__(result)
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 5606380908f38..696b06f174e28 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -1170,7 +1170,7 @@ def match(self, pat, case=True, flags=0, na=None):
Returns
-------
- Series/array of boolean values
+ Series/Index/array of boolean values
See Also
--------
@@ -1197,14 +1197,14 @@ def fullmatch(self, pat, case=True, flags=0, na=None):
If True, case sensitive.
flags : int, default 0 (no flags)
Regex module flags, e.g. re.IGNORECASE.
- na : scalar, optional.
+ na : scalar, optional
Fill value for missing values. The default depends on dtype of the
array. For object-dtype, ``numpy.nan`` is used. For ``StringDtype``,
``pandas.NA`` is used.
Returns
-------
- Series/array of boolean values
+ Series/Index/array of boolean values
See Also
--------
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index 843b0ba55e691..0815d23f2b493 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -494,10 +494,32 @@ def test_fullmatch(any_string_dtype):
expected = Series([True, False, np.nan, False], dtype=expected_dtype)
tm.assert_series_equal(result, expected)
+
+def test_fullmatch_na_kwarg(any_string_dtype):
+ ser = Series(
+ ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
+ )
+ result = ser.str.fullmatch(".*BAD[_]+.*BAD", na=False)
+ expected_dtype = np.bool_ if any_string_dtype == "object" else "boolean"
+ expected = Series([True, False, False, False], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+
+def test_fullmatch_case_kwarg(any_string_dtype):
ser = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype)
- result = ser.str.fullmatch("ab", case=False)
expected_dtype = np.bool_ if any_string_dtype == "object" else "boolean"
+
+ expected = Series([True, False, False, False], dtype=expected_dtype)
+
+ result = ser.str.fullmatch("ab", case=True)
+ tm.assert_series_equal(result, expected)
+
expected = Series([True, True, False, False], dtype=expected_dtype)
+
+ result = ser.str.fullmatch("ab", case=False)
+ tm.assert_series_equal(result, expected)
+
+ result = ser.str.fullmatch("ab", flags=re.IGNORECASE)
tm.assert_series_equal(result, expected)
| https://api.github.com/repos/pandas-dev/pandas/pulls/41332 | 2021-05-05T15:43:30Z | 2021-05-17T20:52:07Z | 2021-05-17T20:52:07Z | 2021-05-18T08:41:20Z | |
REF: dont special-case ngroups==0 | diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index 6b5cedf8a5243..c28db9b669a4b 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -105,10 +105,11 @@ cdef class SeriesBinGrouper(_BaseGrouper):
Py_ssize_t nresults, ngroups
cdef public:
+ ndarray bins # ndarray[int64_t]
ndarray arr, index, dummy_arr, dummy_index
- object values, f, bins, typ, ityp, name, idtype
+ object values, f, typ, ityp, name, idtype
- def __init__(self, object series, object f, object bins):
+ def __init__(self, object series, object f, ndarray[int64_t] bins):
assert len(bins) > 0 # otherwise we get IndexError in get_result
@@ -133,6 +134,8 @@ cdef class SeriesBinGrouper(_BaseGrouper):
if len(bins) > 0 and bins[-1] == len(series):
self.ngroups = len(bins)
else:
+ # TODO: not reached except in test_series_bin_grouper directly
+ # constructing SeriesBinGrouper; can we rule this case out?
self.ngroups = len(bins) + 1
def get_result(self):
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index c5ef18c51a533..7a5054fa2a1a5 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1331,18 +1331,7 @@ def _agg_py_fallback(
# reductions; see GH#28949
ser = df.iloc[:, 0]
- # Create SeriesGroupBy with observed=True so that it does
- # not try to add missing categories if grouping over multiple
- # Categoricals. This will done by later self._reindex_output()
- # Doing it here creates an error. See GH#34951
- sgb = get_groupby(ser, self.grouper, observed=True)
- # For SeriesGroupBy we could just use self instead of sgb
-
- if self.ngroups > 0:
- res_values = self.grouper.agg_series(ser, alt)
- else:
- # equiv: res_values = self._python_agg_general(alt)
- res_values = sgb._python_apply_general(alt, ser)._values
+ res_values = self.grouper.agg_series(ser, alt)
if isinstance(values, Categorical):
# Because we only get here with known dtype-preserving
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index d1a46c1c36439..2f4b126c119ef 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -969,8 +969,8 @@ def _cython_operation(
@final
def agg_series(self, obj: Series, func: F) -> ArrayLike:
- # Caller is responsible for checking ngroups != 0
- assert self.ngroups != 0
+ # test_groupby_empty_with_category gets here with self.ngroups == 0
+ # and len(obj) > 0
cast_back = True
if len(obj) == 0:
@@ -1007,7 +1007,6 @@ def _aggregate_series_fast(self, obj: Series, func: F) -> np.ndarray:
# - obj.index is not a MultiIndex
# - obj is backed by an ndarray, not ExtensionArray
# - len(obj) > 0
- # - ngroups != 0
func = com.is_builtin_func(func)
ids, _, ngroups = self.group_info
diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py
index aa126ae801f1e..92e5e709a9b2e 100644
--- a/pandas/tests/groupby/test_bin_groupby.py
+++ b/pandas/tests/groupby/test_bin_groupby.py
@@ -56,7 +56,7 @@ def test_series_grouper_requires_nonempty_raises():
def test_series_bin_grouper():
obj = Series(np.random.randn(10))
- bins = np.array([3, 6])
+ bins = np.array([3, 6], dtype=np.int64)
grouper = libreduction.SeriesBinGrouper(obj, np.mean, bins)
result, counts = grouper.get_result()
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41331 | 2021-05-05T15:42:27Z | 2021-05-06T23:22:16Z | 2021-05-06T23:22:16Z | 2021-05-06T23:23:31Z |
CLN: remove unnecessary return from agg_series | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index b7254ffecb2bc..c5ef18c51a533 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1269,7 +1269,7 @@ def _python_agg_general(self, func, *args, **kwargs):
try:
# if this function is invalid for this dtype, we will ignore it.
- result, counts = self.grouper.agg_series(obj, f)
+ result = self.grouper.agg_series(obj, f)
except TypeError:
continue
@@ -1339,7 +1339,7 @@ def _agg_py_fallback(
# For SeriesGroupBy we could just use self instead of sgb
if self.ngroups > 0:
- res_values, _ = self.grouper.agg_series(ser, alt)
+ res_values = self.grouper.agg_series(ser, alt)
else:
# equiv: res_values = self._python_agg_general(alt)
res_values = sgb._python_apply_general(alt, ser)._values
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 60d79718cd85f..a6f2a537375a4 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -969,28 +969,28 @@ def _cython_operation(
)
@final
- def agg_series(self, obj: Series, func: F) -> tuple[ArrayLike, np.ndarray]:
+ def agg_series(self, obj: Series, func: F) -> ArrayLike:
# Caller is responsible for checking ngroups != 0
assert self.ngroups != 0
cast_back = True
if len(obj) == 0:
# SeriesGrouper would raise if we were to call _aggregate_series_fast
- result, counts = self._aggregate_series_pure_python(obj, func)
+ result = self._aggregate_series_pure_python(obj, func)
elif is_extension_array_dtype(obj.dtype):
# _aggregate_series_fast would raise TypeError when
# calling libreduction.Slider
# In the datetime64tz case it would incorrectly cast to tz-naive
# TODO: can we get a performant workaround for EAs backed by ndarray?
- result, counts = self._aggregate_series_pure_python(obj, func)
+ result = self._aggregate_series_pure_python(obj, func)
elif obj.index._has_complex_internals:
# Preempt TypeError in _aggregate_series_fast
- result, counts = self._aggregate_series_pure_python(obj, func)
+ result = self._aggregate_series_pure_python(obj, func)
else:
- result, counts = self._aggregate_series_fast(obj, func)
+ result = self._aggregate_series_fast(obj, func)
cast_back = False
npvalues = lib.maybe_convert_objects(result, try_float=False)
@@ -999,11 +999,11 @@ def agg_series(self, obj: Series, func: F) -> tuple[ArrayLike, np.ndarray]:
out = maybe_cast_pointwise_result(npvalues, obj.dtype, numeric_only=True)
else:
out = npvalues
- return out, counts
+ return out
+
+ def _aggregate_series_fast(self, obj: Series, func: F) -> np.ndarray:
+ # -> np.ndarray[object]
- def _aggregate_series_fast(
- self, obj: Series, func: F
- ) -> tuple[ArrayLike, np.ndarray]:
# At this point we have already checked that
# - obj.index is not a MultiIndex
# - obj is backed by an ndarray, not ExtensionArray
@@ -1018,11 +1018,12 @@ def _aggregate_series_fast(
obj = obj.take(indexer)
ids = ids.take(indexer)
sgrouper = libreduction.SeriesGrouper(obj, func, ids, ngroups)
- result, counts = sgrouper.get_result()
- return result, counts
+ result, _ = sgrouper.get_result()
+ return result
@final
- def _aggregate_series_pure_python(self, obj: Series, func: F):
+ def _aggregate_series_pure_python(self, obj: Series, func: F) -> np.ndarray:
+ # -> np.ndarray[object]
ids, _, ngroups = self.group_info
counts = np.zeros(ngroups, dtype=int)
@@ -1047,7 +1048,7 @@ def _aggregate_series_pure_python(self, obj: Series, func: F):
counts[i] = group.shape[0]
result[i] = res
- return result, counts
+ return result
class BinGrouper(BaseGrouper):
@@ -1205,16 +1206,17 @@ def groupings(self) -> list[grouper.Grouping]:
ping = grouper.Grouping(lev, lev, in_axis=False, level=None, name=lev.name)
return [ping]
- def _aggregate_series_fast(
- self, obj: Series, func: F
- ) -> tuple[ArrayLike, np.ndarray]:
+ def _aggregate_series_fast(self, obj: Series, func: F) -> np.ndarray:
+ # -> np.ndarray[object]
+
# At this point we have already checked that
# - obj.index is not a MultiIndex
# - obj is backed by an ndarray, not ExtensionArray
# - ngroups != 0
# - len(self.bins) > 0
sbg = libreduction.SeriesBinGrouper(obj, func, self.bins)
- return sbg.get_result()
+ result, _ = sbg.get_result()
+ return result
def _is_indexed_like(obj, axes, axis: int) -> bool:
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41330 | 2021-05-05T15:36:40Z | 2021-05-06T01:40:08Z | 2021-05-06T01:40:08Z | 2021-05-06T02:01:42Z |
Revert "CI: pin py310-dev version to alpha 7" | diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index 221501ae028f3..2643dc5ec656e 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -22,7 +22,7 @@ jobs:
- name: Set up Python Dev Version
uses: actions/setup-python@v2
with:
- python-version: '3.10.0-alpha.7'
+ python-version: '3.10-dev'
- name: Install dependencies
run: |
| Reverts pandas-dev/pandas#41315, closes #41313 | https://api.github.com/repos/pandas-dev/pandas/pulls/41328 | 2021-05-05T12:01:54Z | 2021-05-05T12:58:42Z | 2021-05-05T12:58:42Z | 2021-05-05T12:58:45Z |
[ArrowStringArray] CLN: remove hasattr checks | diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py
index af2dfe796f82d..8d64bf8852946 100644
--- a/pandas/compat/__init__.py
+++ b/pandas/compat/__init__.py
@@ -20,6 +20,12 @@
np_version_under1p19,
np_version_under1p20,
)
+from pandas.compat.pyarrow import (
+ pa_version_under1p0,
+ pa_version_under2p0,
+ pa_version_under3p0,
+ pa_version_under4p0,
+)
PY38 = sys.version_info >= (3, 8)
PY39 = sys.version_info >= (3, 9)
@@ -136,4 +142,8 @@ def get_lzma_file(lzma):
"np_version_under1p18",
"np_version_under1p19",
"np_version_under1p20",
+ "pa_version_under1p0",
+ "pa_version_under2p0",
+ "pa_version_under3p0",
+ "pa_version_under4p0",
]
diff --git a/pandas/compat/pyarrow.py b/pandas/compat/pyarrow.py
new file mode 100644
index 0000000000000..e9ca9b99d4380
--- /dev/null
+++ b/pandas/compat/pyarrow.py
@@ -0,0 +1,18 @@
+""" support pyarrow compatibility across versions """
+
+from distutils.version import LooseVersion
+
+try:
+ import pyarrow as pa
+
+ _pa_version = pa.__version__
+ _palv = LooseVersion(_pa_version)
+ pa_version_under1p0 = _palv < LooseVersion("1.0.0")
+ pa_version_under2p0 = _palv < LooseVersion("2.0.0")
+ pa_version_under3p0 = _palv < LooseVersion("3.0.0")
+ pa_version_under4p0 = _palv < LooseVersion("4.0.0")
+except ImportError:
+ pa_version_under1p0 = True
+ pa_version_under2p0 = True
+ pa_version_under3p0 = True
+ pa_version_under4p0 = True
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index de987b8d34f08..a1278a129c40f 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -22,6 +22,11 @@
Scalar,
type_t,
)
+from pandas.compat import (
+ pa_version_under2p0,
+ pa_version_under3p0,
+ pa_version_under4p0,
+)
from pandas.util._decorators import doc
from pandas.util._validators import validate_fillna_kwargs
@@ -667,9 +672,7 @@ def take(
return type(self)(self._data.take(indices_array))
def isin(self, values):
-
- # pyarrow.compute.is_in added in pyarrow 2.0.0
- if not hasattr(pc, "is_in"):
+ if pa_version_under2p0:
return super().isin(values)
value_set = [
@@ -684,7 +687,7 @@ def isin(self, values):
return np.zeros(len(self), dtype=bool)
kwargs = {}
- if LooseVersion(pa.__version__) < "3.0.0":
+ if pa_version_under3p0:
# in pyarrow 2.0.0 skip_null is ignored but is a required keyword and raises
# with unexpected keyword argument in pyarrow 3.0.0+
kwargs["skip_null"] = True
@@ -802,11 +805,10 @@ def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex: bool = True):
return super()._str_contains(pat, case, flags, na, regex)
if regex:
- # match_substring_regex added in pyarrow 4.0.0
- if hasattr(pc, "match_substring_regex") and case:
- result = pc.match_substring_regex(self._data, pat)
- else:
+ if pa_version_under4p0 or case is False:
return super()._str_contains(pat, case, flags, na, regex)
+ else:
+ result = pc.match_substring_regex(self._data, pat)
else:
if case:
result = pc.match_substring(self._data, pat)
@@ -818,27 +820,25 @@ def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex: bool = True):
return result
def _str_startswith(self, pat, na=None):
- # match_substring_regex added in pyarrow 4.0.0
- if hasattr(pc, "match_substring_regex"):
- result = pc.match_substring_regex(self._data, "^" + re.escape(pat))
- result = BooleanDtype().__from_arrow__(result)
- if not isna(na):
- result[isna(result)] = bool(na)
- return result
- else:
+ if pa_version_under4p0:
return super()._str_startswith(pat, na)
+ result = pc.match_substring_regex(self._data, "^" + re.escape(pat))
+ result = BooleanDtype().__from_arrow__(result)
+ if not isna(na):
+ result[isna(result)] = bool(na)
+ return result
+
def _str_endswith(self, pat, na=None):
- # match_substring_regex added in pyarrow 4.0.0
- if hasattr(pc, "match_substring_regex"):
- result = pc.match_substring_regex(self._data, re.escape(pat) + "$")
- result = BooleanDtype().__from_arrow__(result)
- if not isna(na):
- result[isna(result)] = bool(na)
- return result
- else:
+ if pa_version_under4p0:
return super()._str_endswith(pat, na)
+ result = pc.match_substring_regex(self._data, re.escape(pat) + "$")
+ result = BooleanDtype().__from_arrow__(result)
+ if not isna(na):
+ result[isna(result)] = bool(na)
+ return result
+
def _str_match(
self, pat: str, case: bool = True, flags: int = 0, na: Scalar = None
):
@@ -871,13 +871,12 @@ def _str_isnumeric(self):
return BooleanDtype().__from_arrow__(result)
def _str_isspace(self):
- # utf8_is_space added in pyarrow 2.0.0
- if hasattr(pc, "utf8_is_space"):
- result = pc.utf8_is_space(self._data)
- return BooleanDtype().__from_arrow__(result)
- else:
+ if pa_version_under2p0:
return super()._str_isspace()
+ result = pc.utf8_is_space(self._data)
+ return BooleanDtype().__from_arrow__(result)
+
def _str_istitle(self):
result = pc.utf8_is_title(self._data)
return BooleanDtype().__from_arrow__(result)
@@ -887,13 +886,12 @@ def _str_isupper(self):
return BooleanDtype().__from_arrow__(result)
def _str_len(self):
- # utf8_length added in pyarrow 4.0.0
- if hasattr(pc, "utf8_length"):
- result = pc.utf8_length(self._data)
- return Int64Dtype().__from_arrow__(result)
- else:
+ if pa_version_under4p0:
return super()._str_len()
+ result = pc.utf8_length(self._data)
+ return Int64Dtype().__from_arrow__(result)
+
def _str_lower(self):
return type(self)(pc.utf8_lower(self._data))
@@ -901,34 +899,31 @@ def _str_upper(self):
return type(self)(pc.utf8_upper(self._data))
def _str_strip(self, to_strip=None):
+ if pa_version_under4p0:
+ return super()._str_strip(to_strip)
+
if to_strip is None:
- # utf8_trim_whitespace added in pyarrow 4.0.0
- if hasattr(pc, "utf8_trim_whitespace"):
- return type(self)(pc.utf8_trim_whitespace(self._data))
+ result = pc.utf8_trim_whitespace(self._data)
else:
- # utf8_trim added in pyarrow 4.0.0
- if hasattr(pc, "utf8_trim"):
- return type(self)(pc.utf8_trim(self._data, characters=to_strip))
- return super()._str_strip(to_strip)
+ result = pc.utf8_trim(self._data, characters=to_strip)
+ return type(self)(result)
def _str_lstrip(self, to_strip=None):
+ if pa_version_under4p0:
+ return super()._str_lstrip(to_strip)
+
if to_strip is None:
- # utf8_ltrim_whitespace added in pyarrow 4.0.0
- if hasattr(pc, "utf8_ltrim_whitespace"):
- return type(self)(pc.utf8_ltrim_whitespace(self._data))
+ result = pc.utf8_ltrim_whitespace(self._data)
else:
- # utf8_ltrim added in pyarrow 4.0.0
- if hasattr(pc, "utf8_ltrim"):
- return type(self)(pc.utf8_ltrim(self._data, characters=to_strip))
- return super()._str_lstrip(to_strip)
+ result = pc.utf8_ltrim(self._data, characters=to_strip)
+ return type(self)(result)
def _str_rstrip(self, to_strip=None):
+ if pa_version_under4p0:
+ return super()._str_rstrip(to_strip)
+
if to_strip is None:
- # utf8_rtrim_whitespace added in pyarrow 4.0.0
- if hasattr(pc, "utf8_rtrim_whitespace"):
- return type(self)(pc.utf8_rtrim_whitespace(self._data))
+ result = pc.utf8_rtrim_whitespace(self._data)
else:
- # utf8_rtrim added in pyarrow 4.0.0
- if hasattr(pc, "utf8_rtrim"):
- return type(self)(pc.utf8_rtrim(self._data, characters=to_strip))
- return super()._str_rstrip(to_strip)
+ result = pc.utf8_rtrim(self._data, characters=to_strip)
+ return type(self)(result)
| xref https://github.com/pandas-dev/pandas/pull/41281#discussion_r625926407 | https://api.github.com/repos/pandas-dev/pandas/pulls/41327 | 2021-05-05T11:51:06Z | 2021-05-05T15:23:44Z | 2021-05-05T15:23:44Z | 2021-05-05T15:24:04Z |
[ArrowStringArray] PERF: use pa.compute.match_substring_regex for str.match if available | diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 44298401d02cb..e48de531db86c 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -19,6 +19,7 @@
Dtype,
NpDtype,
PositionalIndexer,
+ Scalar,
type_t,
)
from pandas.util._decorators import doc
@@ -808,6 +809,13 @@ def _str_endswith(self, pat, na=None):
else:
return super()._str_endswith(pat, na)
+ def _str_match(
+ self, pat: str, case: bool = True, flags: int = 0, na: Scalar = None
+ ):
+ if not pat.startswith("^"):
+ pat = "^" + pat
+ return self._str_contains(pat, case, flags, na, regex=True)
+
def _str_isalnum(self):
result = pc.utf8_is_alnum(self._data)
return BooleanDtype().__from_arrow__(result)
diff --git a/pandas/core/strings/base.py b/pandas/core/strings/base.py
index b8033668aa18f..a77f8861a7c02 100644
--- a/pandas/core/strings/base.py
+++ b/pandas/core/strings/base.py
@@ -61,11 +61,7 @@ def _str_repeat(self, repeats):
@abc.abstractmethod
def _str_match(
- self,
- pat: Union[str, Pattern],
- case: bool = True,
- flags: int = 0,
- na: Scalar = np.nan,
+ self, pat: str, case: bool = True, flags: int = 0, na: Scalar = np.nan
):
pass
diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py
index 0d8db3d3778a3..869eabc76b555 100644
--- a/pandas/core/strings/object_array.py
+++ b/pandas/core/strings/object_array.py
@@ -186,11 +186,7 @@ def rep(x, r):
return result
def _str_match(
- self,
- pat: Union[str, Pattern],
- case: bool = True,
- flags: int = 0,
- na: Scalar = None,
+ self, pat: str, case: bool = True, flags: int = 0, na: Scalar = None
):
if not case:
flags |= re.IGNORECASE
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index 404a7aaf3c9a9..06a7c6d56a61d 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -409,19 +409,39 @@ def test_replace_literal(any_string_dtype):
values.str.replace(compiled_pat, "", regex=False)
-def test_match():
+def test_match(any_string_dtype):
# New match behavior introduced in 0.13
- values = Series(["fooBAD__barBAD", np.nan, "foo"])
+ expected_dtype = "object" if any_string_dtype == "object" else "boolean"
+
+ values = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
result = values.str.match(".*(BAD[_]+).*(BAD)")
- exp = Series([True, np.nan, False])
- tm.assert_series_equal(result, exp)
+ expected = Series([True, np.nan, False], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
- values = Series(["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"])
+ values = Series(
+ ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
+ )
result = values.str.match(".*BAD[_]+.*BAD")
- exp = Series([True, True, np.nan, False])
- tm.assert_series_equal(result, exp)
+ expected = Series([True, True, np.nan, False], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
- # mixed
+ result = values.str.match("BAD[_]+.*BAD")
+ expected = Series([False, True, np.nan, False], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+ values = Series(
+ ["fooBAD__barBAD", "^BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
+ )
+ result = values.str.match("^BAD[_]+.*BAD")
+ expected = Series([False, False, np.nan, False], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+ result = values.str.match("\\^BAD[_]+.*BAD")
+ expected = Series([False, True, np.nan, False], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+
+def test_match_mixed_object():
mixed = Series(
[
"aBAD_BAD",
@@ -435,22 +455,34 @@ def test_match():
2.0,
]
)
- rs = Series(mixed).str.match(".*(BAD[_]+).*(BAD)")
- xp = Series([True, np.nan, True, np.nan, np.nan, False, np.nan, np.nan, np.nan])
- assert isinstance(rs, Series)
- tm.assert_series_equal(rs, xp)
+ result = Series(mixed).str.match(".*(BAD[_]+).*(BAD)")
+ expected = Series(
+ [True, np.nan, True, np.nan, np.nan, False, np.nan, np.nan, np.nan]
+ )
+ assert isinstance(result, Series)
+ tm.assert_series_equal(result, expected)
+
- # na GH #6609
- res = Series(["a", 0, np.nan]).str.match("a", na=False)
- exp = Series([True, False, False])
- tm.assert_series_equal(exp, res)
- res = Series(["a", 0, np.nan]).str.match("a")
- exp = Series([True, np.nan, np.nan])
- tm.assert_series_equal(exp, res)
+def test_match_na_kwarg(any_string_dtype):
+ # GH #6609
+ s = Series(["a", "b", np.nan], dtype=any_string_dtype)
- values = Series(["ab", "AB", "abc", "ABC"])
+ result = s.str.match("a", na=False)
+ expected_dtype = np.bool_ if any_string_dtype == "object" else "boolean"
+ expected = Series([True, False, False], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+ result = s.str.match("a")
+ expected_dtype = "object" if any_string_dtype == "object" else "boolean"
+ expected = Series([True, False, np.nan], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+
+def test_match_case_kwarg(any_string_dtype):
+ values = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype)
result = values.str.match("ab", case=False)
- expected = Series([True, True, True, True])
+ expected_dtype = np.bool_ if any_string_dtype == "object" else "boolean"
+ expected = Series([True, True, True, True], dtype=expected_dtype)
tm.assert_series_equal(result, expected)
|
```
[ 50.00%] ··· strings.Methods.time_match ok
[ 50.00%] ··· ============== ==========
dtype
-------------- ----------
str 28.3±0ms
string 22.5±0ms
arrow_string 2.46±0ms
============== ==========
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/41326 | 2021-05-05T10:43:24Z | 2021-05-05T12:31:31Z | 2021-05-05T12:31:31Z | 2021-05-05T12:45:09Z |
BUG: groupby(axis=0).rank(axis=1) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 320912ec38890..7520b14127c28 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -885,6 +885,7 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrame.rolling` returning sum not zero for all ``NaN`` window with ``min_periods=0`` if calculation is not numerical stable (:issue:`41053`)
- Bug in :meth:`SeriesGroupBy.agg` failing to retain ordered :class:`CategoricalDtype` on order-preserving aggregations (:issue:`41147`)
- Bug in :meth:`DataFrameGroupBy.min` and :meth:`DataFrameGroupBy.max` with multiple object-dtype columns and ``numeric_only=False`` incorrectly raising ``ValueError`` (:issue:41111`)
+- Bug in :meth:`DataFrameGroupBy.rank` with the GroupBy object's ``axis=0`` and the ``rank`` method's keyword ``axis=1`` (:issue:`41320`)
Reshaping
^^^^^^^^^
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 7a8b41fbdf141..9bc9895f3798f 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -2662,14 +2662,23 @@ def rank(
if na_option not in {"keep", "top", "bottom"}:
msg = "na_option must be one of 'keep', 'top', or 'bottom'"
raise ValueError(msg)
+
+ kwargs = {
+ "ties_method": method,
+ "ascending": ascending,
+ "na_option": na_option,
+ "pct": pct,
+ }
+ if axis != 0:
+ # DataFrame uses different keyword name
+ kwargs["method"] = kwargs.pop("ties_method")
+ return self.apply(lambda x: x.rank(axis=axis, numeric_only=False, **kwargs))
+
return self._cython_transform(
"rank",
numeric_only=False,
- ties_method=method,
- ascending=ascending,
- na_option=na_option,
- pct=pct,
axis=axis,
+ **kwargs,
)
@final
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index ffd6209cb83fb..ae46d1b024cc2 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -44,6 +44,7 @@
ensure_float64,
ensure_int64,
ensure_platform_int,
+ is_1d_only_ea_obj,
is_bool_dtype,
is_categorical_dtype,
is_complex_dtype,
@@ -600,9 +601,11 @@ def cython_operation(
if values.ndim > 2:
raise NotImplementedError("number of dimensions is currently limited to 2")
elif values.ndim == 2:
+ assert axis == 1, axis
+ elif not is_1d_only_ea_obj(values):
# Note: it is *not* the case that axis is always 0 for 1-dim values,
# as we can have 1D ExtensionArrays that we need to treat as 2D
- assert axis == 1, axis
+ assert axis == 0
dtype = values.dtype
is_numeric = is_numeric_dtype(dtype)
diff --git a/pandas/tests/groupby/test_rank.py b/pandas/tests/groupby/test_rank.py
index e07c5f404a02a..20edf03c5b96c 100644
--- a/pandas/tests/groupby/test_rank.py
+++ b/pandas/tests/groupby/test_rank.py
@@ -600,3 +600,18 @@ def test_rank_multiindex():
)
tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_axis0_rank_axis1():
+ # GH#41320
+ df = DataFrame(
+ {0: [1, 3, 5, 7], 1: [2, 4, 6, 8], 2: [1.5, 3.5, 5.5, 7.5]},
+ index=["a", "a", "b", "b"],
+ )
+ gb = df.groupby(level=0, axis=0)
+
+ res = gb.rank(axis=1)
+
+ # This should match what we get when "manually" operating group-by-group
+ expected = concat([df.loc["a"].rank(axis=1), df.loc["b"].rank(axis=1)], axis=0)
+ tm.assert_frame_equal(res, expected)
| - [x] closes #41320
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41324 | 2021-05-05T03:46:20Z | 2021-05-05T14:52:58Z | 2021-05-05T14:52:58Z | 2021-05-05T15:01:02Z |
DOC: GH41180 Updated DataFrame.nunique doc string for clarity | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 50837e1b3ed50..32fefb8f9a95f 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -9834,10 +9834,10 @@ def nunique(self, axis: Axis = 0, dropna: bool = True) -> Series:
Examples
--------
- >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1]})
+ >>> df = pd.DataFrame({'A': [5, 6, 7], 'B': [5, 1, 1]})
>>> df.nunique()
A 3
- B 1
+ B 2
dtype: int64
>>> df.nunique(axis=1)
| - closes #41180
| https://api.github.com/repos/pandas-dev/pandas/pulls/41322 | 2021-05-05T01:02:08Z | 2021-05-05T12:32:19Z | null | 2021-05-05T12:32:20Z |
ENH: loosen XLS signature | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 84f9dae8a0850..196a5b5cd136e 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -197,7 +197,7 @@ Other enhancements
- Improved integer type mapping from pandas to SQLAlchemy when using :meth:`DataFrame.to_sql` (:issue:`35076`)
- :func:`to_numeric` now supports downcasting of nullable ``ExtensionDtype`` objects (:issue:`33013`)
- Add support for dict-like names in :class:`MultiIndex.set_names` and :class:`MultiIndex.rename` (:issue:`20421`)
-- :func:`pandas.read_excel` can now auto detect .xlsb files (:issue:`35416`)
+- :func:`pandas.read_excel` can now auto detect .xlsb files and older .xls files (:issue:`35416`, :issue:`41225`)
- :class:`pandas.ExcelWriter` now accepts an ``if_sheet_exists`` parameter to control the behaviour of append mode when writing to existing sheets (:issue:`40230`)
- :meth:`.Rolling.sum`, :meth:`.Expanding.sum`, :meth:`.Rolling.mean`, :meth:`.Expanding.mean`, :meth:`.ExponentialMovingWindow.mean`, :meth:`.Rolling.median`, :meth:`.Expanding.median`, :meth:`.Rolling.max`, :meth:`.Expanding.max`, :meth:`.Rolling.min`, and :meth:`.Expanding.min` now support ``Numba`` execution with the ``engine`` keyword (:issue:`38895`, :issue:`41267`)
- :meth:`DataFrame.apply` can now accept NumPy unary operators as strings, e.g. ``df.apply("sqrt")``, which was already the case for :meth:`Series.apply` (:issue:`39116`)
@@ -843,6 +843,8 @@ I/O
- Bug in :func:`read_csv` and :func:`read_excel` not respecting dtype for duplicated column name when ``mangle_dupe_cols`` is set to ``True`` (:issue:`35211`)
- Bug in :func:`read_csv` and :func:`read_table` misinterpreting arguments when ``sys.setprofile`` had been previously called (:issue:`41069`)
- Bug in the conversion from pyarrow to pandas (e.g. for reading Parquet) with nullable dtypes and a pyarrow array whose data buffer size is not a multiple of dtype size (:issue:`40896`)
+- Bug in :func:`read_excel` would raise an error when pandas could not determine the file type, even when user specified the ``engine`` argument (:issue:`41225`)
+-
Period
^^^^^^
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 4b81b69976c62..ae9fba25cf002 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -1014,16 +1014,21 @@ def close(self):
return content
-XLS_SIGNATURE = b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
+XLS_SIGNATURES = (
+ b"\x09\x00\x04\x00\x07\x00\x10\x00", # BIFF2
+ b"\x09\x02\x06\x00\x00\x00\x10\x00", # BIFF3
+ b"\x09\x04\x06\x00\x00\x00\x10\x00", # BIFF4
+ b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1", # Compound File Binary
+)
ZIP_SIGNATURE = b"PK\x03\x04"
-PEEK_SIZE = max(len(XLS_SIGNATURE), len(ZIP_SIGNATURE))
+PEEK_SIZE = max(map(len, XLS_SIGNATURES + (ZIP_SIGNATURE,)))
@doc(storage_options=_shared_docs["storage_options"])
def inspect_excel_format(
content_or_path: FilePathOrBuffer,
storage_options: StorageOptions = None,
-) -> str:
+) -> str | None:
"""
Inspect the path or content of an excel file and get its format.
@@ -1037,8 +1042,8 @@ def inspect_excel_format(
Returns
-------
- str
- Format of file.
+ str or None
+ Format of file if it can be determined.
Raises
------
@@ -1063,10 +1068,10 @@ def inspect_excel_format(
peek = buf
stream.seek(0)
- if peek.startswith(XLS_SIGNATURE):
+ if any(peek.startswith(sig) for sig in XLS_SIGNATURES):
return "xls"
elif not peek.startswith(ZIP_SIGNATURE):
- raise ValueError("File is not a recognized excel file")
+ return None
# ZipFile typing is overly-strict
# https://github.com/python/typeshed/issues/4212
@@ -1174,8 +1179,12 @@ def __init__(
ext = inspect_excel_format(
content_or_path=path_or_buffer, storage_options=storage_options
)
+ if ext is None:
+ raise ValueError(
+ "Excel file format cannot be determined, you must specify "
+ "an engine manually."
+ )
- # ext will always be valid, otherwise inspect_excel_format would raise
engine = config.get_option(f"io.excel.{ext}.reader", silent=True)
if engine == "auto":
engine = get_default_engine(ext, mode="reader")
@@ -1190,12 +1199,13 @@ def __init__(
path_or_buffer, storage_options=storage_options
)
- if ext != "xls" and xlrd_version >= Version("2"):
+ # Pass through if ext is None, otherwise check if ext valid for xlrd
+ if ext and ext != "xls" and xlrd_version >= Version("2"):
raise ValueError(
f"Your version of xlrd is {xlrd_version}. In xlrd >= 2.0, "
f"only the xls format is supported. Install openpyxl instead."
)
- elif ext != "xls":
+ elif ext and ext != "xls":
caller = inspect.stack()[1]
if (
caller.filename.endswith(
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index a46cb70097bd8..aec638a0d8612 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -727,9 +727,20 @@ def test_missing_file_raises(self, read_ext):
def test_corrupt_bytes_raises(self, read_ext, engine):
bad_stream = b"foo"
- if engine is None or engine == "xlrd":
+ if engine is None:
error = ValueError
- msg = "File is not a recognized excel file"
+ msg = (
+ "Excel file format cannot be determined, you must "
+ "specify an engine manually."
+ )
+ elif engine == "xlrd":
+ from xlrd import XLRDError
+
+ error = XLRDError
+ msg = (
+ "Unsupported format, or corrupt file: Expected BOF "
+ "record; found b'foo'"
+ )
else:
error = BadZipFile
msg = "File is not a zip file"
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
index bf0a0de442ae1..2bb9ba2a397be 100644
--- a/pandas/tests/io/excel/test_xlrd.py
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -1,3 +1,5 @@
+import io
+
import pytest
from pandas.compat._optional import import_optional_dependency
@@ -8,6 +10,7 @@
from pandas.util.version import Version
from pandas.io.excel import ExcelFile
+from pandas.io.excel._base import inspect_excel_format
xlrd = pytest.importorskip("xlrd")
xlwt = pytest.importorskip("xlwt")
@@ -78,3 +81,18 @@ def test_read_excel_warning_with_xlsx_file(datapath):
else:
with tm.assert_produces_warning(None):
pd.read_excel(path, "Sheet1", engine=None)
+
+
+@pytest.mark.parametrize(
+ "file_header",
+ [
+ b"\x09\x00\x04\x00\x07\x00\x10\x00",
+ b"\x09\x02\x06\x00\x00\x00\x10\x00",
+ b"\x09\x04\x06\x00\x00\x00\x10\x00",
+ b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1",
+ ],
+)
+def test_read_old_xls_files(file_header):
+ # GH 41226
+ f = io.BytesIO(file_header)
+ assert inspect_excel_format(f) == "xls"
| - [x] closes #41225
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
Added ability to check for multiple XLS signatures according to testing files available at [Spreadsheet Project](https://www.openoffice.org/sc/testdocs/). Also defer raising an error when the engine is specified but the file signature does not match one of the values in `SIGNATURES`: this allows a user to attempt to specify and use an engine even if the passed file doesn't match one of the provided values in `SIGNATURES`.
This is my first PR for this project, so please let me know if more is expected (writing tests, writing a whatsnew entry, etc). I have run Flake8 on the code and successfully opened BIFF2 through BIFF8 files with this method. Thanks!
| https://api.github.com/repos/pandas-dev/pandas/pulls/41321 | 2021-05-04T21:04:13Z | 2021-05-21T01:44:13Z | 2021-05-21T01:44:13Z | 2021-05-21T01:47:17Z |
REF: remove no-op casting | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index f2041951b9e49..a2556ad54af02 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -59,9 +59,7 @@ class providing the base-class of operations.
doc,
)
-from pandas.core.dtypes.cast import maybe_downcast_numeric
from pandas.core.dtypes.common import (
- ensure_float,
is_bool_dtype,
is_datetime64_dtype,
is_integer_dtype,
@@ -1271,19 +1269,7 @@ def _python_agg_general(self, func, *args, **kwargs):
except TypeError:
continue
- assert result is not None
key = base.OutputKey(label=name, position=idx)
-
- if self.grouper._filter_empty_groups:
- mask = counts.ravel() > 0
-
- # since we are masking, make sure that we have a float object
- values = result
- if is_numeric_dtype(values.dtype):
- values = ensure_float(values)
-
- result = maybe_downcast_numeric(values[mask], result.dtype)
-
output[key] = result
if not output:
@@ -3035,9 +3021,7 @@ def _reindex_output(
Object (potentially) re-indexed to include all possible groups.
"""
groupings = self.grouper.groupings
- if groupings is None:
- return output
- elif len(groupings) == 1:
+ if len(groupings) == 1:
return output
# if we only care about the observed values
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 0727cad941d49..715a3008dc058 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -56,7 +56,6 @@
needs_i8_conversion,
)
from pandas.core.dtypes.dtypes import ExtensionDtype
-from pandas.core.dtypes.generic import ABCCategoricalIndex
from pandas.core.dtypes.missing import (
isna,
maybe_fill,
@@ -89,6 +88,7 @@
grouper,
)
from pandas.core.indexes.api import (
+ CategoricalIndex,
Index,
MultiIndex,
ensure_index,
@@ -676,7 +676,6 @@ def __init__(
):
assert isinstance(axis, Index), axis
- self._filter_empty_groups = self.compressed = len(groupings) != 1
self.axis = axis
self._groupings: list[grouper.Grouping] = list(groupings)
self.sort = sort
@@ -822,9 +821,7 @@ def apply(self, f: F, data: FrameOrSeries, axis: int = 0):
@cache_readonly
def indices(self):
""" dict {group name -> group indices} """
- if len(self.groupings) == 1 and isinstance(
- self.result_index, ABCCategoricalIndex
- ):
+ if len(self.groupings) == 1 and isinstance(self.result_index, CategoricalIndex):
# This shows unused categories in indices GH#38642
return self.groupings[0].indices
codes_list = [ping.codes for ping in self.groupings]
@@ -913,7 +910,7 @@ def reconstructed_codes(self) -> list[np.ndarray]:
@cache_readonly
def result_index(self) -> Index:
- if not self.compressed and len(self.groupings) == 1:
+ if len(self.groupings) == 1:
return self.groupings[0].result_index.rename(self.names[0])
codes = self.reconstructed_codes
@@ -924,7 +921,9 @@ def result_index(self) -> Index:
@final
def get_group_levels(self) -> list[Index]:
- if not self.compressed and len(self.groupings) == 1:
+ # Note: only called from _insert_inaxis_grouper_inplace, which
+ # is only called for BaseGrouper, never for BinGrouper
+ if len(self.groupings) == 1:
return [self.groupings[0].result_index]
name_list = []
@@ -1091,7 +1090,6 @@ def __init__(
):
self.bins = ensure_int64(bins)
self.binlabels = ensure_index(binlabels)
- self._filter_empty_groups = False
self.mutated = mutated
self.indexer = indexer
@@ -1201,10 +1199,9 @@ def names(self) -> list[Hashable]:
@property
def groupings(self) -> list[grouper.Grouping]:
- return [
- grouper.Grouping(lvl, lvl, in_axis=False, level=None, name=name)
- for lvl, name in zip(self.levels, self.names)
- ]
+ lev = self.binlabels
+ ping = grouper.Grouping(lev, lev, in_axis=False, level=None, name=lev.name)
+ return [ping]
def _aggregate_series_fast(
self, obj: Series, func: F
| In _python_agg_general:
```
if self.grouper._filter_empty_groups:
mask = counts.ravel() > 0
```
It isn't entirely trivial, but we can show that we will always have `mask.all()`, as a result of which the remainder of this code chunk of code is a no-op. This PR removes it.
As a consequence, we can remove `_filter_empty_groups` and `compressed`
| https://api.github.com/repos/pandas-dev/pandas/pulls/41317 | 2021-05-04T19:10:25Z | 2021-05-05T12:44:33Z | 2021-05-05T12:44:33Z | 2021-05-05T14:50:22Z |
CI: pin py310-dev version to alpha 7 | diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index 2643dc5ec656e..221501ae028f3 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -22,7 +22,7 @@ jobs:
- name: Set up Python Dev Version
uses: actions/setup-python@v2
with:
- python-version: '3.10-dev'
+ python-version: '3.10.0-alpha.7'
- name: Install dependencies
run: |
| xref #41313
Not sure if the syntax is correct. Let's see. | https://api.github.com/repos/pandas-dev/pandas/pulls/41315 | 2021-05-04T17:10:11Z | 2021-05-04T19:27:24Z | 2021-05-04T19:27:24Z | 2022-11-18T02:21:51Z |
[ArrowStringDtype] Make it already a StringDtype subclass | diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index bd01191719143..2cb30c53b6832 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -530,7 +530,6 @@ def astype(self, dtype, copy=True):
NumPy ndarray with 'dtype' for its dtype.
"""
from pandas.core.arrays.string_ import StringDtype
- from pandas.core.arrays.string_arrow import ArrowStringDtype
dtype = pandas_dtype(dtype)
if is_dtype_equal(dtype, self.dtype):
@@ -540,9 +539,8 @@ def astype(self, dtype, copy=True):
return self.copy()
# FIXME: Really hard-code here?
- if isinstance(
- dtype, (ArrowStringDtype, StringDtype)
- ): # allow conversion to StringArrays
+ if isinstance(dtype, StringDtype):
+ # allow conversion to StringArrays
return dtype.construct_array_type()._from_sequence(self, copy=False)
return np.array(self, dtype=dtype, copy=copy)
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 95c95d98bc968..a99bf245a6073 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -829,7 +829,6 @@ def astype(self, dtype, copy: bool = True):
"""
from pandas import Index
from pandas.core.arrays.string_ import StringDtype
- from pandas.core.arrays.string_arrow import ArrowStringDtype
if dtype is not None:
dtype = pandas_dtype(dtype)
@@ -852,7 +851,7 @@ def astype(self, dtype, copy: bool = True):
return self._shallow_copy(new_left, new_right)
elif is_categorical_dtype(dtype):
return Categorical(np.asarray(self), dtype=dtype)
- elif isinstance(dtype, (StringDtype, ArrowStringDtype)):
+ elif isinstance(dtype, StringDtype):
return dtype.construct_array_type()._from_sequence(self, copy=False)
# TODO: This try/except will be repeated.
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 44298401d02cb..6f23457c04dd4 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -24,7 +24,6 @@
from pandas.util._decorators import doc
from pandas.util._validators import validate_fillna_kwargs
-from pandas.core.dtypes.base import ExtensionDtype
from pandas.core.dtypes.common import (
is_array_like,
is_bool_dtype,
@@ -42,6 +41,7 @@
from pandas.core.arrays.base import ExtensionArray
from pandas.core.arrays.boolean import BooleanDtype
from pandas.core.arrays.integer import Int64Dtype
+from pandas.core.arrays.string_ import StringDtype
from pandas.core.indexers import (
check_array_indexer,
validate_indices,
@@ -74,7 +74,7 @@
@register_extension_dtype
-class ArrowStringDtype(ExtensionDtype):
+class ArrowStringDtype(StringDtype):
"""
Extension dtype for string data in a ``pyarrow.ChunkedArray``.
@@ -110,7 +110,7 @@ def type(self) -> type[str]:
return str
@classmethod
- def construct_array_type(cls) -> type_t[ArrowStringArray]:
+ def construct_array_type(cls) -> type_t[ArrowStringArray]: # type: ignore[override]
"""
Return the array type associated with this dtype.
@@ -126,7 +126,9 @@ def __hash__(self) -> int:
def __repr__(self) -> str:
return "ArrowStringDtype"
- def __from_arrow__(self, array: pa.Array | pa.ChunkedArray) -> ArrowStringArray:
+ def __from_arrow__( # type: ignore[override]
+ self, array: pa.Array | pa.ChunkedArray
+ ) -> ArrowStringArray:
"""
Construct StringArray from pyarrow Array/ChunkedArray.
"""
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index f7fa32076ec86..f8df05a7022d1 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -155,11 +155,10 @@ class StringMethods(NoNewAttributesMixin):
def __init__(self, data):
from pandas.core.arrays.string_ import StringDtype
- from pandas.core.arrays.string_arrow import ArrowStringDtype
self._inferred_dtype = self._validate(data)
self._is_categorical = is_categorical_dtype(data.dtype)
- self._is_string = isinstance(data.dtype, (StringDtype, ArrowStringDtype))
+ self._is_string = isinstance(data.dtype, StringDtype)
self._data = data
self._index = self._name = None
@@ -3028,9 +3027,8 @@ def _result_dtype(arr):
# ideally we just pass `dtype=arr.dtype` unconditionally, but this fails
# when the list of values is empty.
from pandas.core.arrays.string_ import StringDtype
- from pandas.core.arrays.string_arrow import ArrowStringDtype
- if isinstance(arr.dtype, (StringDtype, ArrowStringDtype)):
+ if isinstance(arr.dtype, StringDtype):
return arr.dtype.name
else:
return object
diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py
index ffe2769730f34..2eef828288e59 100644
--- a/pandas/tests/extension/json/array.py
+++ b/pandas/tests/extension/json/array.py
@@ -40,7 +40,6 @@
ExtensionDtype,
)
from pandas.api.types import is_bool_dtype
-from pandas.core.arrays.string_arrow import ArrowStringDtype
class JSONDtype(ExtensionDtype):
@@ -196,7 +195,7 @@ def astype(self, dtype, copy=True):
if copy:
return self.copy()
return self
- elif isinstance(dtype, (StringDtype, ArrowStringDtype)):
+ elif isinstance(dtype, StringDtype):
value = self.astype(str) # numpy doesn'y like nested dicts
return dtype.construct_array_type()._from_sequence(value, copy=False)
| @simonjayhawkins this will be redundant after https://github.com/pandas-dev/pandas/pull/39908, but in the meantime, ArrowStringDtype being a subclass would help for writing robust code related to `StringDtype` in downstream packages (for those testing against pandas master) | https://api.github.com/repos/pandas-dev/pandas/pulls/41312 | 2021-05-04T16:36:23Z | 2021-05-05T06:55:49Z | 2021-05-05T06:55:49Z | 2021-05-05T06:55:53Z |
CI: skip tests when only files in doc/web changes (github actions) | diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml
index b15889351386a..292598dfcab73 100644
--- a/.github/workflows/database.yml
+++ b/.github/workflows/database.yml
@@ -7,6 +7,8 @@ on:
branches:
- master
- 1.2.x
+ paths-ignore:
+ - "doc/**"
env:
PYTEST_WORKERS: "auto"
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index 3a4d3c106f851..cb7d3fb5cabcf 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -7,6 +7,8 @@ on:
branches:
- master
- 1.2.x
+ paths-ignore:
+ - "doc/**"
env:
PYTEST_WORKERS: "auto"
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index 2643dc5ec656e..38b1aa9ae7047 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -7,6 +7,8 @@ on:
pull_request:
branches:
- master
+ paths-ignore:
+ - "doc/**"
jobs:
build:
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 56da4e87f2709..956feaef5f83e 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -1,7 +1,12 @@
# Adapted from https://github.com/numba/numba/blob/master/azure-pipelines.yml
trigger:
-- master
-- 1.2.x
+ branches:
+ include:
+ - master
+ - 1.2.x
+ paths:
+ exclude:
+ - 'doc/*'
pr:
- master
| - [x] closes #41101
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/41310 | 2021-05-04T16:04:48Z | 2021-06-12T09:43:18Z | 2021-06-12T09:43:18Z | 2021-08-26T13:44:50Z |
REF: share GroupBy.transform | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 89623d260af71..f5274f0998e7c 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -526,35 +526,9 @@ def _aggregate_named(self, func, *args, **kwargs):
@Substitution(klass="Series")
@Appender(_transform_template)
def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
-
- if maybe_use_numba(engine):
- with group_selection_context(self):
- data = self._selected_obj
- result = self._transform_with_numba(
- data.to_frame(), func, *args, engine_kwargs=engine_kwargs, **kwargs
- )
- return self.obj._constructor(
- result.ravel(), index=data.index, name=data.name
- )
-
- func = com.get_cython_func(func) or func
-
- if not isinstance(func, str):
- return self._transform_general(func, *args, **kwargs)
-
- elif func not in base.transform_kernel_allowlist:
- msg = f"'{func}' is not a valid function name for transform(name)"
- raise ValueError(msg)
- elif func in base.cythonized_kernels or func in base.transformation_kernels:
- # cythonized transform or canned "agg+broadcast"
- return getattr(self, func)(*args, **kwargs)
- # If func is a reduction, we need to broadcast the
- # result to the whole group. Compute func result
- # and deal with possible broadcasting below.
- # Temporarily set observed for dealing with categoricals.
- with com.temp_setattr(self, "observed", True):
- result = getattr(self, func)(*args, **kwargs)
- return self._wrap_transform_fast_result(result)
+ return self._transform(
+ func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs
+ )
def _transform_general(self, func: Callable, *args, **kwargs) -> Series:
"""
@@ -586,6 +560,9 @@ def _transform_general(self, func: Callable, *args, **kwargs) -> Series:
result.name = self._selected_obj.name
return result
+ def _can_use_transform_fast(self, result) -> bool:
+ return True
+
def _wrap_transform_fast_result(self, result: Series) -> Series:
"""
fast version of transform, only applicable to
@@ -1334,43 +1311,14 @@ def _transform_general(self, func, *args, **kwargs):
@Substitution(klass="DataFrame")
@Appender(_transform_template)
def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
+ return self._transform(
+ func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs
+ )
- if maybe_use_numba(engine):
- with group_selection_context(self):
- data = self._selected_obj
- result = self._transform_with_numba(
- data, func, *args, engine_kwargs=engine_kwargs, **kwargs
- )
- return self.obj._constructor(result, index=data.index, columns=data.columns)
-
- # optimized transforms
- func = com.get_cython_func(func) or func
-
- if not isinstance(func, str):
- return self._transform_general(func, *args, **kwargs)
-
- elif func not in base.transform_kernel_allowlist:
- msg = f"'{func}' is not a valid function name for transform(name)"
- raise ValueError(msg)
- elif func in base.cythonized_kernels or func in base.transformation_kernels:
- # cythonized transformation or canned "reduction+broadcast"
- return getattr(self, func)(*args, **kwargs)
- # GH 30918
- # Use _transform_fast only when we know func is an aggregation
- if func in base.reduction_kernels:
- # If func is a reduction, we need to broadcast the
- # result to the whole group. Compute func result
- # and deal with possible broadcasting below.
- # Temporarily set observed for dealing with categoricals.
- with com.temp_setattr(self, "observed", True):
- result = getattr(self, func)(*args, **kwargs)
-
- if isinstance(result, DataFrame) and result.columns.equals(
- self._obj_with_exclusions.columns
- ):
- return self._wrap_transform_fast_result(result)
-
- return self._transform_general(func, *args, **kwargs)
+ def _can_use_transform_fast(self, result) -> bool:
+ return isinstance(result, DataFrame) and result.columns.equals(
+ self._obj_with_exclusions.columns
+ )
def _wrap_transform_fast_result(self, result: DataFrame) -> DataFrame:
"""
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index f2041951b9e49..7a8b41fbdf141 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -29,6 +29,7 @@ class providing the base-class of operations.
Sequence,
TypeVar,
Union,
+ cast,
)
import numpy as np
@@ -104,7 +105,10 @@ class providing the base-class of operations.
from pandas.core.internals.blocks import ensure_block_shape
from pandas.core.series import Series
from pandas.core.sorting import get_group_index_sorter
-from pandas.core.util.numba_ import NUMBA_FUNC_CACHE
+from pandas.core.util.numba_ import (
+ NUMBA_FUNC_CACHE,
+ maybe_use_numba,
+)
if TYPE_CHECKING:
from typing import Literal
@@ -1398,8 +1402,55 @@ def _cython_transform(
return self._wrap_transformed_output(output)
- def transform(self, func, *args, **kwargs):
- raise AbstractMethodError(self)
+ @final
+ def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
+
+ if maybe_use_numba(engine):
+ # TODO: tests with self._selected_obj.ndim == 1 on DataFrameGroupBy
+ with group_selection_context(self):
+ data = self._selected_obj
+ df = data if data.ndim == 2 else data.to_frame()
+ result = self._transform_with_numba(
+ df, func, *args, engine_kwargs=engine_kwargs, **kwargs
+ )
+ if self.obj.ndim == 2:
+ return cast(DataFrame, self.obj)._constructor(
+ result, index=data.index, columns=data.columns
+ )
+ else:
+ return cast(Series, self.obj)._constructor(
+ result.ravel(), index=data.index, name=data.name
+ )
+
+ # optimized transforms
+ func = com.get_cython_func(func) or func
+
+ if not isinstance(func, str):
+ return self._transform_general(func, *args, **kwargs)
+
+ elif func not in base.transform_kernel_allowlist:
+ msg = f"'{func}' is not a valid function name for transform(name)"
+ raise ValueError(msg)
+ elif func in base.cythonized_kernels or func in base.transformation_kernels:
+ # cythonized transform or canned "agg+broadcast"
+ return getattr(self, func)(*args, **kwargs)
+
+ else:
+ # i.e. func in base.reduction_kernels
+
+ # GH#30918 Use _transform_fast only when we know func is an aggregation
+ # If func is a reduction, we need to broadcast the
+ # result to the whole group. Compute func result
+ # and deal with possible broadcasting below.
+ # Temporarily set observed for dealing with categoricals.
+ with com.temp_setattr(self, "observed", True):
+ result = getattr(self, func)(*args, **kwargs)
+
+ if self._can_use_transform_fast(result):
+ return self._wrap_transform_fast_result(result)
+
+ # only reached for DataFrameGroupBy
+ return self._transform_general(func, *args, **kwargs)
# -----------------------------------------------------------------
# Utilities
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41308 | 2021-05-04T14:55:12Z | 2021-05-04T21:36:53Z | 2021-05-04T21:36:53Z | 2021-05-04T21:55:23Z |
Deprecate inplace in Categorical.set_categories. | diff --git a/doc/source/user_guide/categorical.rst b/doc/source/user_guide/categorical.rst
index fba41f73ba819..f65638cd78a2b 100644
--- a/doc/source/user_guide/categorical.rst
+++ b/doc/source/user_guide/categorical.rst
@@ -954,6 +954,7 @@ categorical (categories and ordering). So if you read back the CSV file you have
relevant columns back to ``category`` and assign the right categories and categories ordering.
.. ipython:: python
+ :okwarning:
import io
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 61bea198e42db..320912ec38890 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -639,7 +639,7 @@ Deprecations
- Deprecated using :func:`merge` or :func:`join` on a different number of levels (:issue:`34862`)
- Deprecated the use of ``**kwargs`` in :class:`.ExcelWriter`; use the keyword argument ``engine_kwargs`` instead (:issue:`40430`)
- Deprecated the ``level`` keyword for :class:`DataFrame` and :class:`Series` aggregations; use groupby instead (:issue:`39983`)
-- The ``inplace`` parameter of :meth:`Categorical.remove_categories`, :meth:`Categorical.add_categories`, :meth:`Categorical.reorder_categories`, :meth:`Categorical.rename_categories` is deprecated and will be removed in a future version (:issue:`37643`)
+- The ``inplace`` parameter of :meth:`Categorical.remove_categories`, :meth:`Categorical.add_categories`, :meth:`Categorical.reorder_categories`, :meth:`Categorical.rename_categories`, :meth:`Categorical.set_categories` is deprecated and will be removed in a future version (:issue:`37643`)
- Deprecated :func:`merge` producing duplicated columns through the ``suffixes`` keyword and already existing columns (:issue:`22818`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 7cddfef3d4292..7b653bf84a466 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -882,7 +882,9 @@ def as_unordered(self, inplace=False):
inplace = validate_bool_kwarg(inplace, "inplace")
return self.set_ordered(False, inplace=inplace)
- def set_categories(self, new_categories, ordered=None, rename=False, inplace=False):
+ def set_categories(
+ self, new_categories, ordered=None, rename=False, inplace=no_default
+ ):
"""
Set the categories to the specified new_categories.
@@ -916,6 +918,8 @@ def set_categories(self, new_categories, ordered=None, rename=False, inplace=Fal
Whether or not to reorder the categories in-place or return a copy
of this categorical with reordered categories.
+ .. deprecated:: 1.3.0
+
Returns
-------
Categorical with reordered categories or None if inplace.
@@ -933,6 +937,18 @@ def set_categories(self, new_categories, ordered=None, rename=False, inplace=Fal
remove_categories : Remove the specified categories.
remove_unused_categories : Remove categories which are not used.
"""
+ if inplace is not no_default:
+ warn(
+ "The `inplace` parameter in pandas.Categorical."
+ "set_categories is deprecated and will be removed in "
+ "a future version. Removing unused categories will always "
+ "return a new Categorical object.",
+ FutureWarning,
+ stacklevel=2,
+ )
+ else:
+ inplace = False
+
inplace = validate_bool_kwarg(inplace, "inplace")
if ordered is None:
ordered = self.dtype.ordered
@@ -1101,7 +1117,10 @@ def reorder_categories(self, new_categories, ordered=None, inplace=no_default):
raise ValueError(
"items in new_categories are not the same as in old categories"
)
- return self.set_categories(new_categories, ordered=ordered, inplace=inplace)
+
+ with catch_warnings():
+ simplefilter("ignore")
+ return self.set_categories(new_categories, ordered=ordered, inplace=inplace)
def add_categories(self, new_categories, inplace=no_default):
"""
@@ -1231,9 +1250,11 @@ def remove_categories(self, removals, inplace=no_default):
if len(not_included) != 0:
raise ValueError(f"removals must all be in old categories: {not_included}")
- return self.set_categories(
- new_categories, ordered=self.ordered, rename=False, inplace=inplace
- )
+ with catch_warnings():
+ simplefilter("ignore")
+ return self.set_categories(
+ new_categories, ordered=self.ordered, rename=False, inplace=inplace
+ )
def remove_unused_categories(self, inplace=no_default):
"""
diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py
index 7bb86987456f1..c0287df1694e9 100644
--- a/pandas/tests/arrays/categorical/test_analytics.py
+++ b/pandas/tests/arrays/categorical/test_analytics.py
@@ -314,7 +314,9 @@ def test_validate_inplace_raises(self, value):
cat.as_unordered(inplace=value)
with pytest.raises(ValueError, match=msg):
- cat.set_categories(["X", "Y", "Z"], rename=True, inplace=value)
+ with tm.assert_produces_warning(FutureWarning):
+ # issue #37643 inplace kwarg deprecated
+ cat.set_categories(["X", "Y", "Z"], rename=True, inplace=value)
with pytest.raises(ValueError, match=msg):
with tm.assert_produces_warning(FutureWarning):
diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py
index 10e29dc82c050..a063491cd08fa 100644
--- a/pandas/tests/arrays/categorical/test_api.py
+++ b/pandas/tests/arrays/categorical/test_api.py
@@ -229,7 +229,10 @@ def test_set_categories(self):
exp_categories = Index(["c", "b", "a"])
exp_values = np.array(["a", "b", "c", "a"], dtype=np.object_)
- res = cat.set_categories(["c", "b", "a"], inplace=True)
+ with tm.assert_produces_warning(FutureWarning):
+ # issue #37643 inplace kwarg deprecated
+ res = cat.set_categories(["c", "b", "a"], inplace=True)
+
tm.assert_index_equal(cat.categories, exp_categories)
tm.assert_numpy_array_equal(cat.__array__(), exp_values)
assert res is None
@@ -439,7 +442,11 @@ def test_describe(self):
# check unused categories
cat = self.factor.copy()
- cat.set_categories(["a", "b", "c", "d"], inplace=True)
+
+ with tm.assert_produces_warning(FutureWarning):
+ # issue #37643 inplace kwarg deprecated
+ cat.set_categories(["a", "b", "c", "d"], inplace=True)
+
desc = cat.describe()
exp_index = CategoricalIndex(
@@ -475,7 +482,11 @@ def test_describe(self):
def test_set_categories_inplace(self):
cat = self.factor.copy()
- cat.set_categories(["a", "b", "c", "d"], inplace=True)
+
+ with tm.assert_produces_warning(FutureWarning):
+ # issue #37643 inplace kwarg deprecated
+ cat.set_categories(["a", "b", "c", "d"], inplace=True)
+
tm.assert_index_equal(cat.categories, Index(["a", "b", "c", "d"]))
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 4004e595c832f..204c7648ac2f7 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -887,9 +887,11 @@ def test_setitem_mask_categorical(self):
df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf)
exp_fancy = exp_multi_row.copy()
- return_value = exp_fancy["cats"].cat.set_categories(
- ["a", "b", "c"], inplace=True
- )
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ # issue #37643 inplace kwarg deprecated
+ return_value = exp_fancy["cats"].cat.set_categories(
+ ["a", "b", "c"], inplace=True
+ )
assert return_value is None
mask = df["cats"] == "c"
diff --git a/pandas/tests/series/accessors/test_cat_accessor.py b/pandas/tests/series/accessors/test_cat_accessor.py
index 8a4c4d56e264d..7aea45755f940 100644
--- a/pandas/tests/series/accessors/test_cat_accessor.py
+++ b/pandas/tests/series/accessors/test_cat_accessor.py
@@ -48,7 +48,11 @@ def test_cat_accessor(self):
assert not ser.cat.ordered, False
exp = Categorical(["a", "b", np.nan, "a"], categories=["b", "a"])
- return_value = ser.cat.set_categories(["b", "a"], inplace=True)
+
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ # issue #37643 inplace kwarg deprecated
+ return_value = ser.cat.set_categories(["b", "a"], inplace=True)
+
assert return_value is None
tm.assert_categorical_equal(ser.values, exp)
| - [x] xref #37643
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41307 | 2021-05-04T14:33:56Z | 2021-05-04T19:40:36Z | 2021-05-04T19:40:36Z | 2021-05-04T19:40:41Z |
[ArrowStringArray] CLN: assorted cleanup | diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 72a2ab8a1b80a..501484a98ded3 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -8,7 +8,6 @@
Sequence,
cast,
)
-import warnings
import numpy as np
@@ -766,20 +765,13 @@ def _str_map(self, f, na_value=None, dtype: Dtype | None = None):
# -> We don't know the result type. E.g. `.get` can return anything.
return lib.map_infer_mask(arr, f, mask.view("uint8"))
- def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex=True):
+ def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex: bool = True):
if flags:
return super()._str_contains(pat, case, flags, na, regex)
if regex:
# match_substring_regex added in pyarrow 4.0.0
if hasattr(pc, "match_substring_regex") and case:
- if re.compile(pat).groups:
- warnings.warn(
- "This pattern has match groups. To actually get the "
- "groups, use str.extract.",
- UserWarning,
- stacklevel=3,
- )
result = pc.match_substring_regex(self._data, pat)
else:
return super()._str_contains(pat, case, flags, na, regex)
@@ -816,48 +808,31 @@ def _str_endswith(self, pat, na=None):
return super()._str_endswith(pat, na)
def _str_isalnum(self):
- if hasattr(pc, "utf8_is_alnum"):
- result = pc.utf8_is_alnum(self._data)
- return BooleanDtype().__from_arrow__(result)
- else:
- return super()._str_isalnum()
+ result = pc.utf8_is_alnum(self._data)
+ return BooleanDtype().__from_arrow__(result)
def _str_isalpha(self):
- if hasattr(pc, "utf8_is_alpha"):
- result = pc.utf8_is_alpha(self._data)
- return BooleanDtype().__from_arrow__(result)
- else:
- return super()._str_isalpha()
+ result = pc.utf8_is_alpha(self._data)
+ return BooleanDtype().__from_arrow__(result)
def _str_isdecimal(self):
- if hasattr(pc, "utf8_is_decimal"):
- result = pc.utf8_is_decimal(self._data)
- return BooleanDtype().__from_arrow__(result)
- else:
- return super()._str_isdecimal()
+ result = pc.utf8_is_decimal(self._data)
+ return BooleanDtype().__from_arrow__(result)
def _str_isdigit(self):
- if hasattr(pc, "utf8_is_digit"):
- result = pc.utf8_is_digit(self._data)
- return BooleanDtype().__from_arrow__(result)
- else:
- return super()._str_isdigit()
+ result = pc.utf8_is_digit(self._data)
+ return BooleanDtype().__from_arrow__(result)
def _str_islower(self):
- if hasattr(pc, "utf8_is_lower"):
- result = pc.utf8_is_lower(self._data)
- return BooleanDtype().__from_arrow__(result)
- else:
- return super()._str_islower()
+ result = pc.utf8_is_lower(self._data)
+ return BooleanDtype().__from_arrow__(result)
def _str_isnumeric(self):
- if hasattr(pc, "utf8_is_numeric"):
- result = pc.utf8_is_numeric(self._data)
- return BooleanDtype().__from_arrow__(result)
- else:
- return super()._str_isnumeric()
+ result = pc.utf8_is_numeric(self._data)
+ return BooleanDtype().__from_arrow__(result)
def _str_isspace(self):
+ # utf8_is_space added in pyarrow 2.0.0
if hasattr(pc, "utf8_is_space"):
result = pc.utf8_is_space(self._data)
return BooleanDtype().__from_arrow__(result)
@@ -865,18 +840,12 @@ def _str_isspace(self):
return super()._str_isspace()
def _str_istitle(self):
- if hasattr(pc, "utf8_is_title"):
- result = pc.utf8_is_title(self._data)
- return BooleanDtype().__from_arrow__(result)
- else:
- return super()._str_istitle()
+ result = pc.utf8_is_title(self._data)
+ return BooleanDtype().__from_arrow__(result)
def _str_isupper(self):
- if hasattr(pc, "utf8_is_upper"):
- result = pc.utf8_is_upper(self._data)
- return BooleanDtype().__from_arrow__(result)
- else:
- return super()._str_isupper()
+ result = pc.utf8_is_upper(self._data)
+ return BooleanDtype().__from_arrow__(result)
def _str_lower(self):
return type(self)(pc.utf8_lower(self._data))
@@ -886,27 +855,33 @@ def _str_upper(self):
def _str_strip(self, to_strip=None):
if to_strip is None:
+ # utf8_trim_whitespace added in pyarrow 4.0.0
if hasattr(pc, "utf8_trim_whitespace"):
return type(self)(pc.utf8_trim_whitespace(self._data))
else:
+ # utf8_trim added in pyarrow 4.0.0
if hasattr(pc, "utf8_trim"):
return type(self)(pc.utf8_trim(self._data, characters=to_strip))
return super()._str_strip(to_strip)
def _str_lstrip(self, to_strip=None):
if to_strip is None:
+ # utf8_ltrim_whitespace added in pyarrow 4.0.0
if hasattr(pc, "utf8_ltrim_whitespace"):
return type(self)(pc.utf8_ltrim_whitespace(self._data))
else:
+ # utf8_ltrim added in pyarrow 4.0.0
if hasattr(pc, "utf8_ltrim"):
return type(self)(pc.utf8_ltrim(self._data, characters=to_strip))
return super()._str_lstrip(to_strip)
def _str_rstrip(self, to_strip=None):
if to_strip is None:
+ # utf8_rtrim_whitespace added in pyarrow 4.0.0
if hasattr(pc, "utf8_rtrim_whitespace"):
return type(self)(pc.utf8_rtrim_whitespace(self._data))
else:
+ # utf8_rtrim added in pyarrow 4.0.0
if hasattr(pc, "utf8_rtrim"):
return type(self)(pc.utf8_rtrim(self._data, characters=to_strip))
return super()._str_rstrip(to_strip)
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 85a58d3d99795..8f971eb33f1dc 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -195,8 +195,6 @@ def _validate(data):
-------
dtype : inferred dtype of data
"""
- from pandas import StringDtype
-
if isinstance(data, ABCMultiIndex):
raise AttributeError(
"Can only use .str accessor with Index, not MultiIndex"
@@ -208,10 +206,6 @@ def _validate(data):
values = getattr(data, "values", data) # Series / Index
values = getattr(values, "categories", values) # categorical / normal
- # explicitly allow StringDtype
- if isinstance(values.dtype, StringDtype):
- return "string"
-
inferred_dtype = lib.infer_dtype(values, skipna=True)
if inferred_dtype not in allowed_types:
@@ -1132,6 +1126,14 @@ def contains(self, pat, case=True, flags=0, na=None, regex=True):
4 False
dtype: bool
"""
+ if regex and re.compile(pat).groups:
+ warnings.warn(
+ "This pattern has match groups. To actually get the "
+ "groups, use str.extract.",
+ UserWarning,
+ stacklevel=3,
+ )
+
result = self._data.array._str_contains(pat, case, flags, na, regex)
return self._wrap_result(result, fill_value=na, returns_string=False)
diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py
index b794690ccc5af..a47a6d49a4ba1 100644
--- a/pandas/core/strings/object_array.py
+++ b/pandas/core/strings/object_array.py
@@ -7,7 +7,6 @@
Union,
)
import unicodedata
-import warnings
import numpy as np
@@ -115,22 +114,14 @@ def _str_pad(self, width, side="left", fillchar=" "):
raise ValueError("Invalid side")
return self._str_map(f)
- def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex=True):
+ def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex: bool = True):
if regex:
if not case:
flags |= re.IGNORECASE
- regex = re.compile(pat, flags=flags)
+ pat = re.compile(pat, flags=flags)
- if regex.groups > 0:
- warnings.warn(
- "This pattern has match groups. To actually get the "
- "groups, use str.extract.",
- UserWarning,
- stacklevel=3,
- )
-
- f = lambda x: regex.search(x) is not None
+ f = lambda x: pat.search(x) is not None
else:
if case:
f = lambda x: pat in x
diff --git a/pandas/tests/strings/conftest.py b/pandas/tests/strings/conftest.py
index 4fedbee91f649..17703d970e29e 100644
--- a/pandas/tests/strings/conftest.py
+++ b/pandas/tests/strings/conftest.py
@@ -1,6 +1,8 @@
import numpy as np
import pytest
+import pandas.util._test_decorators as td
+
from pandas import Series
from pandas.core import strings as strings
@@ -173,3 +175,24 @@ def any_allowed_skipna_inferred_dtype(request):
# correctness of inference tested in tests/dtypes/test_inference.py
return inferred_dtype, values
+
+
+@pytest.fixture(
+ params=[
+ "object",
+ "string",
+ pytest.param(
+ "arrow_string", marks=td.skip_if_no("pyarrow", min_version="1.0.0")
+ ),
+ ]
+)
+def any_string_dtype(request):
+ """
+ Parametrized fixture for string dtypes.
+ * 'object'
+ * 'string'
+ * 'arrow_string'
+ """
+ from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
+
+ return request.param
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index 0c54042d983ad..b547af6b4cedd 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -4,8 +4,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
import pandas as pd
from pandas import (
Index,
@@ -14,27 +12,6 @@
)
-@pytest.fixture(
- params=[
- "object",
- "string",
- pytest.param(
- "arrow_string", marks=td.skip_if_no("pyarrow", min_version="1.0.0")
- ),
- ]
-)
-def any_string_dtype(request):
- """
- Parametrized fixture for string dtypes.
- * 'object'
- * 'string'
- * 'arrow_string'
- """
- from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
-
- return request.param
-
-
def test_contains(any_string_dtype):
values = np.array(
["foo", np.nan, "fooommm__foo", "mmm_", "foommm[_]+bar"], dtype=np.object_
@@ -751,6 +728,7 @@ def test_flags_kwarg(any_string_dtype):
result = data.str.count(pat, flags=re.IGNORECASE)
assert result[0] == 1
- with tm.assert_produces_warning(UserWarning):
+ msg = "This pattern has match groups"
+ with tm.assert_produces_warning(UserWarning, match=msg):
result = data.str.contains(pat, flags=re.IGNORECASE)
assert result[0]
diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py
index f218d5333b415..38e714a7bc5c7 100644
--- a/pandas/tests/strings/test_strings.py
+++ b/pandas/tests/strings/test_strings.py
@@ -6,8 +6,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas import (
DataFrame,
Index,
@@ -19,27 +17,6 @@
import pandas._testing as tm
-@pytest.fixture(
- params=[
- "object",
- "string",
- pytest.param(
- "arrow_string", marks=td.skip_if_no("pyarrow", min_version="1.0.0")
- ),
- ]
-)
-def any_string_dtype(request):
- """
- Parametrized fixture for string dtypes.
- * 'object'
- * 'string'
- * 'arrow_string'
- """
- from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
-
- return request.param
-
-
def assert_series_or_index_equal(left, right):
if isinstance(left, Series):
tm.assert_series_equal(left, right)
| seperate commits for cleanups
remove hasattr for str methods available in pyarrow 1.0.0
add comments to indicate pyarrow version a method is addded.
de-duplicate fixture
de-duplicate warning from str.contains with pattern with capture groups
remove special casing StringDtype | https://api.github.com/repos/pandas-dev/pandas/pulls/41306 | 2021-05-04T12:27:42Z | 2021-05-04T16:37:46Z | 2021-05-04T16:37:46Z | 2021-05-04T17:58:37Z |
ASV: add benchmarks to test formatting func in Styler. | diff --git a/asv_bench/benchmarks/io/style.py b/asv_bench/benchmarks/io/style.py
index e4369d67ca67e..a01610a69278b 100644
--- a/asv_bench/benchmarks/io/style.py
+++ b/asv_bench/benchmarks/io/style.py
@@ -1,6 +1,9 @@
import numpy as np
-from pandas import DataFrame
+from pandas import (
+ DataFrame,
+ IndexSlice,
+)
class Render:
@@ -31,6 +34,14 @@ def peakmem_classes_render(self, cols, rows):
self._style_classes()
self.st._render_html()
+ def time_format_render(self, cols, rows):
+ self._style_format()
+ self.st.render()
+
+ def peakmem_format_render(self, cols, rows):
+ self._style_format()
+ self.st.render()
+
def _style_apply(self):
def _apply_func(s):
return [
@@ -43,3 +54,12 @@ def _style_classes(self):
classes = self.df.applymap(lambda v: ("cls-1" if v > 0 else ""))
classes.index, classes.columns = self.df.index, self.df.columns
self.st = self.df.style.set_td_classes(classes)
+
+ def _style_format(self):
+ ic = int(len(self.df.columns) / 4 * 3)
+ ir = int(len(self.df.index) / 4 * 3)
+ # apply a formatting function
+ # subset is flexible but hinders vectorised solutions
+ self.st = self.df.style.format(
+ "{:,.3f}", subset=IndexSlice["row_1":f"row_{ir}", "float_1":f"float_{ic}"]
+ )
| The main time in rendering Styler is consumed by:
- formatting values for display
- adding cell styles via apply / applymap
- adding cell styles via set_td_classes
We have benchmarks for the latter 2 but not the first. Any future changes to the formatting function might be worth having benchmarks (I would use them :) )
Especially if we try to merge Styler formatting with the floatformatter for example.
| https://api.github.com/repos/pandas-dev/pandas/pulls/41302 | 2021-05-04T10:43:44Z | 2021-05-04T12:44:09Z | 2021-05-04T12:44:09Z | 2021-05-06T07:35:51Z |
COMPAT: frame round error msg for py310 | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 6d3042507d930..d1ff69f16d993 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -9206,9 +9206,12 @@ def _series_round(s, decimals):
nv.validate_round(args, kwargs)
if isinstance(decimals, (dict, Series)):
- if isinstance(decimals, Series):
- if not decimals.index.is_unique:
- raise ValueError("Index of decimals must be unique")
+ if isinstance(decimals, Series) and not decimals.index.is_unique:
+ raise ValueError("Index of decimals must be unique")
+ if is_dict_like(decimals) and not all(
+ is_integer(value) for _, value in decimals.items()
+ ):
+ raise TypeError("Values in decimals must be integers")
new_cols = list(_dict_round(self, decimals))
elif is_integer(decimals):
# Dispatch to Series.round
diff --git a/pandas/tests/frame/methods/test_round.py b/pandas/tests/frame/methods/test_round.py
index ebe33922be541..dd9206940bcd6 100644
--- a/pandas/tests/frame/methods/test_round.py
+++ b/pandas/tests/frame/methods/test_round.py
@@ -62,13 +62,12 @@ def test_round(self):
# float input to `decimals`
non_int_round_dict = {"col1": 1, "col2": 0.5}
- msg = "integer argument expected, got float"
+ msg = "Values in decimals must be integers"
with pytest.raises(TypeError, match=msg):
df.round(non_int_round_dict)
# String input
non_int_round_dict = {"col1": 1, "col2": "foo"}
- msg = r"an integer is required \(got type str\)"
with pytest.raises(TypeError, match=msg):
df.round(non_int_round_dict)
@@ -78,7 +77,6 @@ def test_round(self):
# List input
non_int_round_dict = {"col1": 1, "col2": [1, 2]}
- msg = r"an integer is required \(got type list\)"
with pytest.raises(TypeError, match=msg):
df.round(non_int_round_dict)
@@ -106,7 +104,6 @@ def test_round(self):
# nan in Series round
nan_round_Series = Series({"col1": np.nan, "col2": 1})
- msg = "integer argument expected, got float"
with pytest.raises(TypeError, match=msg):
df.round(nan_round_Series)
| Not sure if this is the desired way to address this.
```
________________________ TestDataFrameRound.test_round _________________________
self = <pandas.tests.frame.methods.test_round.TestDataFrameRound object at 0x7fcdd089eb90>
def test_round(self):
# GH#2665
# Test that rounding an empty DataFrame does nothing
df = DataFrame()
tm.assert_frame_equal(df, df.round())
# Here's the test frame we'll be working with
df = DataFrame({"col1": [1.123, 2.123, 3.123], "col2": [1.234, 2.234, 3.234]})
# Default round to integer (i.e. decimals=0)
expected_rounded = DataFrame({"col1": [1.0, 2.0, 3.0], "col2": [1.0, 2.0, 3.0]})
tm.assert_frame_equal(df.round(), expected_rounded)
# Round with an integer
decimals = 2
expected_rounded = DataFrame(
{"col1": [1.12, 2.12, 3.12], "col2": [1.23, 2.23, 3.23]}
)
tm.assert_frame_equal(df.round(decimals), expected_rounded)
# This should also work with np.round (since np.round dispatches to
# df.round)
tm.assert_frame_equal(np.round(df, decimals), expected_rounded)
# Round with a list
round_list = [1, 2]
msg = "decimals must be an integer, a dict-like or a Series"
with pytest.raises(TypeError, match=msg):
df.round(round_list)
# Round with a dictionary
expected_rounded = DataFrame(
{"col1": [1.1, 2.1, 3.1], "col2": [1.23, 2.23, 3.23]}
)
round_dict = {"col1": 1, "col2": 2}
tm.assert_frame_equal(df.round(round_dict), expected_rounded)
# Incomplete dict
expected_partially_rounded = DataFrame(
{"col1": [1.123, 2.123, 3.123], "col2": [1.2, 2.2, 3.2]}
)
partial_round_dict = {"col2": 1}
tm.assert_frame_equal(df.round(partial_round_dict), expected_partially_rounded)
# Dict with unknown elements
wrong_round_dict = {"col3": 2, "col2": 1}
tm.assert_frame_equal(df.round(wrong_round_dict), expected_partially_rounded)
# float input to `decimals`
non_int_round_dict = {"col1": 1, "col2": 0.5}
msg = "integer argument expected, got float"
with pytest.raises(TypeError, match=msg):
> df.round(non_int_round_dict)
pandas/tests/frame/methods/test_round.py:67:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = col1 col2
0 1.123 1.234
1 2.123 2.234
2 3.123 3.234
decimals = {'col1': 1, 'col2': 0.5}, args = (), kwargs = {}
concat = <function concat at 0x7fce2c668e50>
_dict_round = <function DataFrame.round.<locals>._dict_round at 0x7fcdd13728c0>
def round(
self, decimals: int | dict[IndexLabel, int] | Series = 0, *args, **kwargs
) -> DataFrame:
"""
Round a DataFrame to a variable number of decimal places.
Parameters
----------
decimals : int, dict, Series
Number of decimal places to round each column to. If an int is
given, round each column to the same number of places.
Otherwise dict and Series round to variable numbers of places.
Column names should be in the keys if `decimals` is a
dict-like, or in the index if `decimals` is a Series. Any
columns not included in `decimals` will be left as is. Elements
of `decimals` which are not columns of the input will be
ignored.
*args
Additional keywords have no effect but might be accepted for
compatibility with numpy.
**kwargs
Additional keywords have no effect but might be accepted for
compatibility with numpy.
Returns
-------
DataFrame
A DataFrame with the affected columns rounded to the specified
number of decimal places.
See Also
--------
numpy.around : Round a numpy array to the given number of decimals.
Series.round : Round a Series to the given number of decimals.
Examples
--------
>>> df = pd.DataFrame([(.21, .32), (.01, .67), (.66, .03), (.21, .18)],
... columns=['dogs', 'cats'])
>>> df
dogs cats
0 0.21 0.32
1 0.01 0.67
2 0.66 0.03
3 0.21 0.18
By providing an integer each column is rounded to the same number
of decimal places
>>> df.round(1)
dogs cats
0 0.2 0.3
1 0.0 0.7
2 0.7 0.0
3 0.2 0.2
With a dict, the number of places for specific columns can be
specified with the column names as key and the number of decimal
places as value
>>> df.round({'dogs': 1, 'cats': 0})
dogs cats
0 0.2 0.0
1 0.0 1.0
2 0.7 0.0
3 0.2 0.0
Using a Series, the number of places for specific columns can be
specified with the column names as index and the number of
decimal places as value
>>> decimals = pd.Series([0, 1], index=['cats', 'dogs'])
>>> df.round(decimals)
dogs cats
0 0.2 0.0
1 0.0 1.0
2 0.7 0.0
3 0.2 0.0
"""
from pandas.core.reshape.concat import concat
def _dict_round(df, decimals):
for col, vals in df.items():
try:
yield _series_round(vals, decimals[col])
except KeyError:
yield vals
def _series_round(s, decimals):
if is_integer_dtype(s) or is_float_dtype(s):
return s.round(decimals)
return s
nv.validate_round(args, kwargs)
if isinstance(decimals, (dict, Series)):
if isinstance(decimals, Series):
if not decimals.index.is_unique:
raise ValueError("Index of decimals must be unique")
> new_cols = list(_dict_round(self, decimals))
pandas/core/frame.py:9205:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
df = col1 col2
0 1.123 1.234
1 2.123 2.234
2 3.123 3.234
decimals = {'col1': 1, 'col2': 0.5}
def _dict_round(df, decimals):
for col, vals in df.items():
try:
> yield _series_round(vals, decimals[col])
pandas/core/frame.py:9190:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
s = 0 1.234
1 2.234
2 3.234
Name: col2, dtype: float64, decimals = 0.5
def _series_round(s, decimals):
if is_integer_dtype(s) or is_float_dtype(s):
> return s.round(decimals)
pandas/core/frame.py:9196:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = 0 1.234
1 2.234
2 3.234
Name: col2, dtype: float64
decimals = 0.5, args = (), kwargs = {}
def round(self, decimals=0, *args, **kwargs) -> Series:
"""
Round each value in a Series to the given number of decimals.
Parameters
----------
decimals : int, default 0
Number of decimal places to round to. If decimals is negative,
it specifies the number of positions to the left of the decimal point.
*args, **kwargs
Additional arguments and keywords have no effect but might be
accepted for compatibility with NumPy.
Returns
-------
Series
Rounded values of the Series.
See Also
--------
numpy.around : Round values of an np.array.
DataFrame.round : Round values of a DataFrame.
Examples
--------
>>> s = pd.Series([0.1, 1.3, 2.7])
>>> s.round()
0 0.0
1 1.0
2 3.0
dtype: float64
"""
nv.validate_round(args, kwargs)
> result = self._values.round(decimals)
E TypeError: 'float' object cannot be interpreted as an integer
pandas/core/series.py:2361: TypeError
During handling of the above exception, another exception occurred:
self = <pandas.tests.frame.methods.test_round.TestDataFrameRound object at 0x7fcdd089eb90>
> ???
E AssertionError: Regex pattern 'integer argument expected, got float' does not match "'float' object cannot be interpreted as an integer".
pandas/tests/frame/methods/test_round.py:-1: AssertionError
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/41301 | 2021-05-04T02:47:57Z | 2021-05-06T23:22:43Z | 2021-05-06T23:22:43Z | 2022-11-18T02:21:39Z |
CLN: more descriptive names, annotations in groupby | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 4f60660dfb499..324aef3cd5435 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -524,7 +524,8 @@ def _aggregate_named(self, func, *args, **kwargs):
for name, group in self:
# Each step of this loop corresponds to
# libreduction._BaseGrouper._apply_to_group
- group.name = name # NB: libreduction does not pin name
+ # NB: libreduction does not pin name
+ object.__setattr__(group, "name", name)
output = func(group, *args, **kwargs)
output = libreduction.extract_result(output)
@@ -567,9 +568,9 @@ def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
# Temporarily set observed for dealing with categoricals.
with com.temp_setattr(self, "observed", True):
result = getattr(self, func)(*args, **kwargs)
- return self._transform_fast(result)
+ return self._wrap_transform_fast_result(result)
- def _transform_general(self, func, *args, **kwargs):
+ def _transform_general(self, func: Callable, *args, **kwargs) -> Series:
"""
Transform with a callable func`.
"""
@@ -599,7 +600,7 @@ def _transform_general(self, func, *args, **kwargs):
result.name = self._selected_obj.name
return result
- def _transform_fast(self, result) -> Series:
+ def _wrap_transform_fast_result(self, result: Series) -> Series:
"""
fast version of transform, only applicable to
builtin/cythonizable functions
@@ -1436,11 +1437,11 @@ def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
if isinstance(result, DataFrame) and result.columns.equals(
self._obj_with_exclusions.columns
):
- return self._transform_fast(result)
+ return self._wrap_transform_fast_result(result)
return self._transform_general(func, *args, **kwargs)
- def _transform_fast(self, result: DataFrame) -> DataFrame:
+ def _wrap_transform_fast_result(self, result: DataFrame) -> DataFrame:
"""
Fast transform path for aggregations
"""
@@ -1449,14 +1450,9 @@ def _transform_fast(self, result: DataFrame) -> DataFrame:
# for each col, reshape to size of original frame by take operation
ids, _, _ = self.grouper.group_info
result = result.reindex(self.grouper.result_index, copy=False)
- output = [
- algorithms.take_nd(result.iloc[:, i].values, ids)
- for i, _ in enumerate(result.columns)
- ]
-
- return self.obj._constructor._from_arrays(
- output, columns=result.columns, index=obj.index
- )
+ output = result.take(ids, axis=0)
+ output.index = obj.index
+ return output
def _define_paths(self, func, *args, **kwargs):
if isinstance(func, str):
@@ -1653,7 +1649,7 @@ def _gotitem(self, key, ndim: int, subset=None):
raise AssertionError("invalid ndim for _gotitem")
- def _wrap_frame_output(self, result, obj: DataFrame) -> DataFrame:
+ def _wrap_frame_output(self, result: dict, obj: DataFrame) -> DataFrame:
result_index = self.grouper.levels[0]
if self.axis == 0:
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 620668dadc32d..4bcb1b5a19cb6 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -18,6 +18,7 @@ class providing the base-class of operations.
from textwrap import dedent
import types
from typing import (
+ TYPE_CHECKING,
Callable,
Generic,
Hashable,
@@ -104,6 +105,9 @@ class providing the base-class of operations.
from pandas.core.sorting import get_group_index_sorter
from pandas.core.util.numba_ import NUMBA_FUNC_CACHE
+if TYPE_CHECKING:
+ from typing import Literal
+
_common_see_also = """
See Also
--------
@@ -1989,7 +1993,7 @@ def ewm(self, *args, **kwargs):
)
@final
- def _fill(self, direction, limit=None):
+ def _fill(self, direction: Literal["ffill", "bfill"], limit=None):
"""
Shared function for `pad` and `backfill` to call Cython method.
@@ -2731,7 +2735,7 @@ def _get_cythonized_result(
name = obj.name
values = obj._values
- if numeric_only and not is_numeric_dtype(values):
+ if numeric_only and not is_numeric_dtype(values.dtype):
continue
if aggregate:
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py
index 151756b829a1d..f1762a2535ff7 100644
--- a/pandas/core/groupby/grouper.py
+++ b/pandas/core/groupby/grouper.py
@@ -249,6 +249,10 @@ class Grouper:
Freq: 17T, dtype: int64
"""
+ axis: int
+ sort: bool
+ dropna: bool
+
_attributes: tuple[str, ...] = ("key", "level", "freq", "axis", "sort")
def __new__(cls, *args, **kwargs):
@@ -260,7 +264,13 @@ def __new__(cls, *args, **kwargs):
return super().__new__(cls)
def __init__(
- self, key=None, level=None, freq=None, axis=0, sort=False, dropna=True
+ self,
+ key=None,
+ level=None,
+ freq=None,
+ axis: int = 0,
+ sort: bool = False,
+ dropna: bool = True,
):
self.key = key
self.level = level
@@ -281,11 +291,11 @@ def __init__(
def ax(self):
return self.grouper
- def _get_grouper(self, obj, validate: bool = True):
+ def _get_grouper(self, obj: FrameOrSeries, validate: bool = True):
"""
Parameters
----------
- obj : the subject object
+ obj : Series or DataFrame
validate : bool, default True
if True, validate the grouper
@@ -296,7 +306,9 @@ def _get_grouper(self, obj, validate: bool = True):
self._set_grouper(obj)
# error: Value of type variable "FrameOrSeries" of "get_grouper" cannot be
# "Optional[Any]"
- self.grouper, _, self.obj = get_grouper( # type: ignore[type-var]
+ # error: Incompatible types in assignment (expression has type "BaseGrouper",
+ # variable has type "None")
+ self.grouper, _, self.obj = get_grouper( # type: ignore[type-var,assignment]
self.obj,
[self.key],
axis=self.axis,
@@ -375,15 +387,19 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False):
ax = ax.take(indexer)
obj = obj.take(indexer, axis=self.axis)
- self.obj = obj
- self.grouper = ax
+ # error: Incompatible types in assignment (expression has type
+ # "FrameOrSeries", variable has type "None")
+ self.obj = obj # type: ignore[assignment]
+ # error: Incompatible types in assignment (expression has type "Index",
+ # variable has type "None")
+ self.grouper = ax # type: ignore[assignment]
return self.grouper
@final
@property
def groups(self):
- # error: Item "None" of "Optional[Any]" has no attribute "groups"
- return self.grouper.groups # type: ignore[union-attr]
+ # error: "None" has no attribute "groups"
+ return self.grouper.groups # type: ignore[attr-defined]
@final
def __repr__(self) -> str:
@@ -428,7 +444,7 @@ def __init__(
index: Index,
grouper=None,
obj: FrameOrSeries | None = None,
- name=None,
+ name: Hashable = None,
level=None,
sort: bool = True,
observed: bool = False,
@@ -478,7 +494,12 @@ def __init__(
# what key/level refer to exactly, don't need to
# check again as we have by this point converted these
# to an actual value (rather than a pd.Grouper)
- _, grouper, _ = self.grouper._get_grouper(self.obj, validate=False)
+ _, grouper, _ = self.grouper._get_grouper(
+ # error: Value of type variable "FrameOrSeries" of "_get_grouper"
+ # of "Grouper" cannot be "Optional[FrameOrSeries]"
+ self.obj, # type: ignore[type-var]
+ validate=False,
+ )
if self.name is None:
self.name = grouper.result_index.name
self.obj = self.grouper.obj
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 975a902f49db9..e90892138f15a 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -662,6 +662,8 @@ class BaseGrouper:
"""
+ axis: Index
+
def __init__(
self,
axis: Index,
| https://api.github.com/repos/pandas-dev/pandas/pulls/41300 | 2021-05-04T02:01:14Z | 2021-05-04T16:21:53Z | 2021-05-04T16:21:53Z | 2021-05-04T16:21:53Z | |
TYP: BaseWindowGroupby._grouper | diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 1c85385c587a5..b51875134c614 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -101,6 +101,7 @@
DataFrame,
Series,
)
+ from pandas.core.groupby.ops import BaseGrouper
from pandas.core.internals import Block # noqa:F401
@@ -538,18 +539,22 @@ class BaseWindowGroupby(BaseWindow):
Provide the groupby windowing facilities.
"""
+ _grouper: BaseGrouper
+ _as_index: bool
_attributes = ["_grouper"]
def __init__(
self,
obj: FrameOrSeries,
*args,
- _grouper=None,
- _as_index=True,
+ _grouper: BaseGrouper,
+ _as_index: bool = True,
**kwargs,
):
- if _grouper is None:
- raise ValueError("Must pass a Grouper object.")
+ from pandas.core.groupby.ops import BaseGrouper
+
+ if not isinstance(_grouper, BaseGrouper):
+ raise ValueError("Must pass a BaseGrouper object.")
self._grouper = _grouper
self._as_index = _as_index
# GH 32262: It's convention to keep the grouping column in
@@ -659,7 +664,9 @@ def _apply_pairwise(
# When we evaluate the pairwise=True result, repeat the groupby
# labels by the number of columns in the original object
groupby_codes = self._grouper.codes
- groupby_levels = self._grouper.levels
+ # error: Incompatible types in assignment (expression has type
+ # "List[Index]", variable has type "List[Union[ndarray, Index]]")
+ groupby_levels = self._grouper.levels # type: ignore[assignment]
group_indices = self._grouper.indices.values()
if group_indices:
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41299 | 2021-05-04T01:56:29Z | 2021-05-04T19:29:11Z | 2021-05-04T19:29:11Z | 2021-05-04T19:38:03Z |
REF: raise more selectively in libreduction | diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index 09999b6970bca..9bef6cb428e8a 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -27,12 +27,18 @@ from pandas._libs.lib import (
)
-cpdef check_result_array(object obj):
+cdef cnp.dtype _dtype_obj = np.dtype("object")
- if (is_array(obj) or
- (isinstance(obj, list) and len(obj) == 0) or
- getattr(obj, 'shape', None) == (0,)):
- raise ValueError('Must produce aggregated value')
+
+cpdef check_result_array(object obj, object dtype):
+ # Our operation is supposed to be an aggregation/reduction. If
+ # it returns an ndarray, this likely means an invalid operation has
+ # been passed. See test_apply_without_aggregation, test_agg_must_agg
+ if is_array(obj):
+ if dtype != _dtype_obj:
+ # If it is object dtype, the function can be a reduction/aggregation
+ # and still return an ndarray e.g. test_agg_over_numpy_arrays
+ raise ValueError("Must produce aggregated value")
cdef class _BaseGrouper:
@@ -89,7 +95,7 @@ cdef class _BaseGrouper:
# On the first pass, we check the output shape to see
# if this looks like a reduction.
initialized = True
- check_result_array(res)
+ check_result_array(res, cached_series.dtype)
return res, initialized
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 4f60660dfb499..a69f7ef9dcd49 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -530,7 +530,7 @@ def _aggregate_named(self, func, *args, **kwargs):
output = libreduction.extract_result(output)
if not initialized:
# We only do this validation on the first iteration
- libreduction.check_result_array(output)
+ libreduction.check_result_array(output, group.dtype)
initialized = True
result[name] = output
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 975a902f49db9..d649240c1df88 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -1027,7 +1027,7 @@ def _aggregate_series_pure_python(self, obj: Series, func: F):
if not initialized:
# We only do this validation on the first iteration
- libreduction.check_result_array(res)
+ libreduction.check_result_array(res, group.dtype)
initialized = True
counts[i] = group.shape[0]
| This allows slightly more cases to go through the cython path | https://api.github.com/repos/pandas-dev/pandas/pulls/41298 | 2021-05-04T01:46:50Z | 2021-05-04T19:38:18Z | 2021-05-04T19:38:18Z | 2021-05-04T19:40:52Z |
CLN: remove unused filter_empty from BinGrouper | diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 975a902f49db9..d75e7f75a2b62 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -1047,7 +1047,6 @@ class BinGrouper(BaseGrouper):
----------
bins : the split index of binlabels to group the item of axis
binlabels : the label list
- filter_empty : bool, default False
mutated : bool, default False
indexer : np.ndarray[np.intp]
@@ -1069,17 +1068,20 @@ class BinGrouper(BaseGrouper):
"""
+ bins: np.ndarray # np.ndarray[np.int64]
+ binlabels: Index
+ mutated: bool
+
def __init__(
self,
bins,
binlabels,
- filter_empty: bool = False,
mutated: bool = False,
indexer=None,
):
self.bins = ensure_int64(bins)
self.binlabels = ensure_index(binlabels)
- self._filter_empty_groups = filter_empty
+ self._filter_empty_groups = False
self.mutated = mutated
self.indexer = indexer
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41296 | 2021-05-04T01:12:40Z | 2021-05-04T12:49:12Z | 2021-05-04T12:49:12Z | 2021-05-04T13:58:54Z |
DOC: Validator + converting array_like to array-like in docstrings | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 177dfee0c03ab..f26cf113f7d5e 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1530,13 +1530,13 @@ def searchsorted(arr, value, side="left", sorter=None) -> np.ndarray:
Input array. If `sorter` is None, then it must be sorted in
ascending order, otherwise `sorter` must be an array of indices
that sort it.
- value : array_like
+ value : array-like
Values to insert into `arr`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given.
If 'right', return the last such index. If there is no suitable
index, return either 0 or N (where N is the length of `self`).
- sorter : 1-D array_like, optional
+ sorter : 1-D array-like, optional
Optional array of integer indices that sort array a into ascending
order. They are typically the result of argsort.
diff --git a/pandas/core/array_algos/replace.py b/pandas/core/array_algos/replace.py
index e800f5ac748ec..df4407067b131 100644
--- a/pandas/core/array_algos/replace.py
+++ b/pandas/core/array_algos/replace.py
@@ -45,21 +45,21 @@ def compare_or_regex_search(
a: ArrayLike, b: Scalar | Pattern, regex: bool, mask: np.ndarray
) -> ArrayLike | bool:
"""
- Compare two array_like inputs of the same shape or two scalar values
+ Compare two array-like inputs of the same shape or two scalar values
Calls operator.eq or re.search, depending on regex argument. If regex is
True, perform an element-wise regex matching.
Parameters
----------
- a : array_like
+ a : array-like
b : scalar or regex pattern
regex : bool
mask : np.ndarray[bool]
Returns
-------
- mask : array_like of bool
+ mask : array-like of bool
"""
if isna(b):
return ~mask
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index a6d1986937d2b..888c7cbbffb59 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -826,13 +826,13 @@ def searchsorted(self, value, side="left", sorter=None):
Parameters
----------
- value : array_like
+ value : array-like
Values to insert into `self`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given.
If 'right', return the last such index. If there is no suitable
index, return either 0 or N (where N is the length of `self`).
- sorter : 1-D array_like, optional
+ sorter : 1-D array-like, optional
Optional array of integer indices that sort array a into ascending
order. They are typically the result of argsort.
diff --git a/pandas/core/base.py b/pandas/core/base.py
index ae7e1a1062cfb..104baa04d3459 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -1133,13 +1133,13 @@ def factorize(self, sort: bool = False, na_sentinel: int | None = -1):
Parameters
----------
- value : array_like
+ value : array-like
Values to insert into `self`.
side : {{'left', 'right'}}, optional
If 'left', the index of the first suitable location found is given.
If 'right', return the last such index. If there is no suitable
index, return either 0 or N (where N is the length of `self`).
- sorter : 1-D array_like, optional
+ sorter : 1-D array-like, optional
Optional array of integer indices that sort `self` into ascending
order. They are typically the result of ``np.argsort``.
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 41f77e081c1e9..5bd845534fc96 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -7285,11 +7285,11 @@ def clip(
Parameters
----------
- lower : float or array_like, default None
+ lower : float or array-like, default None
Minimum threshold value. All values below this
threshold will be set to it. A missing
threshold (e.g `NA`) will not clip the value.
- upper : float or array_like, default None
+ upper : float or array-like, default None
Maximum threshold value. All values above this
threshold will be set to it. A missing
threshold (e.g `NA`) will not clip the value.
@@ -7889,8 +7889,8 @@ def resample(
Pass a custom function via ``apply``
- >>> def custom_resampler(array_like):
- ... return np.sum(array_like) + 5
+ >>> def custom_resampler(arraylike):
+ ... return np.sum(arraylike) + 5
...
>>> series.resample('3T').apply(custom_resampler)
2000-01-01 00:00:00 8
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index e4c21b3de2cac..eaba30012a5b8 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -6025,8 +6025,8 @@ def any(self, *args, **kwargs):
Returns
-------
- any : bool or array_like (if axis is specified)
- A single element array_like may be converted to bool.
+ any : bool or array-like (if axis is specified)
+ A single element array-like may be converted to bool.
See Also
--------
@@ -6069,8 +6069,8 @@ def all(self, *args, **kwargs):
Returns
-------
- all : bool or array_like (if axis is specified)
- A single element array_like may be converted to bool.
+ all : bool or array-like (if axis is specified)
+ A single element array-like may be converted to bool.
See Also
--------
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 821d696200175..4dff63ea22e00 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3877,7 +3877,7 @@ def maybe_droplevels(index: Index, key) -> Index:
def _coerce_indexer_frozen(array_like, categories, copy: bool = False) -> np.ndarray:
"""
- Coerce the array_like indexer to the smallest integer dtype that can encode all
+ Coerce the array-like indexer to the smallest integer dtype that can encode all
of the given categories.
Parameters
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 2e7e6c7f7a100..237d06402a0ee 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1276,7 +1276,7 @@ def _unstack(self, unstacker, fill_value, new_placement):
-------
blocks : list of Block
New blocks of unstacked values.
- mask : array_like of bool
+ mask : array-like of bool
The mask of columns of `blocks` we should keep.
"""
new_values, mask = unstacker.get_new_values(
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index 8849eb0670faa..424173ccc69f0 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -524,11 +524,11 @@ def _from_derivatives(xi, yi, x, order=None, der=0, extrapolate=False):
Parameters
----------
- xi : array_like
+ xi : array-like
sorted 1D array of x-coordinates
- yi : array_like or list of array-likes
+ yi : array-like or list of array-likes
yi[i][j] is the j-th derivative known at xi[i]
- order: None or int or array_like of ints. Default: None.
+ order: None or int or array-like of ints. Default: None.
Specifies the degree of local polynomials. If not None, some
derivatives are ignored.
der : int or list
@@ -546,7 +546,7 @@ def _from_derivatives(xi, yi, x, order=None, der=0, extrapolate=False):
Returns
-------
- y : scalar or array_like
+ y : scalar or array-like
The result, of length R or length M or M by R.
"""
from scipy import interpolate
@@ -568,13 +568,13 @@ def _akima_interpolate(xi, yi, x, der=0, axis=0):
Parameters
----------
- xi : array_like
+ xi : array-like
A sorted list of x-coordinates, of length N.
- yi : array_like
+ yi : array-like
A 1-D array of real values. `yi`'s length along the interpolation
axis must be equal to the length of `xi`. If N-D array, use axis
parameter to select correct axis.
- x : scalar or array_like
+ x : scalar or array-like
Of length M.
der : int, optional
How many derivatives to extract; None for all potentially
@@ -590,7 +590,7 @@ def _akima_interpolate(xi, yi, x, der=0, axis=0):
Returns
-------
- y : scalar or array_like
+ y : scalar or array-like
The result, of length R or length M or M by R,
"""
@@ -609,14 +609,14 @@ def _cubicspline_interpolate(xi, yi, x, axis=0, bc_type="not-a-knot", extrapolat
Parameters
----------
- xi : array_like, shape (n,)
+ xi : array-like, shape (n,)
1-d array containing values of the independent variable.
Values must be real, finite and in strictly increasing order.
- yi : array_like
+ yi : array-like
Array containing values of the dependent variable. It can have
arbitrary number of dimensions, but the length along ``axis``
(see below) must match the length of ``x``. Values must be finite.
- x : scalar or array_like, shape (m,)
+ x : scalar or array-like, shape (m,)
axis : int, optional
Axis along which `y` is assumed to be varying. Meaning that for
``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
@@ -644,7 +644,7 @@ def _cubicspline_interpolate(xi, yi, x, axis=0, bc_type="not-a-knot", extrapolat
tuple `(order, deriv_values)` allowing to specify arbitrary
derivatives at curve ends:
* `order`: the derivative order, 1 or 2.
- * `deriv_value`: array_like containing derivative values, shape must
+ * `deriv_value`: array-like containing derivative values, shape must
be the same as `y`, excluding ``axis`` dimension. For example, if
`y` is 1D, then `deriv_value` must be a scalar. If `y` is 3D with
the shape (n0, n1, n2) and axis=2, then `deriv_value` must be 2D
@@ -661,7 +661,7 @@ def _cubicspline_interpolate(xi, yi, x, axis=0, bc_type="not-a-knot", extrapolat
Returns
-------
- y : scalar or array_like
+ y : scalar or array-like
The result, of shape (m,)
References
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index 5d3db13610845..00d87b707580d 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -430,7 +430,7 @@ def hist_frame(
y : label or position, optional
Allows plotting of one column versus another. If not specified,
all numerical columns are used.
- color : str, array_like, or dict, optional
+ color : str, array-like, or dict, optional
The color for each of the DataFrame's columns. Possible values are:
- A single color string referred to by name, RGB or RGBA code,
@@ -1571,7 +1571,7 @@ def scatter(self, x, y, s=None, c=None, **kwargs):
y : int or str
The column name or column position to be used as vertical
coordinates for each point.
- s : str, scalar or array_like, optional
+ s : str, scalar or array-like, optional
The size of each point. Possible values are:
- A string with the name of the column to be used for marker's size.
@@ -1584,7 +1584,7 @@ def scatter(self, x, y, s=None, c=None, **kwargs):
.. versionchanged:: 1.1.0
- c : str, int or array_like, optional
+ c : str, int or array-like, optional
The color of each point. Possible values are:
- A single color string referred to by name, RGB or RGBA code,
diff --git a/scripts/tests/test_validate_docstrings.py b/scripts/tests/test_validate_docstrings.py
index cbf3e84044d53..46cfae8e31208 100644
--- a/scripts/tests/test_validate_docstrings.py
+++ b/scripts/tests/test_validate_docstrings.py
@@ -82,6 +82,12 @@ def missing_whitespace_after_comma(self):
"""
pass
+ def write_array_like_with_hyphen_not_underscore(self):
+ """
+ In docstrings, use array-like over array_like
+ """
+ pass
+
class TestValidator:
def _import_path(self, klass=None, func=None):
@@ -172,6 +178,11 @@ def test_bad_class(self, capsys):
"missing_whitespace_after_comma",
("flake8 error: E231 missing whitespace after ',' (3 times)",),
),
+ (
+ "BadDocstrings",
+ "write_array_like_with_hyphen_not_underscore",
+ ("Use 'array-like' rather than 'array_like' in docstrings",),
+ ),
],
)
def test_bad_docstrings(self, capsys, klass, func, msgs):
diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py
index b77210e3d2bab..9b65204403612 100755
--- a/scripts/validate_docstrings.py
+++ b/scripts/validate_docstrings.py
@@ -54,6 +54,7 @@
ERROR_MSGS = {
"GL04": "Private classes ({mentioned_private_classes}) should not be "
"mentioned in public docstrings",
+ "GL05": "Use 'array-like' rather than 'array_like' in docstrings.",
"SA05": "{reference_name} in `See Also` section does not need `pandas` "
"prefix, use {right_reference} instead.",
"EX02": "Examples do not pass tests:\n{doctest_log}",
@@ -196,6 +197,9 @@ def validate_pep8(self):
error_count, error_code, message = error_message.split(maxsplit=2)
yield error_code, message, int(error_count)
+ def non_hyphenated_array_like(self):
+ return "array_like" in self.raw_doc
+
def pandas_validate(func_name: str):
"""
@@ -256,6 +260,9 @@ def pandas_validate(func_name: str):
pandas_error("EX04", imported_library=wrong_import)
)
+ if doc.non_hyphenated_array_like():
+ result["errors"].append(pandas_error("GL05"))
+
return result
| - [ ] closes #40560 (Pending feedback on decorator-generated docstrings)
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
First try at any open source stuff! This one looked pretty doable, hopefully it's there's nothing wrong with it/let me know!
I'm not sure whether *I* should be checking these boxes, or a reviewer should. I *believe* this fixes the issue since it adds the validator, though it's not a particularly clever validator.
It technically is an added test, and it technically works - I re-added one of the entries and got a successful (correct) result for its failure... (amongst the infinite other validation failures 😢 )
I assume linting will run after the PR is submitted, but I'll look into running it locally, too.
```
...
None:None:ES01:pandas.IndexSlice:No extended summary foundNone:None:EX03:pandas.IndexSlice:flake8 error: E231 missing whitespace after ',' (4 times)
.../pandas/pandas/core/indexes/multi.py:434:ES01:pandas.MultiIndex.from_arrays:No extended summary found
.../pandas/pandas/core/indexes/multi.py:434:GL05:pandas.MultiIndex.from_arrays:Use 'array-like' rather than 'array_like' in docstrings. <<<--- Message for added issue.
.../pandas/pandas/core/indexes/multi.py:500:ES01:pandas.MultiIndex.from_tuples:No extended summary found
.../pandas/pandas/core/indexes/multi.py:567:ES01:pandas.MultiIndex.from_product:No extended summary found
None:None:ES01:pandas.MultiIndex.names:No extended summary found
...
```
More on the validator:
* I chose `GL` as the code after looking through [the numpy docstring validation guide](https://numpydoc.readthedocs.io/en/latest/validation.html) and the [pandas docstring validation guide](https://pandas.pydata.org/docs/dev/development/contributing_docstring.html) - I think it stands for "General" and that seems like the best categorization for this message.
* I used `raw_doc` for this but there was another property like `clean_doc` as well. I could just iterate through each section, too. 🤷
* I didn't add any extra detail/context to the error message. The line and file are already given, so I think there's nothing extra that's needed.
Using the validator to pick up any missed docstring changes:
```
$ time ./validate_docstrings.py 2>&1 | tee validate_docstrings.log ### (It takes ~5m to run)
$ grep GL05 validate_docstrings.log
.../pandas/pandas/core/frame.py:10220:GL05:pandas.DataFrame.resample:Use 'array-like' rather than 'array_like' in docstrings.
.../pandas/pandas/core/series.py:5171:GL05:pandas.Series.resample:Use 'array-like' rather than 'array_like' in docstrings.
```
-----
Actually, looking into those two remaining results - those are docstrings generated by lines like:
```10220 @doc(NDFrame.resample, **_shared_doc_kwargs)```
Looking in more detail, I'm not exactly sure how this happens, but it seems like this decorator must be generating text with "array_like" in it. I kind of want to declare it out of scope for this PR, but I can dig into it more if needed.
I suspect maybe the `Substitution` decorator tool can help, possibly. It seems kind of cheesy to add something that will substitute array_like for array-like in a docstring - eg, it might be the result of a function whose param is actually called `array_like`, which, I'm pretty sure they *do* exist. I'm open to feedback on that.
| https://api.github.com/repos/pandas-dev/pandas/pulls/41295 | 2021-05-04T00:10:24Z | 2021-06-12T10:21:23Z | 2021-06-12T10:21:22Z | 2021-06-19T22:37:10Z |
REF: support object dtype in libgroupby.group_add | diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx
index 3fa92ce2229c3..8637d50745195 100644
--- a/pandas/_libs/groupby.pyx
+++ b/pandas/_libs/groupby.pyx
@@ -469,18 +469,19 @@ def group_any_all(int8_t[::1] out,
# group_add, group_prod, group_var, group_mean, group_ohlc
# ----------------------------------------------------------------------
-ctypedef fused complexfloating_t:
+ctypedef fused add_t:
float64_t
float32_t
complex64_t
complex128_t
+ object
@cython.wraparound(False)
@cython.boundscheck(False)
-def group_add(complexfloating_t[:, ::1] out,
+def group_add(add_t[:, ::1] out,
int64_t[::1] counts,
- ndarray[complexfloating_t, ndim=2] values,
+ ndarray[add_t, ndim=2] values,
const intp_t[:] labels,
Py_ssize_t min_count=0) -> None:
"""
@@ -488,8 +489,8 @@ def group_add(complexfloating_t[:, ::1] out,
"""
cdef:
Py_ssize_t i, j, N, K, lab, ncounts = len(counts)
- complexfloating_t val, count, t, y
- complexfloating_t[:, ::1] sumx, compensation
+ add_t val, t, y
+ add_t[:, ::1] sumx, compensation
int64_t[:, ::1] nobs
Py_ssize_t len_values = len(values), len_labels = len(labels)
@@ -503,7 +504,8 @@ def group_add(complexfloating_t[:, ::1] out,
N, K = (<object>values).shape
- with nogil:
+ if add_t is object:
+ # NB: this does not use 'compensation' like the non-object track does.
for i in range(N):
lab = labels[i]
if lab < 0:
@@ -516,9 +518,13 @@ def group_add(complexfloating_t[:, ::1] out,
# not nan
if val == val:
nobs[lab, j] += 1
- y = val - compensation[lab, j]
- t = sumx[lab, j] + y
- compensation[lab, j] = t - sumx[lab, j] - y
+
+ if nobs[lab, j] == 1:
+ # i.e. we havent added anything yet; avoid TypeError
+ # if e.g. val is a str and sumx[lab, j] is 0
+ t = val
+ else:
+ t = sumx[lab, j] + val
sumx[lab, j] = t
for i in range(ncounts):
@@ -527,6 +533,31 @@ def group_add(complexfloating_t[:, ::1] out,
out[i, j] = NAN
else:
out[i, j] = sumx[i, j]
+ else:
+ with nogil:
+ for i in range(N):
+ lab = labels[i]
+ if lab < 0:
+ continue
+
+ counts[lab] += 1
+ for j in range(K):
+ val = values[i, j]
+
+ # not nan
+ if val == val:
+ nobs[lab, j] += 1
+ y = val - compensation[lab, j]
+ t = sumx[lab, j] + y
+ compensation[lab, j] = t - sumx[lab, j] - y
+ sumx[lab, j] = t
+
+ for i in range(ncounts):
+ for j in range(K):
+ if nobs[i, j] < min_count:
+ out[i, j] = NAN
+ else:
+ out[i, j] = sumx[i, j]
@cython.wraparound(False)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41294 | 2021-05-03T23:02:03Z | 2021-05-04T16:22:29Z | 2021-05-04T16:22:29Z | 2021-05-04T16:25:45Z |
[ArrowStringArray] REF: pre-cursor to adding replace str accessor method | diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 85a58d3d99795..82462f8d922d5 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -19,6 +19,7 @@
is_categorical_dtype,
is_integer,
is_list_like,
+ is_re,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
@@ -1333,6 +1334,29 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None):
)
warnings.warn(msg, FutureWarning, stacklevel=3)
regex = True
+
+ # Check whether repl is valid (GH 13438, GH 15055)
+ if not (isinstance(repl, str) or callable(repl)):
+ raise TypeError("repl must be a string or callable")
+
+ is_compiled_re = is_re(pat)
+ if regex:
+ if is_compiled_re:
+ if (case is not None) or (flags != 0):
+ raise ValueError(
+ "case and flags cannot be set when pat is a compiled regex"
+ )
+ elif case is None:
+ # not a compiled regex, set default case
+ case = True
+
+ elif is_compiled_re:
+ raise ValueError(
+ "Cannot use a compiled regex as replacement pattern with regex=False"
+ )
+ elif callable(repl):
+ raise ValueError("Cannot use a callable replacement when regex=False")
+
result = self._data.array._str_replace(
pat, repl, n=n, case=case, flags=flags, regex=regex
)
diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py
index b794690ccc5af..c7e4368a98c95 100644
--- a/pandas/core/strings/object_array.py
+++ b/pandas/core/strings/object_array.py
@@ -147,41 +147,20 @@ def _str_endswith(self, pat, na=None):
f = lambda x: x.endswith(pat)
return self._str_map(f, na_value=na, dtype=np.dtype(bool))
- def _str_replace(self, pat, repl, n=-1, case=None, flags=0, regex=True):
- # Check whether repl is valid (GH 13438, GH 15055)
- if not (isinstance(repl, str) or callable(repl)):
- raise TypeError("repl must be a string or callable")
-
+ def _str_replace(self, pat, repl, n=-1, case: bool = True, flags=0, regex=True):
is_compiled_re = is_re(pat)
- if regex:
- if is_compiled_re:
- if (case is not None) or (flags != 0):
- raise ValueError(
- "case and flags cannot be set when pat is a compiled regex"
- )
- else:
- # not a compiled regex
- # set default case
- if case is None:
- case = True
-
- # add case flag, if provided
- if case is False:
- flags |= re.IGNORECASE
- if is_compiled_re or len(pat) > 1 or flags or callable(repl):
- n = n if n >= 0 else 0
- compiled = re.compile(pat, flags=flags)
- f = lambda x: compiled.sub(repl=repl, string=x, count=n)
- else:
- f = lambda x: x.replace(pat, repl, n)
+
+ if case is False:
+ # add case flag, if provided
+ flags |= re.IGNORECASE
+
+ if regex and (is_compiled_re or len(pat) > 1 or flags or callable(repl)):
+ if not is_compiled_re:
+ pat = re.compile(pat, flags=flags)
+
+ n = n if n >= 0 else 0
+ f = lambda x: pat.sub(repl=repl, string=x, count=n)
else:
- if is_compiled_re:
- raise ValueError(
- "Cannot use a compiled regex as replacement pattern with "
- "regex=False"
- )
- if callable(repl):
- raise ValueError("Cannot use a callable replacement when regex=False")
f = lambda x: x.replace(pat, repl, n)
return self._str_map(f, dtype=str)
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index 0c54042d983ad..3d33e34a9dcfe 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -266,144 +266,157 @@ def test_endswith_nullable_string_dtype(nullable_string_dtype, na):
tm.assert_series_equal(result, exp)
-def test_replace():
- values = Series(["fooBAD__barBAD", np.nan])
+def test_replace(any_string_dtype):
+ values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
result = values.str.replace("BAD[_]*", "", regex=True)
- exp = Series(["foobar", np.nan])
- tm.assert_series_equal(result, exp)
+ expected = Series(["foobar", np.nan], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
result = values.str.replace("BAD[_]*", "", n=1, regex=True)
- exp = Series(["foobarBAD", np.nan])
- tm.assert_series_equal(result, exp)
+ expected = Series(["foobarBAD", np.nan], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
- # mixed
+
+def test_replace_mixed_object():
mixed = Series(
["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0]
)
- rs = Series(mixed).str.replace("BAD[_]*", "", regex=True)
- xp = Series(["a", np.nan, "b", np.nan, np.nan, "foo", np.nan, np.nan, np.nan])
- assert isinstance(rs, Series)
- tm.assert_almost_equal(rs, xp)
+ result = Series(mixed).str.replace("BAD[_]*", "", regex=True)
+ expected = Series(["a", np.nan, "b", np.nan, np.nan, "foo", np.nan, np.nan, np.nan])
+ assert isinstance(result, Series)
+ tm.assert_almost_equal(result, expected)
- # flags + unicode
- values = Series([b"abcd,\xc3\xa0".decode("utf-8")])
- exp = Series([b"abcd, \xc3\xa0".decode("utf-8")])
+
+def test_replace_unicode(any_string_dtype):
+ values = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
+ expected = Series([b"abcd, \xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
result = values.str.replace(r"(?<=\w),(?=\w)", ", ", flags=re.UNICODE, regex=True)
- tm.assert_series_equal(result, exp)
+ tm.assert_series_equal(result, expected)
+
- # GH 13438
+@pytest.mark.parametrize("klass", [Series, Index])
+@pytest.mark.parametrize("repl", [None, 3, {"a": "b"}])
+@pytest.mark.parametrize("data", [["a", "b", None], ["a", "b", "c", "ad"]])
+def test_replace_raises(any_string_dtype, klass, repl, data):
+ # https://github.com/pandas-dev/pandas/issues/13438
msg = "repl must be a string or callable"
- for klass in (Series, Index):
- for repl in (None, 3, {"a": "b"}):
- for data in (["a", "b", None], ["a", "b", "c", "ad"]):
- values = klass(data)
- with pytest.raises(TypeError, match=msg):
- values.str.replace("a", repl)
+ values = klass(data, dtype=any_string_dtype)
+ with pytest.raises(TypeError, match=msg):
+ values.str.replace("a", repl)
-def test_replace_callable():
+def test_replace_callable(any_string_dtype):
# GH 15055
- values = Series(["fooBAD__barBAD", np.nan])
+ values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
# test with callable
repl = lambda m: m.group(0).swapcase()
result = values.str.replace("[a-z][A-Z]{2}", repl, n=2, regex=True)
- exp = Series(["foObaD__baRbaD", np.nan])
- tm.assert_series_equal(result, exp)
+ expected = Series(["foObaD__baRbaD", np.nan], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "repl", [lambda: None, lambda m, x: None, lambda m, x, y=None: None]
+)
+def test_replace_callable_raises(any_string_dtype, repl):
+ # GH 15055
+ values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
# test with wrong number of arguments, raising an error
- p_err = (
+ msg = (
r"((takes)|(missing)) (?(2)from \d+ to )?\d+ "
r"(?(3)required )positional arguments?"
)
-
- repl = lambda: None
- with pytest.raises(TypeError, match=p_err):
+ with pytest.raises(TypeError, match=msg):
values.str.replace("a", repl)
- repl = lambda m, x: None
- with pytest.raises(TypeError, match=p_err):
- values.str.replace("a", repl)
-
- repl = lambda m, x, y=None: None
- with pytest.raises(TypeError, match=p_err):
- values.str.replace("a", repl)
+def test_replace_callable_named_groups(any_string_dtype):
# test regex named groups
- values = Series(["Foo Bar Baz", np.nan])
+ values = Series(["Foo Bar Baz", np.nan], dtype=any_string_dtype)
pat = r"(?P<first>\w+) (?P<middle>\w+) (?P<last>\w+)"
repl = lambda m: m.group("middle").swapcase()
result = values.str.replace(pat, repl, regex=True)
- exp = Series(["bAR", np.nan])
- tm.assert_series_equal(result, exp)
+ expected = Series(["bAR", np.nan], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
-def test_replace_compiled_regex():
+def test_replace_compiled_regex(any_string_dtype):
# GH 15446
- values = Series(["fooBAD__barBAD", np.nan])
+ values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
# test with compiled regex
pat = re.compile(r"BAD_*")
result = values.str.replace(pat, "", regex=True)
- exp = Series(["foobar", np.nan])
- tm.assert_series_equal(result, exp)
+ expected = Series(["foobar", np.nan], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
result = values.str.replace(pat, "", n=1, regex=True)
- exp = Series(["foobarBAD", np.nan])
- tm.assert_series_equal(result, exp)
+ expected = Series(["foobarBAD", np.nan], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
- # mixed
+
+def test_replace_compiled_regex_mixed_object():
+ pat = re.compile(r"BAD_*")
mixed = Series(
["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0]
)
- rs = Series(mixed).str.replace(pat, "", regex=True)
- xp = Series(["a", np.nan, "b", np.nan, np.nan, "foo", np.nan, np.nan, np.nan])
- assert isinstance(rs, Series)
- tm.assert_almost_equal(rs, xp)
+ result = Series(mixed).str.replace(pat, "", regex=True)
+ expected = Series(["a", np.nan, "b", np.nan, np.nan, "foo", np.nan, np.nan, np.nan])
+ assert isinstance(result, Series)
+ tm.assert_almost_equal(result, expected)
+
- # flags + unicode
- values = Series([b"abcd,\xc3\xa0".decode("utf-8")])
- exp = Series([b"abcd, \xc3\xa0".decode("utf-8")])
+def test_replace_compiled_regex_unicode(any_string_dtype):
+ values = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
+ expected = Series([b"abcd, \xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
pat = re.compile(r"(?<=\w),(?=\w)", flags=re.UNICODE)
result = values.str.replace(pat, ", ")
- tm.assert_series_equal(result, exp)
+ tm.assert_series_equal(result, expected)
+
+def test_replace_compiled_regex_raises(any_string_dtype):
# case and flags provided to str.replace will have no effect
# and will produce warnings
- values = Series(["fooBAD__barBAD__bad", np.nan])
+ values = Series(["fooBAD__barBAD__bad", np.nan], dtype=any_string_dtype)
pat = re.compile(r"BAD_*")
- with pytest.raises(ValueError, match="case and flags cannot be"):
- result = values.str.replace(pat, "", flags=re.IGNORECASE)
+ msg = "case and flags cannot be set when pat is a compiled regex"
- with pytest.raises(ValueError, match="case and flags cannot be"):
- result = values.str.replace(pat, "", case=False)
+ with pytest.raises(ValueError, match=msg):
+ values.str.replace(pat, "", flags=re.IGNORECASE)
- with pytest.raises(ValueError, match="case and flags cannot be"):
- result = values.str.replace(pat, "", case=True)
+ with pytest.raises(ValueError, match=msg):
+ values.str.replace(pat, "", case=False)
+ with pytest.raises(ValueError, match=msg):
+ values.str.replace(pat, "", case=True)
+
+
+def test_replace_compiled_regex_callable(any_string_dtype):
# test with callable
- values = Series(["fooBAD__barBAD", np.nan])
+ values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
repl = lambda m: m.group(0).swapcase()
pat = re.compile("[a-z][A-Z]{2}")
result = values.str.replace(pat, repl, n=2)
- exp = Series(["foObaD__baRbaD", np.nan])
- tm.assert_series_equal(result, exp)
+ expected = Series(["foObaD__baRbaD", np.nan], dtype=any_string_dtype)
+ tm.assert_series_equal(result, expected)
-def test_replace_literal():
+def test_replace_literal(any_string_dtype):
# GH16808 literal replace (regex=False vs regex=True)
- values = Series(["f.o", "foo", np.nan])
- exp = Series(["bao", "bao", np.nan])
+ values = Series(["f.o", "foo", np.nan], dtype=any_string_dtype)
+ expected = Series(["bao", "bao", np.nan], dtype=any_string_dtype)
result = values.str.replace("f.", "ba", regex=True)
- tm.assert_series_equal(result, exp)
+ tm.assert_series_equal(result, expected)
- exp = Series(["bao", "foo", np.nan])
+ expected = Series(["bao", "foo", np.nan], dtype=any_string_dtype)
result = values.str.replace("f.", "ba", regex=False)
- tm.assert_series_equal(result, exp)
+ tm.assert_series_equal(result, expected)
# Cannot do a literal replace if given a callable repl or compiled
# pattern
@@ -680,13 +693,17 @@ def test_contains_nan(any_string_dtype):
tm.assert_series_equal(result, expected)
-def test_replace_moar():
+def test_replace_moar(any_string_dtype):
# PR #1179
- s = Series(["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"])
+ s = Series(
+ ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"],
+ dtype=any_string_dtype,
+ )
result = s.str.replace("A", "YYY")
expected = Series(
- ["YYY", "B", "C", "YYYaba", "Baca", "", np.nan, "CYYYBYYY", "dog", "cat"]
+ ["YYY", "B", "C", "YYYaba", "Baca", "", np.nan, "CYYYBYYY", "dog", "cat"],
+ dtype=any_string_dtype,
)
tm.assert_series_equal(result, expected)
@@ -703,7 +720,8 @@ def test_replace_moar():
"CYYYBYYY",
"dog",
"cYYYt",
- ]
+ ],
+ dtype=any_string_dtype,
)
tm.assert_series_equal(result, expected)
@@ -720,7 +738,8 @@ def test_replace_moar():
"XX-XX BA",
"XX-XX ",
"XX-XX t",
- ]
+ ],
+ dtype=any_string_dtype,
)
tm.assert_series_equal(result, expected)
| pre-cursor cleanup to avoid duplicating validation | https://api.github.com/repos/pandas-dev/pandas/pulls/41293 | 2021-05-03T21:40:25Z | 2021-05-04T16:26:35Z | 2021-05-04T16:26:35Z | 2021-05-04T18:10:17Z |
BUG: fix suppressed TypeErrors in Groupby.mean, median, var | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 620668dadc32d..9935bc706b7b1 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1559,7 +1559,7 @@ def mean(self, numeric_only: bool = True):
"""
result = self._cython_agg_general(
"mean",
- alt=lambda x, axis: Series(x).mean(numeric_only=numeric_only),
+ alt=lambda x: Series(x).mean(numeric_only=numeric_only),
numeric_only=numeric_only,
)
return result.__finalize__(self.obj, method="groupby")
@@ -1586,7 +1586,7 @@ def median(self, numeric_only=True):
"""
result = self._cython_agg_general(
"median",
- alt=lambda x, axis: Series(x).median(axis=axis, numeric_only=numeric_only),
+ alt=lambda x: Series(x).median(numeric_only=numeric_only),
numeric_only=numeric_only,
)
return result.__finalize__(self.obj, method="groupby")
@@ -1642,7 +1642,7 @@ def var(self, ddof: int = 1):
"""
if ddof == 1:
return self._cython_agg_general(
- "var", alt=lambda x, axis: Series(x).var(ddof=ddof)
+ "var", alt=lambda x: Series(x).var(ddof=ddof)
)
else:
func = lambda x: x.var(ddof=ddof)
| These are raising TypeError because we aren't passing enough args, but then we're catching those TypeErrors and falling back. So this doesn't change behavior, just avoids an unnecessary fallback in some cases.
No tests. Surfacing the exceptions would require ugly/invasive changes. | https://api.github.com/repos/pandas-dev/pandas/pulls/41292 | 2021-05-03T21:31:20Z | 2021-05-04T16:23:01Z | 2021-05-04T16:23:01Z | 2021-05-04T16:26:07Z |
REF: Share py_fallback | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 4f60660dfb499..c04ad0e9dfa30 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -69,7 +69,6 @@
validate_func_kwargs,
)
from pandas.core.apply import GroupByApply
-from pandas.core.arrays import Categorical
from pandas.core.base import (
DataError,
SpecificationError,
@@ -84,7 +83,6 @@
_agg_template,
_apply_docs,
_transform_template,
- get_groupby,
group_selection_context,
)
from pandas.core.indexes.api import (
@@ -353,6 +351,7 @@ def _cython_agg_general(
obj = self._selected_obj
objvals = obj._values
+ data = obj._mgr
if numeric_only and not is_numeric_dtype(obj.dtype):
raise DataError("No numeric types to aggregate")
@@ -362,28 +361,15 @@ def _cython_agg_general(
def array_func(values: ArrayLike) -> ArrayLike:
try:
result = self.grouper._cython_operation(
- "aggregate", values, how, axis=0, min_count=min_count
+ "aggregate", values, how, axis=data.ndim - 1, min_count=min_count
)
except NotImplementedError:
- ser = Series(values) # equiv 'obj' from outer frame
- if self.ngroups > 0:
- res_values, _ = self.grouper.agg_series(ser, alt)
- else:
- # equiv: res_values = self._python_agg_general(alt)
- # error: Incompatible types in assignment (expression has
- # type "Union[DataFrame, Series]", variable has type
- # "Union[ExtensionArray, ndarray]")
- res_values = self._python_apply_general( # type: ignore[assignment]
- alt, ser
- )
+ # generally if we have numeric_only=False
+ # and non-applicable functions
+ # try to python agg
+ # TODO: shouldn't min_count matter?
+ result = self._agg_py_fallback(values, ndim=data.ndim, alt=alt)
- if isinstance(values, Categorical):
- # Because we only get here with known dtype-preserving
- # reductions, we cast back to Categorical.
- # TODO: if we ever get "rank" working, exclude it here.
- result = type(values)._from_sequence(res_values, dtype=values.dtype)
- else:
- result = res_values
return result
result = array_func(objvals)
@@ -1115,72 +1101,17 @@ def _cython_agg_general(
if numeric_only:
data = data.get_numeric_data(copy=False)
- def cast_agg_result(result: ArrayLike, values: ArrayLike) -> ArrayLike:
- # see if we can cast the values to the desired dtype
- # this may not be the original dtype
-
- if isinstance(result.dtype, np.dtype) and result.ndim == 1:
- # We went through a SeriesGroupByPath and need to reshape
- # GH#32223 includes case with IntegerArray values
- # We only get here with values.dtype == object
- result = result.reshape(1, -1)
- # test_groupby_duplicate_columns gets here with
- # result.dtype == int64, values.dtype=object, how="min"
-
- return result
-
- def py_fallback(values: ArrayLike) -> ArrayLike:
- # if self.grouper.aggregate fails, we fall back to a pure-python
- # solution
-
- # We get here with a) EADtypes and b) object dtype
- obj: FrameOrSeriesUnion
-
- # call our grouper again with only this block
- if values.ndim == 1:
- # We only get here with ExtensionArray
-
- obj = Series(values)
- else:
- # We only get here with values.dtype == object
- # TODO special case not needed with ArrayManager
- df = DataFrame(values.T)
- # bc we split object blocks in grouped_reduce, we have only 1 col
- # otherwise we'd have to worry about block-splitting GH#39329
- assert df.shape[1] == 1
- # Avoid call to self.values that can occur in DataFrame
- # reductions; see GH#28949
- obj = df.iloc[:, 0]
-
- # Create SeriesGroupBy with observed=True so that it does
- # not try to add missing categories if grouping over multiple
- # Categoricals. This will done by later self._reindex_output()
- # Doing it here creates an error. See GH#34951
- sgb = get_groupby(obj, self.grouper, observed=True)
-
- # Note: bc obj is always a Series here, we can ignore axis and pass
- # `alt` directly instead of `lambda x: alt(x, axis=self.axis)`
- # use _agg_general bc it will go through _cython_agg_general
- # which will correctly cast Categoricals.
- res_ser = sgb._agg_general(
- numeric_only=False, min_count=min_count, alias=how, npfunc=alt
- )
-
- # unwrap Series to get array
- res_values = res_ser._mgr.arrays[0]
- return cast_agg_result(res_values, values)
-
def array_func(values: ArrayLike) -> ArrayLike:
-
try:
result = self.grouper._cython_operation(
- "aggregate", values, how, axis=1, min_count=min_count
+ "aggregate", values, how, axis=data.ndim - 1, min_count=min_count
)
except NotImplementedError:
# generally if we have numeric_only=False
# and non-applicable functions
# try to python agg
- result = py_fallback(values)
+ # TODO: shouldn't min_count matter?
+ result = self._agg_py_fallback(values, ndim=data.ndim, alt=alt)
return result
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 620668dadc32d..5b2b00713b318 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -100,6 +100,7 @@ class providing the base-class of operations.
Index,
MultiIndex,
)
+from pandas.core.internals.blocks import ensure_block_shape
from pandas.core.series import Series
from pandas.core.sorting import get_group_index_sorter
from pandas.core.util.numba_ import NUMBA_FUNC_CACHE
@@ -1313,6 +1314,54 @@ def _agg_general(
result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
return result.__finalize__(self.obj, method="groupby")
+ def _agg_py_fallback(
+ self, values: ArrayLike, ndim: int, alt: Callable
+ ) -> ArrayLike:
+ """
+ Fallback to pure-python aggregation if _cython_operation raises
+ NotImplementedError.
+ """
+ # We get here with a) EADtypes and b) object dtype
+
+ if values.ndim == 1:
+ # For DataFrameGroupBy we only get here with ExtensionArray
+ ser = Series(values)
+ else:
+ # We only get here with values.dtype == object
+ # TODO: special case not needed with ArrayManager
+ df = DataFrame(values.T)
+ # bc we split object blocks in grouped_reduce, we have only 1 col
+ # otherwise we'd have to worry about block-splitting GH#39329
+ assert df.shape[1] == 1
+ # Avoid call to self.values that can occur in DataFrame
+ # reductions; see GH#28949
+ ser = df.iloc[:, 0]
+
+ # Create SeriesGroupBy with observed=True so that it does
+ # not try to add missing categories if grouping over multiple
+ # Categoricals. This will done by later self._reindex_output()
+ # Doing it here creates an error. See GH#34951
+ sgb = get_groupby(ser, self.grouper, observed=True)
+ # For SeriesGroupBy we could just use self instead of sgb
+
+ if self.ngroups > 0:
+ res_values, _ = self.grouper.agg_series(ser, alt)
+ else:
+ # equiv: res_values = self._python_agg_general(alt)
+ res_values = sgb._python_apply_general(alt, ser)._values
+
+ if isinstance(values, Categorical):
+ # Because we only get here with known dtype-preserving
+ # reductions, we cast back to Categorical.
+ # TODO: if we ever get "rank" working, exclude it here.
+ res_values = type(values)._from_sequence(res_values, dtype=values.dtype)
+
+ # If we are DataFrameGroupBy and went through a SeriesGroupByPath
+ # then we need to reshape
+ # GH#32223 includes case with IntegerArray values, ndarray res_values
+ # test_groupby_duplicate_columns with object dtype values
+ return ensure_block_shape(res_values, ndim=ndim)
+
def _cython_agg_general(
self, how: str, alt=None, numeric_only: bool = True, min_count: int = -1
):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41289 | 2021-05-03T19:24:11Z | 2021-05-04T16:27:25Z | 2021-05-04T16:27:25Z | 2021-05-04T16:40:44Z |
Bug in iloc.setitem orienting IntegerArray into the wrong direction | diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py
index d3756d6252c0a..4f3f536cd3290 100644
--- a/pandas/core/indexers.py
+++ b/pandas/core/indexers.py
@@ -164,7 +164,7 @@ def check_setitem_lengths(indexer, value, values) -> bool:
# a) not necessarily 1-D indexers, e.g. tuple
# b) boolean indexers e.g. BoolArray
if is_list_like(value):
- if len(indexer) != len(value):
+ if len(indexer) != len(value) and values.ndim == 1:
# boolean with truth values == len of the value is ok too
if not (
isinstance(indexer, np.ndarray)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 61396fdf372d5..d87e77043a713 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -970,12 +970,7 @@ def setitem(self, indexer, value):
values[indexer] = value
elif is_ea_value:
- # GH#38952
- if values.ndim == 1:
- values[indexer] = value
- else:
- # TODO(EA2D): special case not needed with 2D EA
- values[indexer] = value.to_numpy(values.dtype).reshape(-1, 1)
+ values[indexer] = value
else:
# error: Argument 1 to "setitem_datetimelike_compat" has incompatible type
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 4004e595c832f..f46ecf61138b1 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -18,6 +18,7 @@
PeriodDtype,
)
+import pandas as pd
from pandas import (
Categorical,
DataFrame,
@@ -792,22 +793,29 @@ def test_setitem_slice_position(self):
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc])
- @pytest.mark.parametrize("box", [Series, np.array, list])
+ @pytest.mark.parametrize("box", [Series, np.array, list, pd.array])
@pytest.mark.parametrize("n", [1, 2, 3])
- def test_setitem_broadcasting_rhs(self, n, box, indexer):
+ def test_setitem_slice_indexer_broadcasting_rhs(self, n, box, indexer):
# GH#40440
- # TODO: Add pandas array as box after GH#40933 is fixed
df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"])
indexer(df)[1:] = box([10, 11, 12])
expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"])
tm.assert_frame_equal(df, expected)
+ @pytest.mark.parametrize("box", [Series, np.array, list, pd.array])
+ @pytest.mark.parametrize("n", [1, 2, 3])
+ def test_setitem_list_indexer_broadcasting_rhs(self, n, box):
+ # GH#40440
+ df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"])
+ df.iloc[list(range(1, n + 1))] = box([10, 11, 12])
+ expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"])
+ tm.assert_frame_equal(df, expected)
+
@pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc])
- @pytest.mark.parametrize("box", [Series, np.array, list])
+ @pytest.mark.parametrize("box", [Series, np.array, list, pd.array])
@pytest.mark.parametrize("n", [1, 2, 3])
- def test_setitem_broadcasting_rhs_mixed_dtypes(self, n, box, indexer):
+ def test_setitem_slice_broadcasting_rhs_mixed_dtypes(self, n, box, indexer):
# GH#40440
- # TODO: Add pandas array as box after GH#40933 is fixed
df = DataFrame(
[[1, 3, 5], ["x", "y", "z"]] + [[2, 4, 6]] * n, columns=["a", "b", "c"]
)
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index ad0d4245d58c3..446b616111e9e 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -122,7 +122,11 @@ def test_iloc_setitem_ea_inplace(self, frame_or_series, box, using_array_manager
else:
values = obj[0].values
- obj.iloc[:2] = box(arr[2:])
+ if frame_or_series is Series:
+ obj.iloc[:2] = box(arr[2:])
+ else:
+ obj.iloc[:2, 0] = box(arr[2:])
+
expected = frame_or_series(np.array([3, 4, 3, 4], dtype="i8"))
tm.assert_equal(obj, expected)
| - [x] closes #40933
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
This is more or less a follow up of #39040, so don't think we need a whatsnew? | https://api.github.com/repos/pandas-dev/pandas/pulls/41288 | 2021-05-03T19:08:19Z | 2021-05-05T12:41:14Z | 2021-05-05T12:41:13Z | 2021-05-05T19:51:11Z |
REF: Avoid fallback in GroupBy._agg_general | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 4f60660dfb499..396fb0a32b2e8 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1230,6 +1230,24 @@ def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame:
return self.obj._constructor(result, columns=result_columns)
def _wrap_applied_output(self, data, keys, values, not_indexed_same=False):
+ # Note: `data` is _usually_ self._selected_obj or self._obj_with_exclusions
+
+ # TODO: write this case in a more principled manner; ATM it is written
+ # just to pass the one relevant test
+ if self.ndim == data.ndim == 1 and len(keys) == 0:
+ # corner case where self._selected_obj is a Series
+ # reached in test_groupby_as_index_select_column_sum_empty_df
+ res_ser = self.obj._constructor_sliced(
+ values,
+ index=self.grouper.result_index,
+ name=data.name,
+ dtype=data.dtype,
+ )
+ result = res_ser.to_frame()
+ if not self.as_index:
+ self._insert_inaxis_grouper_inplace(result)
+ return result
+
if len(keys) == 0:
result = self.obj._constructor(
index=self.grouper.result_index, columns=data.columns
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 620668dadc32d..35d6b77bf8929 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1296,21 +1296,34 @@ def _agg_general(
npfunc: Callable,
):
with group_selection_context(self):
- # try a cython aggregation if we can
- result = None
- try:
- result = self._cython_agg_general(
- how=alias,
- alt=npfunc,
- numeric_only=numeric_only,
- min_count=min_count,
- )
- except DataError:
- pass
+ sso = self._selected_obj
+
+ # Note: self.ndim can be one for DataFrameGroupBy in corner cases
+ if self.ndim == 1 and numeric_only and not is_numeric_dtype(sso.dtype):
+ # _cython_agg_general would raise DataError
+ # Note: this is equivalent to the self.aggregate call below,
+ # but skips some unnecessary checks.
+ result = self._python_agg_general(npfunc)
+ return result.__finalize__(self.obj, method="groupby")
+
+ if self.ndim == 2:
+
+ mgr = self._get_data_to_aggregate()
+ if numeric_only:
+ mgr = mgr.get_numeric_data(copy=False)
+
+ if mgr.shape[0] == 0:
+ # _cython_agg_general would raise DataError
+ result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
+ return result.__finalize__(self.obj, method="groupby")
+
+ result = self._cython_agg_general(
+ how=alias,
+ alt=npfunc,
+ numeric_only=numeric_only,
+ min_count=min_count,
+ )
- # apply a non-cython aggregation
- if result is None:
- result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
return result.__finalize__(self.obj, method="groupby")
def _cython_agg_general(
| pre-emptively use non-cython path in explicit cases instead of try/except. Many of the affected cases involve empty DataFrames and I think the tested behavior is sketchy (e.g. the fallback paths ignore the `numeric_only` kwarg), so putting this in draft mode while I look at that.
@WillAyd can i get your help with _wrap_applied_output here? As commented, the added case is pretty much a kludge and I think we can do better. Am I remembering correctly that you refactored a bunch of the wrapping code ~18 months ago? | https://api.github.com/repos/pandas-dev/pandas/pulls/41287 | 2021-05-03T18:03:10Z | 2021-05-06T15:35:27Z | null | 2021-05-06T15:35:35Z |
DOC: Fix docs in pandas/io/excel/* | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 149e10b48933d..8e876eebf93ad 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -15,7 +15,7 @@
# $ ./ci/code_checks.sh code # checks on imported code
# $ ./ci/code_checks.sh doctests # run doctests
# $ ./ci/code_checks.sh docstrings # validate docstring errors
-# $ ./ci/code_checks.sh typing # run static type analysis
+# $ ./ci/code_checks.sh typing # run static type analysis
[[ -z "$1" || "$1" == "lint" || "$1" == "patterns" || "$1" == "code" || "$1" == "doctests" || "$1" == "docstrings" || "$1" == "typing" ]] || \
{ echo "Unknown command $1. Usage: $0 [lint|patterns|code|doctests|docstrings|typing]"; exit 9999; }
@@ -140,6 +140,7 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
pandas/core/window/ \
pandas/errors/ \
pandas/io/clipboard/ \
+ pandas/io/excel/ \
pandas/io/parsers/ \
pandas/io/sas/ \
pandas/tseries/
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 3c9dd90c0a0cb..d26a991ba2820 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -707,30 +707,45 @@ class ExcelWriter(metaclass=abc.ABCMeta):
--------
Default usage:
- >>> with ExcelWriter('path_to_file.xlsx') as writer:
+ >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
+ >>> with ExcelWriter("path_to_file.xlsx") as writer:
... df.to_excel(writer)
To write to separate sheets in a single file:
- >>> with ExcelWriter('path_to_file.xlsx') as writer:
- ... df1.to_excel(writer, sheet_name='Sheet1')
- ... df2.to_excel(writer, sheet_name='Sheet2')
+ >>> df1 = pd.DataFrame([["AAA", "BBB"]], columns=["Spam", "Egg"])
+ >>> df2 = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
+ >>> with ExcelWriter("path_to_file.xlsx") as writer:
+ ... df1.to_excel(writer, sheet_name="Sheet1")
+ ... df2.to_excel(writer, sheet_name="Sheet2")
You can set the date format or datetime format:
- >>> with ExcelWriter('path_to_file.xlsx',
- ... date_format='YYYY-MM-DD',
- ... datetime_format='YYYY-MM-DD HH:MM:SS') as writer:
+ >>> from datetime import date, datetime
+ >>> df = pd.DataFrame(
+ ... [
+ ... [date(2014, 1, 31), date(1999, 9, 24)],
+ ... [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)],
+ ... ],
+ ... index=["Date", "Datetime"],
+ ... columns=["X", "Y"],
+ ... )
+ >>> with ExcelWriter(
+ ... "path_to_file.xlsx",
+ ... date_format="YYYY-MM-DD",
+ ... datetime_format="YYYY-MM-DD HH:MM:SS"
+ ... ) as writer:
... df.to_excel(writer)
You can also append to an existing Excel file:
- >>> with ExcelWriter('path_to_file.xlsx', mode='a') as writer:
- ... df.to_excel(writer, sheet_name='Sheet3')
+ >>> with ExcelWriter("path_to_file.xlsx", mode="a", engine="openpyxl") as writer:
+ ... df.to_excel(writer, sheet_name="Sheet3")
You can store Excel file in RAM:
>>> import io
+ >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
>>> buffer = io.BytesIO()
>>> with pd.ExcelWriter(buffer) as writer:
... df.to_excel(writer)
@@ -738,8 +753,9 @@ class ExcelWriter(metaclass=abc.ABCMeta):
You can pack Excel file into zip archive:
>>> import zipfile
- >>> with zipfile.ZipFile('path_to_file.zip', 'w') as zf:
- ... with zf.open('filename.xlsx', 'w') as buffer:
+ >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
+ >>> with zipfile.ZipFile("path_to_file.zip", "w") as zf:
+ ... with zf.open("filename.xlsx", "w") as buffer:
... with pd.ExcelWriter(buffer) as writer:
... df.to_excel(writer)
"""
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/41286 | 2021-05-03T16:23:40Z | 2021-05-04T12:50:12Z | 2021-05-04T12:50:12Z | 2021-05-04T13:50:41Z |
TYP: core.sorting | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 8e12a8cb18b68..50837e1b3ed50 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -6146,7 +6146,7 @@ def duplicated(
if self.empty:
return self._constructor_sliced(dtype=bool)
- def f(vals):
+ def f(vals) -> tuple[np.ndarray, int]:
labels, shape = algorithms.factorize(vals, size_hint=len(self))
return labels.astype("i8", copy=False), len(shape)
@@ -6173,7 +6173,14 @@ def f(vals):
vals = (col.values for name, col in self.items() if name in subset)
labels, shape = map(list, zip(*map(f, vals)))
- ids = get_group_index(labels, shape, sort=False, xnull=False)
+ ids = get_group_index(
+ labels,
+ # error: Argument 1 to "tuple" has incompatible type "List[_T]";
+ # expected "Iterable[int]"
+ tuple(shape), # type: ignore[arg-type]
+ sort=False,
+ xnull=False,
+ )
result = self._constructor_sliced(duplicated_int64(ids, keep), index=self.index)
return result.__finalize__(self, method="duplicated")
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 794f13bbfb6b1..3ddb5b1248060 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1611,7 +1611,7 @@ def _inferred_type_levels(self) -> list[str]:
@doc(Index.duplicated)
def duplicated(self, keep="first") -> np.ndarray:
- shape = map(len, self.levels)
+ shape = tuple(len(lev) for lev in self.levels)
ids = get_group_index(self.codes, shape, sort=False, xnull=False)
return duplicated_int64(ids, keep)
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index d1e076da9293d..037fe5366255a 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -142,7 +142,7 @@ def _indexer_and_to_sort(
codes = list(self.index.codes)
levs = list(self.index.levels)
to_sort = codes[:v] + codes[v + 1 :] + [codes[v]]
- sizes = [len(x) for x in levs[:v] + levs[v + 1 :] + [levs[v]]]
+ sizes = tuple(len(x) for x in levs[:v] + levs[v + 1 :] + [levs[v]])
comp_index, obs_ids = get_compressed_ids(to_sort, sizes)
ngroups = len(obs_ids)
@@ -166,7 +166,7 @@ def _make_selectors(self):
# make the mask
remaining_labels = self.sorted_labels[:-1]
- level_sizes = [len(x) for x in new_levels]
+ level_sizes = tuple(len(x) for x in new_levels)
comp_index, obs_ids = get_compressed_ids(remaining_labels, level_sizes)
ngroups = len(obs_ids)
@@ -353,7 +353,7 @@ def _unstack_multiple(data, clocs, fill_value=None):
rcodes = [index.codes[i] for i in rlocs]
rnames = [index.names[i] for i in rlocs]
- shape = [len(x) for x in clevels]
+ shape = tuple(len(x) for x in clevels)
group_index = get_group_index(ccodes, shape, sort=False, xnull=False)
comp_ids, obs_ids = compress_group_index(group_index, sort=False)
diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py
index f5cd390f077a6..f6c1afbde0bd9 100644
--- a/pandas/core/sorting.py
+++ b/pandas/core/sorting.py
@@ -18,7 +18,10 @@
lib,
)
from pandas._libs.hashtable import unique_label_indices
-from pandas._typing import IndexKeyFunc
+from pandas._typing import (
+ IndexKeyFunc,
+ Shape,
+)
from pandas.core.dtypes.common import (
ensure_int64,
@@ -93,7 +96,7 @@ def get_indexer_indexer(
return indexer
-def get_group_index(labels, shape, sort: bool, xnull: bool):
+def get_group_index(labels, shape: Shape, sort: bool, xnull: bool):
"""
For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
@@ -108,7 +111,7 @@ def get_group_index(labels, shape, sort: bool, xnull: bool):
----------
labels : sequence of arrays
Integers identifying levels at each location
- shape : sequence of ints
+ shape : tuple[int, ...]
Number of unique levels at each location
sort : bool
If the ranks of returned ids should match lexical ranks of labels
@@ -134,33 +137,36 @@ def _int64_cut_off(shape) -> int:
return i
return len(shape)
- def maybe_lift(lab, size):
+ def maybe_lift(lab, size) -> tuple[np.ndarray, int]:
# promote nan values (assigned -1 label in lab array)
# so that all output values are non-negative
return (lab + 1, size + 1) if (lab == -1).any() else (lab, size)
- labels = map(ensure_int64, labels)
+ labels = [ensure_int64(x) for x in labels]
+ lshape = list(shape)
if not xnull:
- labels, shape = map(list, zip(*map(maybe_lift, labels, shape)))
+ for i, (lab, size) in enumerate(zip(labels, shape)):
+ lab, size = maybe_lift(lab, size)
+ labels[i] = lab
+ lshape[i] = size
labels = list(labels)
- shape = list(shape)
# Iteratively process all the labels in chunks sized so less
# than _INT64_MAX unique int ids will be required for each chunk
while True:
# how many levels can be done without overflow:
- nlev = _int64_cut_off(shape)
+ nlev = _int64_cut_off(lshape)
# compute flat ids for the first `nlev` levels
- stride = np.prod(shape[1:nlev], dtype="i8")
+ stride = np.prod(lshape[1:nlev], dtype="i8")
out = stride * labels[0].astype("i8", subok=False, copy=False)
for i in range(1, nlev):
- if shape[i] == 0:
- stride = 0
+ if lshape[i] == 0:
+ stride = np.int64(0)
else:
- stride //= shape[i]
+ stride //= lshape[i]
out += labels[i] * stride
if xnull: # exclude nulls
@@ -169,7 +175,7 @@ def maybe_lift(lab, size):
mask |= lab == -1
out[mask] = -1
- if nlev == len(shape): # all levels done!
+ if nlev == len(lshape): # all levels done!
break
# compress what has been done so far in order to avoid overflow
@@ -177,12 +183,12 @@ def maybe_lift(lab, size):
comp_ids, obs_ids = compress_group_index(out, sort=sort)
labels = [comp_ids] + labels[nlev:]
- shape = [len(obs_ids)] + shape[nlev:]
+ lshape = [len(obs_ids)] + lshape[nlev:]
return out
-def get_compressed_ids(labels, sizes) -> tuple[np.ndarray, np.ndarray]:
+def get_compressed_ids(labels, sizes: Shape) -> tuple[np.ndarray, np.ndarray]:
"""
Group_index is offsets into cartesian product of all possible labels. This
space can be huge, so this function compresses it, by computing offsets
@@ -191,7 +197,7 @@ def get_compressed_ids(labels, sizes) -> tuple[np.ndarray, np.ndarray]:
Parameters
----------
labels : list of label arrays
- sizes : list of size of the levels
+ sizes : tuple[int] of size of the levels
Returns
-------
@@ -252,12 +258,11 @@ def decons_obs_group_ids(comp_ids: np.ndarray, obs_ids, shape, labels, xnull: bo
return out if xnull or not lift.any() else [x - y for x, y in zip(out, lift)]
# TODO: unique_label_indices only used here, should take ndarray[np.intp]
- i = unique_label_indices(ensure_int64(comp_ids))
- i8copy = lambda a: a.astype("i8", subok=False, copy=True)
- return [i8copy(lab[i]) for lab in labels]
+ indexer = unique_label_indices(ensure_int64(comp_ids))
+ return [lab[indexer].astype(np.intp, subok=False, copy=True) for lab in labels]
-def indexer_from_factorized(labels, shape, compress: bool = True) -> np.ndarray:
+def indexer_from_factorized(labels, shape: Shape, compress: bool = True) -> np.ndarray:
# returned ndarray is np.intp
ids = get_group_index(labels, shape, sort=True, xnull=False)
@@ -334,7 +339,7 @@ def lexsort_indexer(
shape.append(n)
labels.append(codes)
- return indexer_from_factorized(labels, shape)
+ return indexer_from_factorized(labels, tuple(shape))
def nargsort(
@@ -576,7 +581,7 @@ def get_indexer_dict(
"""
shape = [len(x) for x in keys]
- group_index = get_group_index(label_list, shape, sort=True, xnull=True)
+ group_index = get_group_index(label_list, tuple(shape), sort=True, xnull=True)
if np.all(group_index == -1):
# Short-circuit, lib.indices_fast will return the same
return {}
| both mypy and i have a hard time with `labels, lshape = map(list, zip(*map(maybe_lift, labels, lshape)))` | https://api.github.com/repos/pandas-dev/pandas/pulls/41285 | 2021-05-03T15:16:39Z | 2021-05-04T12:58:41Z | 2021-05-04T12:58:41Z | 2021-05-04T14:00:12Z |
DOC: Fix docs for io/json/* | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 8e876eebf93ad..7cc171330e01a 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -140,6 +140,7 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
pandas/core/window/ \
pandas/errors/ \
pandas/io/clipboard/ \
+ pandas/io/json/ \
pandas/io/excel/ \
pandas/io/parsers/ \
pandas/io/sas/ \
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index b7493ebeadf34..259850e9a7233 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -526,9 +526,13 @@ def read_json(
Encoding/decoding a Dataframe using ``'split'`` formatted JSON:
>>> df.to_json(orient='split')
- '{{"columns":["col 1","col 2"],
- "index":["row 1","row 2"],
- "data":[["a","b"],["c","d"]]}}'
+ '\
+{{\
+"columns":["col 1","col 2"],\
+"index":["row 1","row 2"],\
+"data":[["a","b"],["c","d"]]\
+}}\
+'
>>> pd.read_json(_, orient='split')
col 1 col 2
row 1 a b
@@ -538,6 +542,7 @@ def read_json(
>>> df.to_json(orient='index')
'{{"row 1":{{"col 1":"a","col 2":"b"}},"row 2":{{"col 1":"c","col 2":"d"}}}}'
+
>>> pd.read_json(_, orient='index')
col 1 col 2
row 1 a b
@@ -556,13 +561,18 @@ def read_json(
Encoding with Table Schema
>>> df.to_json(orient='table')
- '{{"schema": {{"fields": [{{"name": "index", "type": "string"}},
- {{"name": "col 1", "type": "string"}},
- {{"name": "col 2", "type": "string"}}],
- "primaryKey": "index",
- "pandas_version": "0.20.0"}},
- "data": [{{"index": "row 1", "col 1": "a", "col 2": "b"}},
- {{"index": "row 2", "col 1": "c", "col 2": "d"}}]}}'
+ '\
+{{"schema":{{"fields":[\
+{{"name":"index","type":"string"}},\
+{{"name":"col 1","type":"string"}},\
+{{"name":"col 2","type":"string"}}],\
+"primaryKey":["index"],\
+"pandas_version":"0.20.0"}},\
+"data":[\
+{{"index":"row 1","col 1":"a","col 2":"b"}},\
+{{"index":"row 2","col 1":"c","col 2":"d"}}]\
+}}\
+'
"""
if orient == "table" and dtype:
raise ValueError("cannot pass both dtype and orient='table'")
diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py
index 3d07b9d98f9a9..5927d6482d3b0 100644
--- a/pandas/io/json/_normalize.py
+++ b/pandas/io/json/_normalize.py
@@ -70,15 +70,17 @@ def nested_to_record(
Examples
--------
- IN[52]: nested_to_record(dict(flat1=1,dict1=dict(c=1,d=2),
- nested=dict(e=dict(c=1,d=2),d=2)))
- Out[52]:
- {'dict1.c': 1,
- 'dict1.d': 2,
- 'flat1': 1,
- 'nested.d': 2,
- 'nested.e.c': 1,
- 'nested.e.d': 2}
+ >>> nested_to_record(
+ ... dict(flat1=1, dict1=dict(c=1, d=2), nested=dict(e=dict(c=1, d=2), d=2))
+ ... )
+ {\
+'flat1': 1, \
+'dict1.c': 1, \
+'dict1.d': 2, \
+'nested.e.c': 1, \
+'nested.e.d': 2, \
+'nested.d': 2\
+}
"""
singleton = False
if isinstance(ds, dict):
@@ -208,18 +210,21 @@ def _simple_json_normalize(
Examples
--------
- IN[52]: _simple_json_normalize({
- 'flat1': 1,
- 'dict1': {'c': 1, 'd': 2},
- 'nested': {'e': {'c': 1, 'd': 2}, 'd': 2}
- })
- Out[52]:
- {'dict1.c': 1,
- 'dict1.d': 2,
- 'flat1': 1,
- 'nested.d': 2,
- 'nested.e.c': 1,
- 'nested.e.d': 2}
+ >>> _simple_json_normalize(
+ ... {
+ ... "flat1": 1,
+ ... "dict1": {"c": 1, "d": 2},
+ ... "nested": {"e": {"c": 1, "d": 2}, "d": 2},
+ ... }
+ ... )
+ {\
+'flat1': 1, \
+'dict1.c': 1, \
+'dict1.d': 2, \
+'nested.e.c': 1, \
+'nested.e.d': 2, \
+'nested.d': 2\
+}
"""
normalised_json_object = {}
@@ -283,22 +288,30 @@ def _json_normalize(
Examples
--------
- >>> data = [{'id': 1, 'name': {'first': 'Coleen', 'last': 'Volk'}},
- ... {'name': {'given': 'Mark', 'family': 'Regner'}},
- ... {'id': 2, 'name': 'Faye Raker'}]
+ >>> data = [
+ ... {"id": 1, "name": {"first": "Coleen", "last": "Volk"}},
+ ... {"name": {"given": "Mark", "family": "Regner"}},
+ ... {"id": 2, "name": "Faye Raker"},
+ ... ]
>>> pd.json_normalize(data)
id name.first name.last name.given name.family name
0 1.0 Coleen Volk NaN NaN NaN
1 NaN NaN NaN Mark Regner NaN
2 2.0 NaN NaN NaN NaN Faye Raker
- >>> data = [{'id': 1,
- ... 'name': "Cole Volk",
- ... 'fitness': {'height': 130, 'weight': 60}},
- ... {'name': "Mark Reg",
- ... 'fitness': {'height': 130, 'weight': 60}},
- ... {'id': 2, 'name': 'Faye Raker',
- ... 'fitness': {'height': 130, 'weight': 60}}]
+ >>> data = [
+ ... {
+ ... "id": 1,
+ ... "name": "Cole Volk",
+ ... "fitness": {"height": 130, "weight": 60},
+ ... },
+ ... {"name": "Mark Reg", "fitness": {"height": 130, "weight": 60}},
+ ... {
+ ... "id": 2,
+ ... "name": "Faye Raker",
+ ... "fitness": {"height": 130, "weight": 60},
+ ... },
+ ... ]
>>> pd.json_normalize(data, max_level=0)
id name fitness
0 1.0 Cole Volk {'height': 130, 'weight': 60}
@@ -307,32 +320,49 @@ def _json_normalize(
Normalizes nested data up to level 1.
- >>> data = [{'id': 1,
- ... 'name': "Cole Volk",
- ... 'fitness': {'height': 130, 'weight': 60}},
- ... {'name': "Mark Reg",
- ... 'fitness': {'height': 130, 'weight': 60}},
- ... {'id': 2, 'name': 'Faye Raker',
- ... 'fitness': {'height': 130, 'weight': 60}}]
+ >>> data = [
+ ... {
+ ... "id": 1,
+ ... "name": "Cole Volk",
+ ... "fitness": {"height": 130, "weight": 60},
+ ... },
+ ... {"name": "Mark Reg", "fitness": {"height": 130, "weight": 60}},
+ ... {
+ ... "id": 2,
+ ... "name": "Faye Raker",
+ ... "fitness": {"height": 130, "weight": 60},
+ ... },
+ ... ]
>>> pd.json_normalize(data, max_level=1)
id name fitness.height fitness.weight
0 1.0 Cole Volk 130 60
1 NaN Mark Reg 130 60
2 2.0 Faye Raker 130 60
- >>> data = [{'state': 'Florida',
- ... 'shortname': 'FL',
- ... 'info': {'governor': 'Rick Scott'},
- ... 'counties': [{'name': 'Dade', 'population': 12345},
- ... {'name': 'Broward', 'population': 40000},
- ... {'name': 'Palm Beach', 'population': 60000}]},
- ... {'state': 'Ohio',
- ... 'shortname': 'OH',
- ... 'info': {'governor': 'John Kasich'},
- ... 'counties': [{'name': 'Summit', 'population': 1234},
- ... {'name': 'Cuyahoga', 'population': 1337}]}]
- >>> result = pd.json_normalize(data, 'counties', ['state', 'shortname',
- ... ['info', 'governor']])
+ >>> data = [
+ ... {
+ ... "state": "Florida",
+ ... "shortname": "FL",
+ ... "info": {"governor": "Rick Scott"},
+ ... "counties": [
+ ... {"name": "Dade", "population": 12345},
+ ... {"name": "Broward", "population": 40000},
+ ... {"name": "Palm Beach", "population": 60000},
+ ... ],
+ ... },
+ ... {
+ ... "state": "Ohio",
+ ... "shortname": "OH",
+ ... "info": {"governor": "John Kasich"},
+ ... "counties": [
+ ... {"name": "Summit", "population": 1234},
+ ... {"name": "Cuyahoga", "population": 1337},
+ ... ],
+ ... },
+ ... ]
+ >>> result = pd.json_normalize(
+ ... data, "counties", ["state", "shortname", ["info", "governor"]]
+ ... )
>>> result
name population state shortname info.governor
0 Dade 12345 Florida FL Rick Scott
@@ -341,8 +371,8 @@ def _json_normalize(
3 Summit 1234 Ohio OH John Kasich
4 Cuyahoga 1337 Ohio OH John Kasich
- >>> data = {'A': [1, 2]}
- >>> pd.json_normalize(data, 'A', record_prefix='Prefix.')
+ >>> data = {"A": [1, 2]}
+ >>> pd.json_normalize(data, "A", record_prefix="Prefix.")
Prefix.0
0 1
1 2
diff --git a/pandas/io/json/_table_schema.py b/pandas/io/json/_table_schema.py
index ea47dca4f079e..87ea109c20f43 100644
--- a/pandas/io/json/_table_schema.py
+++ b/pandas/io/json/_table_schema.py
@@ -155,21 +155,25 @@ def convert_json_field_to_pandas_type(field):
Examples
--------
- >>> convert_json_field_to_pandas_type({'name': 'an_int',
- 'type': 'integer'})
+ >>> convert_json_field_to_pandas_type({"name": "an_int", "type": "integer"})
'int64'
- >>> convert_json_field_to_pandas_type({'name': 'a_categorical',
- 'type': 'any',
- 'constraints': {'enum': [
- 'a', 'b', 'c']},
- 'ordered': True})
- 'CategoricalDtype(categories=['a', 'b', 'c'], ordered=True)'
- >>> convert_json_field_to_pandas_type({'name': 'a_datetime',
- 'type': 'datetime'})
+
+ >>> convert_json_field_to_pandas_type(
+ ... {
+ ... "name": "a_categorical",
+ ... "type": "any",
+ ... "constraints": {"enum": ["a", "b", "c"]},
+ ... "ordered": True,
+ ... }
+ ... )
+ CategoricalDtype(categories=['a', 'b', 'c'], ordered=True)
+
+ >>> convert_json_field_to_pandas_type({"name": "a_datetime", "type": "datetime"})
'datetime64[ns]'
- >>> convert_json_field_to_pandas_type({'name': 'a_datetime_with_tz',
- 'type': 'datetime',
- 'tz': 'US/Central'})
+
+ >>> convert_json_field_to_pandas_type(
+ ... {"name": "a_datetime_with_tz", "type": "datetime", "tz": "US/Central"}
+ ... )
'datetime64[ns, US/Central]'
"""
typ = field["type"]
@@ -245,12 +249,13 @@ def build_table_schema(
... 'C': pd.date_range('2016-01-01', freq='d', periods=3),
... }, index=pd.Index(range(3), name='idx'))
>>> build_table_schema(df)
- {'fields': [{'name': 'idx', 'type': 'integer'},
- {'name': 'A', 'type': 'integer'},
- {'name': 'B', 'type': 'string'},
- {'name': 'C', 'type': 'datetime'}],
- 'pandas_version': '0.20.0',
- 'primaryKey': ['idx']}
+ {'fields': \
+[{'name': 'idx', 'type': 'integer'}, \
+{'name': 'A', 'type': 'integer'}, \
+{'name': 'B', 'type': 'string'}, \
+{'name': 'C', 'type': 'datetime'}], \
+'primaryKey': ['idx'], \
+'pandas_version': '0.20.0'}
"""
if index is True:
data = set_default_names(data)
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/41284 | 2021-05-03T15:08:39Z | 2021-05-04T21:55:08Z | 2021-05-04T21:55:08Z | 2021-05-05T12:13:24Z |
TYP Series and DataFrame currently type-check as hashable | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 0641b32383125..60dc7096c9d1e 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -707,6 +707,7 @@ Other API changes
- Added new ``engine`` and ``**engine_kwargs`` parameters to :meth:`DataFrame.to_sql` to support other future "SQL engines". Currently we still only use ``SQLAlchemy`` under the hood, but more engines are planned to be supported such as `turbodbc <https://turbodbc.readthedocs.io/en/latest/>`_ (:issue:`36893`)
- Removed redundant ``freq`` from :class:`PeriodIndex` string representation (:issue:`41653`)
- :meth:`ExtensionDtype.construct_array_type` is now a required method instead of an optional one for :class:`ExtensionDtype` subclasses (:issue:`24860`)
+- Calling ``hash`` on non-hashable pandas objects will now raise ``TypeError`` with the built-in error message (e.g. ``unhashable type: 'Series'``). Previously it would raise a custom message such as ``'Series' objects are mutable, thus they cannot be hashed``. Furthermore, ``isinstance(<Series>, abc.collections.Hashable)`` will now return ``False`` (:issue:`40013`)
- :meth:`.Styler.from_custom_template` now has two new arguments for template names, and removed the old ``name``, due to template inheritance having been introducing for better parsing (:issue:`42053`). Subclassing modifications to Styler attributes are also needed.
.. _whatsnew_130.api_breaking.build:
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 888c7cbbffb59..96bd4280f4da4 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -1296,8 +1296,10 @@ def _reduce(self, name: str, *, skipna: bool = True, **kwargs):
"""
raise TypeError(f"cannot perform {name} with type {self.dtype}")
- def __hash__(self) -> int:
- raise TypeError(f"unhashable type: {repr(type(self).__name__)}")
+ # https://github.com/python/typeshed/issues/2148#issuecomment-520783318
+ # Incompatible types in assignment (expression has type "None", base class
+ # "object" defined the type as "Callable[[object], int]")
+ __hash__: None # type: ignore[assignment]
# ------------------------------------------------------------------------
# Non-Optimized Default Methods
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 7432aa90afbc2..6f621699aa5ae 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -6180,7 +6180,10 @@ def f(vals) -> tuple[np.ndarray, int]:
return labels.astype("i8", copy=False), len(shape)
if subset is None:
- subset = self.columns
+ # Incompatible types in assignment
+ # (expression has type "Index", variable has type "Sequence[Any]")
+ # (pending on https://github.com/pandas-dev/pandas/issues/28770)
+ subset = self.columns # type: ignore[assignment]
elif (
not np.iterable(subset)
or isinstance(subset, str)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 82895ab9eb67a..c052b977ea07a 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1874,11 +1874,10 @@ def _drop_labels_or_levels(self, keys, axis: int = 0):
# ----------------------------------------------------------------------
# Iteration
- def __hash__(self) -> int:
- raise TypeError(
- f"{repr(type(self).__name__)} objects are mutable, "
- f"thus they cannot be hashed"
- )
+ # https://github.com/python/typeshed/issues/2148#issuecomment-520783318
+ # Incompatible types in assignment (expression has type "None", base class
+ # "object" defined the type as "Callable[[object], int]")
+ __hash__: None # type: ignore[assignment]
def __iter__(self):
"""
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 7b7b234a06eca..3cfa1f15fa118 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4604,9 +4604,10 @@ def __contains__(self, key: Any) -> bool:
except (OverflowError, TypeError, ValueError):
return False
- @final
- def __hash__(self):
- raise TypeError(f"unhashable type: {repr(type(self).__name__)}")
+ # https://github.com/python/typeshed/issues/2148#issuecomment-520783318
+ # Incompatible types in assignment (expression has type "None", base class
+ # "object" defined the type as "Callable[[object], int]")
+ __hash__: None # type: ignore[assignment]
@final
def __setitem__(self, key, value):
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index 51556fda6da04..7a5c2677307e2 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -482,7 +482,7 @@ def pivot(
if columns is None:
raise TypeError("pivot() missing 1 required argument: 'columns'")
- columns = com.convert_to_list_like(columns)
+ columns_listlike = com.convert_to_list_like(columns)
if values is None:
if index is not None:
@@ -494,28 +494,27 @@ def pivot(
# error: Unsupported operand types for + ("List[Any]" and "ExtensionArray")
# error: Unsupported left operand type for + ("ExtensionArray")
indexed = data.set_index(
- cols + columns, append=append # type: ignore[operator]
+ cols + columns_listlike, append=append # type: ignore[operator]
)
else:
if index is None:
- index = [Series(data.index, name=data.index.name)]
+ index_list = [Series(data.index, name=data.index.name)]
else:
- index = com.convert_to_list_like(index)
- index = [data[idx] for idx in index]
+ index_list = [data[idx] for idx in com.convert_to_list_like(index)]
- data_columns = [data[col] for col in columns]
- index.extend(data_columns)
- index = MultiIndex.from_arrays(index)
+ data_columns = [data[col] for col in columns_listlike]
+ index_list.extend(data_columns)
+ multiindex = MultiIndex.from_arrays(index_list)
if is_list_like(values) and not isinstance(values, tuple):
# Exclude tuple because it is seen as a single column name
values = cast(Sequence[Hashable], values)
indexed = data._constructor(
- data[values]._values, index=index, columns=values
+ data[values]._values, index=multiindex, columns=values
)
else:
- indexed = data._constructor_sliced(data[values]._values, index=index)
- return indexed.unstack(columns)
+ indexed = data._constructor_sliced(data[values]._values, index=multiindex)
+ return indexed.unstack(columns_listlike)
def crosstab(
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 455d51455c456..c79ecd554bed5 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -305,7 +305,6 @@ class Series(base.IndexOpsMixin, generic.NDFrame):
hasnans = property( # type: ignore[assignment]
base.IndexOpsMixin.hasnans.func, doc=base.IndexOpsMixin.hasnans.__doc__
)
- __hash__ = generic.NDFrame.__hash__
_mgr: SingleManager
div: Callable[[Series, Any], Series]
rdiv: Callable[[Series, Any], Series]
diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py
index 76cfd77d254f2..49649c1487f13 100644
--- a/pandas/tests/frame/test_api.py
+++ b/pandas/tests/frame/test_api.py
@@ -91,7 +91,7 @@ def test_not_hashable(self):
empty_frame = DataFrame()
df = DataFrame([1])
- msg = "'DataFrame' objects are mutable, thus they cannot be hashed"
+ msg = "unhashable type: 'DataFrame'"
with pytest.raises(TypeError, match=msg):
hash(df)
with pytest.raises(TypeError, match=msg):
diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py
index eddf57c1e88f3..b49c209a59a06 100644
--- a/pandas/tests/series/test_api.py
+++ b/pandas/tests/series/test_api.py
@@ -101,7 +101,7 @@ def test_index_tab_completion(self, index):
def test_not_hashable(self):
s_empty = Series(dtype=object)
s = Series([1])
- msg = "'Series' objects are mutable, thus they cannot be hashed"
+ msg = "unhashable type: 'Series'"
with pytest.raises(TypeError, match=msg):
hash(s_empty)
with pytest.raises(TypeError, match=msg):
| - [ ] closes #40013
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41283 | 2021-05-03T14:15:01Z | 2021-06-29T12:27:43Z | 2021-06-29T12:27:42Z | 2021-06-29T12:31:30Z |
[ArrowStringArray] PERF: isin using native pyarrow function if available | diff --git a/asv_bench/benchmarks/algos/isin.py b/asv_bench/benchmarks/algos/isin.py
index a8b8a193dbcfc..44245295beafc 100644
--- a/asv_bench/benchmarks/algos/isin.py
+++ b/asv_bench/benchmarks/algos/isin.py
@@ -9,6 +9,8 @@
date_range,
)
+from ..pandas_vb_common import tm
+
class IsIn:
@@ -22,6 +24,9 @@ class IsIn:
"datetime64[ns]",
"category[object]",
"category[int]",
+ "str",
+ "string",
+ "arrow_string",
]
param_names = ["dtype"]
@@ -57,6 +62,15 @@ def setup(self, dtype):
self.values = np.random.choice(arr, sample_size)
self.series = Series(arr).astype("category")
+ elif dtype in ["str", "string", "arrow_string"]:
+ from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
+
+ try:
+ self.series = Series(tm.makeStringIndex(N), dtype=dtype)
+ except ImportError:
+ raise NotImplementedError
+ self.values = list(self.series[:2])
+
else:
self.series = Series(np.random.randint(1, 10, N)).astype(dtype)
self.values = [1, 2]
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 2c4477056a112..c52105b77e4dc 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -468,10 +468,9 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> np.ndarray:
comps = _ensure_arraylike(comps)
comps = extract_array(comps, extract_numpy=True)
- if is_extension_array_dtype(comps.dtype):
- # error: Incompatible return value type (got "Series", expected "ndarray")
- # error: Item "ndarray" of "Union[Any, ndarray]" has no attribute "isin"
- return comps.isin(values) # type: ignore[return-value,union-attr]
+ if not isinstance(comps, np.ndarray):
+ # i.e. Extension Array
+ return comps.isin(values)
elif needs_i8_conversion(comps.dtype):
# Dispatch to DatetimeLikeArrayMixin.isin
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 72a2ab8a1b80a..01813cef97b8d 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -663,6 +663,34 @@ def take(
indices_array[indices_array < 0] += len(self._data)
return type(self)(self._data.take(indices_array))
+ def isin(self, values):
+
+ # pyarrow.compute.is_in added in pyarrow 2.0.0
+ if not hasattr(pc, "is_in"):
+ return super().isin(values)
+
+ value_set = [
+ pa_scalar.as_py()
+ for pa_scalar in [pa.scalar(value, from_pandas=True) for value in values]
+ if pa_scalar.type in (pa.string(), pa.null())
+ ]
+
+ # for an empty value_set pyarrow 3.0.0 segfaults and pyarrow 2.0.0 returns True
+ # for null values, so we short-circuit to return all False array.
+ if not len(value_set):
+ return np.zeros(len(self), dtype=bool)
+
+ kwargs = {}
+ if LooseVersion(pa.__version__) < "3.0.0":
+ # in pyarrow 2.0.0 skip_null is ignored but is a required keyword and raises
+ # with unexpected keyword argument in pyarrow 3.0.0+
+ kwargs["skip_null"] = True
+
+ result = pc.is_in(self._data, value_set=pa.array(value_set), **kwargs)
+ # pyarrow 2.0.0 returned nulls, so we explicily specify dtype to convert nulls
+ # to False
+ return np.array(result, dtype=np.bool_)
+
def value_counts(self, dropna: bool = True) -> Series:
"""
Return a Series containing counts of each unique value.
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index e2d8e522abb35..43ba5667d4d93 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -566,3 +566,23 @@ def test_to_numpy_na_value(dtype, nulls_fixture):
result = arr.to_numpy(na_value=na_value)
expected = np.array(["a", na_value, "b"], dtype=object)
tm.assert_numpy_array_equal(result, expected)
+
+
+def test_isin(dtype, request):
+ s = pd.Series(["a", "b", None], dtype=dtype)
+
+ result = s.isin(["a", "c"])
+ expected = pd.Series([True, False, False])
+ tm.assert_series_equal(result, expected)
+
+ result = s.isin(["a", pd.NA])
+ expected = pd.Series([True, False, True])
+ tm.assert_series_equal(result, expected)
+
+ result = s.isin([])
+ expected = pd.Series([False, False, False])
+ tm.assert_series_equal(result, expected)
+
+ result = s.isin(["a", pd.Timestamp.now()])
+ expected = pd.Series([True, False, False])
+ tm.assert_series_equal(result, expected)
| Unlike MaskedArray, this returns a numpy bool array to be consistent with the EA interface and StringArray and also due to the fact that the returned boolean array has no null values to be consistent with the latest version of pyarrow.
```
[ 0.00%] ·· Benchmarking existing-py_home_simon_miniconda3_envs_pandas-dev_bin_python
[ 4.17%] ··· algos.isin.IsIn.time_isin ok
[ 4.17%] ··· ================== ==========
dtype
------------------ ----------
int64 295±0μs
uint64 348±0μs
object 337±0μs
Int64 785±0μs
boolean 868±0μs
bool 420±0μs
datetime64[ns] 4.67±0ms
category[object] 9.46±0ms
category[int] 7.30±0ms
str 535±0μs
string 556±0μs
arrow_string 330±0μs
================== ==========
[ 8.33%] ··· algos.isin.IsIn.time_isin_categorical ok
[ 8.33%] ··· ================== ==========
dtype
------------------ ----------
int64 374±0μs
uint64 507±0μs
object 467±0μs
Int64 633±0μs
boolean 702±0μs
bool 458±0μs
datetime64[ns] 3.10±0ms
category[object] 10.2±0ms
category[int] 9.12±0ms
str 598±0μs
string 628±0μs
arrow_string 404±0μs
================== ==========
[ 12.50%] ··· algos.isin.IsIn.time_isin_empty ok
[ 12.50%] ··· ================== ==========
dtype
------------------ ----------
int64 275±0μs
uint64 285±0μs
object 390±0μs
Int64 1.06±0ms
boolean 1.14±0ms
bool 280±0μs
datetime64[ns] 295±0μs
category[object] 4.17±0ms
category[int] 3.49±0ms
str 424±0μs
string 718±0μs
arrow_string 140±0μs
================== ==========
[ 16.67%] ··· algos.isin.IsIn.time_isin_mismatched_dtype ok
[ 16.67%] ··· ================== ==========
dtype
------------------ ----------
int64 221±0μs
uint64 216±0μs
object 337±0μs
Int64 337±0μs
boolean 356±0μs
bool 323±0μs
datetime64[ns] 348±0μs
category[object] 4.86±0ms
category[int] 3.47±0ms
str 586±0μs
string 525±0μs
arrow_string 224±0μs
================== ==========
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/41281 | 2021-05-03T12:41:35Z | 2021-05-05T12:50:49Z | 2021-05-05T12:50:49Z | 2021-05-05T12:55:43Z |
CI: Added unselected directories to doctest CI | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index c178e9f7cecbe..149e10b48933d 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -123,6 +123,11 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
MSG='Doctests for directories' ; echo $MSG
pytest -q --doctest-modules \
+ pandas/_libs/ \
+ pandas/api/ \
+ pandas/arrays/ \
+ pandas/compat/ \
+ pandas/core/array_algos/ \
pandas/core/arrays/ \
pandas/core/computation/ \
pandas/core/dtypes/ \
@@ -133,6 +138,10 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
pandas/core/strings/ \
pandas/core/tools/ \
pandas/core/window/ \
+ pandas/errors/ \
+ pandas/io/clipboard/ \
+ pandas/io/parsers/ \
+ pandas/io/sas/ \
pandas/tseries/
RET=$(($RET + $?)) ; echo $MSG "DONE"
| Some of those do have docstrings with example to be validated, and some do not have.
This only make sure that future files or changes to files in those directories will be checked.
---
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/41280 | 2021-05-03T12:23:55Z | 2021-05-03T13:50:14Z | 2021-05-03T13:50:14Z | 2021-05-03T13:53:19Z |
CI: Fix warning from SSL transport (again) | diff --git a/pandas/_testing/_warnings.py b/pandas/_testing/_warnings.py
index b1f070d1a1ccc..5153118e9b142 100644
--- a/pandas/_testing/_warnings.py
+++ b/pandas/_testing/_warnings.py
@@ -143,7 +143,7 @@ def _assert_caught_no_extra_warnings(
for actual_warning in caught_warnings:
if _is_unexpected_warning(actual_warning, expected_warning):
unclosed = "unclosed transport <asyncio.sslproto._SSLProtocolTransport"
- if isinstance(actual_warning, ResourceWarning) and unclosed in str(
+ if actual_warning.category == ResourceWarning and unclosed in str(
actual_warning.message
):
# FIXME: kludge because pytest.filterwarnings does not
| Turns out that the issue was the comparison of the type. Loop has `WarningMessage`, but the type of warning is in `actual_warning.category` | https://api.github.com/repos/pandas-dev/pandas/pulls/41279 | 2021-05-03T12:19:53Z | 2021-05-03T13:49:46Z | 2021-05-03T13:49:46Z | 2021-05-03T13:53:58Z |
TST: fix casting extension tests for external users | diff --git a/pandas/tests/extension/base/casting.py b/pandas/tests/extension/base/casting.py
index 47f4f7585243d..99a5666926e10 100644
--- a/pandas/tests/extension/base/casting.py
+++ b/pandas/tests/extension/base/casting.py
@@ -1,6 +1,8 @@
import numpy as np
import pytest
+import pandas.util._test_decorators as td
+
import pandas as pd
from pandas.core.internals import ObjectBlock
from pandas.tests.extension.base.base import BaseExtensionTests
@@ -43,8 +45,19 @@ def test_astype_str(self, data):
expected = pd.Series([str(x) for x in data[:5]], dtype=str)
self.assert_series_equal(result, expected)
+ @pytest.mark.parametrize(
+ "nullable_string_dtype",
+ [
+ "string",
+ pytest.param(
+ "arrow_string", marks=td.skip_if_no("pyarrow", min_version="1.0.0")
+ ),
+ ],
+ )
def test_astype_string(self, data, nullable_string_dtype):
# GH-33465
+ from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
+
result = pd.Series(data[:5]).astype(nullable_string_dtype)
expected = pd.Series([str(x) for x in data[:5]], dtype=nullable_string_dtype)
self.assert_series_equal(result, expected)
| cc @simonjayhawkins fixtures defined by pandas are not known when inheriting the tests as external package. There are a bunch of fixtures that external packages are expected to define in `pandas/tests/extension/conftest.py`, but I think for the string dtype here this is not worth it to expect downstream users to define it themselves (certainly given that it is still going to change) | https://api.github.com/repos/pandas-dev/pandas/pulls/41278 | 2021-05-03T09:48:43Z | 2021-05-03T14:28:06Z | 2021-05-03T14:28:06Z | 2021-05-03T14:40:34Z |
Allow to union `MultiIndex` with empty `RangeIndex` | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 9b3f2d191831d..ee2ae291cd288 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -2923,8 +2923,10 @@ def union(self, other, sort=None):
other, result_name = self._convert_can_do_setop(other)
if not is_dtype_equal(self.dtype, other.dtype):
- if isinstance(self, ABCMultiIndex) and not is_object_dtype(
- unpack_nested_dtype(other)
+ if (
+ isinstance(self, ABCMultiIndex)
+ and not is_object_dtype(unpack_nested_dtype(other))
+ and len(other) > 0
):
raise NotImplementedError(
"Can only union MultiIndex with MultiIndex or Index of tuples, "
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 794f13bbfb6b1..36c8e818f1a24 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3597,7 +3597,7 @@ def _get_reconciled_name_object(self, other) -> MultiIndex:
def _maybe_match_names(self, other):
"""
Try to find common names to attach to the result of an operation between
- a and b. Return a consensus list of names if they match at least partly
+ a and b. Return a consensus list of names if they match at least partly
or list of None if they have completely different names.
"""
if len(self.names) != len(other.names):
diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py
index 4a170d9cd161f..0b59e832ce3a8 100644
--- a/pandas/tests/indexes/multi/test_setops.py
+++ b/pandas/tests/indexes/multi/test_setops.py
@@ -414,6 +414,18 @@ def test_union_empty_self_different_names():
tm.assert_index_equal(result, expected)
+def test_union_multiindex_empty_rangeindex():
+ # GH#41234
+ mi = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])
+ ri = pd.RangeIndex(0)
+
+ result_left = mi.union(ri)
+ tm.assert_index_equal(mi, result_left, check_names=False)
+
+ result_right = ri.union(mi)
+ tm.assert_index_equal(mi, result_right, check_names=False)
+
+
@pytest.mark.parametrize(
"method", ["union", "intersection", "difference", "symmetric_difference"]
)
diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py
index 2ed38670e88a6..96b88dc61cfed 100644
--- a/pandas/tests/reshape/concat/test_concat.py
+++ b/pandas/tests/reshape/concat/test_concat.py
@@ -627,3 +627,14 @@ def test_concat_null_object_with_dti():
index=exp_index,
)
tm.assert_frame_equal(result, expected)
+
+
+def test_concat_multiindex_with_empty_rangeindex():
+ # GH#41234
+ mi = MultiIndex.from_tuples([("B", 1), ("C", 1)])
+ df1 = DataFrame([[1, 2]], columns=mi)
+ df2 = DataFrame(index=[1], columns=pd.RangeIndex(0))
+
+ result = concat([df1, df2])
+ expected = DataFrame([[1, 2], [np.nan, np.nan]], columns=mi)
+ tm.assert_frame_equal(result, expected)
| - [x] closes #41234
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
See also https://github.com/dask/dask/issues/7610 and https://github.com/JDASoftwareGroup/kartothek/issues/464. The regression seems to have been introduced in pandas-dev/pandas#38671. | https://api.github.com/repos/pandas-dev/pandas/pulls/41275 | 2021-05-03T07:03:01Z | 2021-05-04T12:53:48Z | 2021-05-04T12:53:47Z | 2021-06-02T14:38:08Z |
REF: clearer names in libreduction | diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index d0f85b75a629e..09999b6970bca 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -63,17 +63,17 @@ cdef class _BaseGrouper:
)
return cached_index, cached_series
- cdef inline _update_cached_objs(self, object cached_typ, object cached_ityp,
+ cdef inline _update_cached_objs(self, object cached_series, object cached_index,
Slider islider, Slider vslider):
# See the comment in indexes/base.py about _index_data.
# We need this for EA-backed indexes that have a reference
# to a 1-d ndarray like datetime / timedelta / period.
- cached_ityp._engine.clear_mapping()
- cached_ityp._cache.clear() # e.g. inferred_freq must go
- cached_typ._mgr.set_values(vslider.buf)
+ cached_index._engine.clear_mapping()
+ cached_index._cache.clear() # e.g. inferred_freq must go
+ cached_series._mgr.set_values(vslider.buf)
cdef inline object _apply_to_group(self,
- object cached_typ, object cached_ityp,
+ object cached_series, object cached_index,
bint initialized):
"""
Call self.f on our new group, then update to the next group.
@@ -83,7 +83,7 @@ cdef class _BaseGrouper:
# NB: we assume that _update_cached_objs has already cleared cleared
# the cache and engine mapping
- res = self.f(cached_typ)
+ res = self.f(cached_series)
res = extract_result(res)
if not initialized:
# On the first pass, we check the output shape to see
@@ -140,7 +140,7 @@ cdef class SeriesBinGrouper(_BaseGrouper):
object res
bint initialized = 0
Slider vslider, islider
- object cached_typ = None, cached_ityp = None
+ object cached_series = None, cached_index = None
counts = np.zeros(self.ngroups, dtype=np.int64)
@@ -160,7 +160,9 @@ cdef class SeriesBinGrouper(_BaseGrouper):
result = np.empty(self.ngroups, dtype='O')
- cached_ityp, cached_typ = self._init_dummy_series_and_index(islider, vslider)
+ cached_index, cached_series = self._init_dummy_series_and_index(
+ islider, vslider
+ )
start = 0
try:
@@ -172,9 +174,9 @@ cdef class SeriesBinGrouper(_BaseGrouper):
vslider.move(start, end)
self._update_cached_objs(
- cached_typ, cached_ityp, islider, vslider)
+ cached_series, cached_index, islider, vslider)
- res, initialized = self._apply_to_group(cached_typ, cached_ityp,
+ res, initialized = self._apply_to_group(cached_series, cached_index,
initialized)
start += group_size
@@ -236,7 +238,7 @@ cdef class SeriesGrouper(_BaseGrouper):
object res
bint initialized = 0
Slider vslider, islider
- object cached_typ = None, cached_ityp = None
+ object cached_series = None, cached_index = None
labels = self.labels
counts = np.zeros(self.ngroups, dtype=np.int64)
@@ -248,7 +250,9 @@ cdef class SeriesGrouper(_BaseGrouper):
result = np.empty(self.ngroups, dtype='O')
- cached_ityp, cached_typ = self._init_dummy_series_and_index(islider, vslider)
+ cached_index, cached_series = self._init_dummy_series_and_index(
+ islider, vslider
+ )
start = 0
try:
@@ -268,9 +272,9 @@ cdef class SeriesGrouper(_BaseGrouper):
vslider.move(start, end)
self._update_cached_objs(
- cached_typ, cached_ityp, islider, vslider)
+ cached_series, cached_index, islider, vslider)
- res, initialized = self._apply_to_group(cached_typ, cached_ityp,
+ res, initialized = self._apply_to_group(cached_series, cached_index,
initialized)
start += group_size
@@ -293,20 +297,20 @@ cdef class SeriesGrouper(_BaseGrouper):
return result, counts
-cpdef inline extract_result(object res, bint squeeze=True):
+cpdef inline extract_result(object res):
""" extract the result object, it might be a 0-dim ndarray
or a len-1 0-dim, or a scalar """
if hasattr(res, "_values"):
# Preserve EA
res = res._values
- if squeeze and res.ndim == 1 and len(res) == 1:
+ if res.ndim == 1 and len(res) == 1:
res = res[0]
if hasattr(res, 'values') and is_array(res.values):
res = res.values
if is_array(res):
if res.ndim == 0:
res = res.item()
- elif squeeze and res.ndim == 1 and len(res) == 1:
+ elif res.ndim == 1 and len(res) == 1:
res = res[0]
return res
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41274 | 2021-05-03T01:57:34Z | 2021-05-03T15:15:36Z | 2021-05-03T15:15:36Z | 2021-05-03T16:50:08Z |
REF: consolidate casting in groupby agg_series | diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index d0f85b75a629e..8dcd01b14535f 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -21,10 +21,7 @@ from pandas._libs.util cimport (
set_array_not_contiguous,
)
-from pandas._libs.lib import (
- is_scalar,
- maybe_convert_objects,
-)
+from pandas._libs.lib import is_scalar
cpdef check_result_array(object obj):
@@ -185,7 +182,6 @@ cdef class SeriesBinGrouper(_BaseGrouper):
islider.reset()
vslider.reset()
- result = maybe_convert_objects(result)
return result, counts
@@ -288,8 +284,6 @@ cdef class SeriesGrouper(_BaseGrouper):
# have result initialized by this point.
assert initialized, "`result` has not been initialized."
- result = maybe_convert_objects(result)
-
return result, counts
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 9edbeb412026d..30be9968ad91f 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -970,22 +970,33 @@ def agg_series(self, obj: Series, func: F) -> tuple[ArrayLike, np.ndarray]:
# Caller is responsible for checking ngroups != 0
assert self.ngroups != 0
+ cast_back = True
if len(obj) == 0:
# SeriesGrouper would raise if we were to call _aggregate_series_fast
- return self._aggregate_series_pure_python(obj, func)
+ result, counts = self._aggregate_series_pure_python(obj, func)
elif is_extension_array_dtype(obj.dtype):
# _aggregate_series_fast would raise TypeError when
# calling libreduction.Slider
# In the datetime64tz case it would incorrectly cast to tz-naive
# TODO: can we get a performant workaround for EAs backed by ndarray?
- return self._aggregate_series_pure_python(obj, func)
+ result, counts = self._aggregate_series_pure_python(obj, func)
elif obj.index._has_complex_internals:
# Preempt TypeError in _aggregate_series_fast
- return self._aggregate_series_pure_python(obj, func)
+ result, counts = self._aggregate_series_pure_python(obj, func)
- return self._aggregate_series_fast(obj, func)
+ else:
+ result, counts = self._aggregate_series_fast(obj, func)
+ cast_back = False
+
+ npvalues = lib.maybe_convert_objects(result, try_float=False)
+ if cast_back:
+ # TODO: Is there a documented reason why we dont always cast_back?
+ out = maybe_cast_pointwise_result(npvalues, obj.dtype, numeric_only=True)
+ else:
+ out = npvalues
+ return out, counts
def _aggregate_series_fast(
self, obj: Series, func: F
@@ -1033,10 +1044,7 @@ def _aggregate_series_pure_python(self, obj: Series, func: F):
counts[i] = group.shape[0]
result[i] = res
- npvalues = lib.maybe_convert_objects(result, try_float=False)
- out = maybe_cast_pointwise_result(npvalues, obj.dtype, numeric_only=True)
-
- return out, counts
+ return result, counts
class BinGrouper(BaseGrouper):
diff --git a/pandas/core/series.py b/pandas/core/series.py
index a07a685c2ffde..240f678960969 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -3086,7 +3086,7 @@ def combine(self, other, func, fill_value=None) -> Series:
new_values[:] = [func(lv, other) for lv in self._values]
new_name = self.name
- # try_float=False is to match _aggregate_series_pure_python
+ # try_float=False is to match agg_series
npvalues = lib.maybe_convert_objects(new_values, try_float=False)
res_values = maybe_cast_pointwise_result(npvalues, self.dtype, same_dtype=False)
return self._constructor(res_values, index=new_index, name=new_name)
diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py
index 13fddad30eeba..aa126ae801f1e 100644
--- a/pandas/tests/groupby/test_bin_groupby.py
+++ b/pandas/tests/groupby/test_bin_groupby.py
@@ -20,7 +20,7 @@ def test_series_grouper():
grouper = libreduction.SeriesGrouper(obj, np.mean, labels, 2)
result, counts = grouper.get_result()
- expected = np.array([obj[3:6].mean(), obj[6:].mean()])
+ expected = np.array([obj[3:6].mean(), obj[6:].mean()], dtype=object)
tm.assert_almost_equal(result, expected)
exp_counts = np.array([3, 4], dtype=np.int64)
@@ -36,7 +36,7 @@ def test_series_grouper_result_length_difference():
grouper = libreduction.SeriesGrouper(obj, lambda x: all(x > 0), labels, 2)
result, counts = grouper.get_result()
- expected = np.array([all(obj[3:6] > 0), all(obj[6:] > 0)])
+ expected = np.array([all(obj[3:6] > 0), all(obj[6:] > 0)], dtype=object)
tm.assert_equal(result, expected)
exp_counts = np.array([3, 4], dtype=np.int64)
@@ -61,7 +61,7 @@ def test_series_bin_grouper():
grouper = libreduction.SeriesBinGrouper(obj, np.mean, bins)
result, counts = grouper.get_result()
- expected = np.array([obj[:3].mean(), obj[3:6].mean(), obj[6:].mean()])
+ expected = np.array([obj[:3].mean(), obj[3:6].mean(), obj[6:].mean()], dtype=object)
tm.assert_almost_equal(result, expected)
exp_counts = np.array([3, 3, 4], dtype=np.int64)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41273 | 2021-05-02T21:49:16Z | 2021-05-04T12:52:35Z | 2021-05-04T12:52:35Z | 2021-05-04T14:04:01Z |
REF: simpilify _cython_agg_general | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index b9f1ca0710872..7edd458ced790 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -345,47 +345,48 @@ def _aggregate_multiple_funcs(self, arg):
def _cython_agg_general(
self, how: str, alt=None, numeric_only: bool = True, min_count: int = -1
):
- output: dict[base.OutputKey, ArrayLike] = {}
- # Ideally we would be able to enumerate self._iterate_slices and use
- # the index from enumeration as the key of output, but ohlc in particular
- # returns a (n x 4) array. Output requires 1D ndarrays as values, so we
- # need to slice that up into 1D arrays
- idx = 0
- for obj in self._iterate_slices():
- name = obj.name
- is_numeric = is_numeric_dtype(obj.dtype)
- if numeric_only and not is_numeric:
- continue
-
- objvals = obj._values
- if isinstance(objvals, Categorical):
- if self.grouper.ngroups > 0:
- # without special-casing, we would raise, then in fallback
- # would eventually call agg_series but without re-casting
- # to Categorical
- # equiv: res_values, _ = self.grouper.agg_series(obj, alt)
- res_values, _ = self.grouper._aggregate_series_pure_python(obj, alt)
- else:
- # equiv: res_values = self._python_agg_general(alt)
- res_values = self._python_apply_general(alt, self._selected_obj)
+ obj = self._selected_obj
+ objvals = obj._values
- result = type(objvals)._from_sequence(res_values, dtype=objvals.dtype)
+ if numeric_only and not is_numeric_dtype(obj.dtype):
+ raise DataError("No numeric types to aggregate")
- else:
+ # This is overkill because it is only called once, but is here to
+ # mirror the array_func used in DataFrameGroupBy._cython_agg_general
+ def array_func(values: ArrayLike) -> ArrayLike:
+ try:
result = self.grouper._cython_operation(
- "aggregate", obj._values, how, axis=0, min_count=min_count
+ "aggregate", values, how, axis=0, min_count=min_count
)
+ except NotImplementedError:
+ ser = Series(values) # equiv 'obj' from outer frame
+ if self.grouper.ngroups > 0:
+ res_values, _ = self.grouper.agg_series(ser, alt)
+ else:
+ # equiv: res_values = self._python_agg_general(alt)
+ # error: Incompatible types in assignment (expression has
+ # type "Union[DataFrame, Series]", variable has type
+ # "Union[ExtensionArray, ndarray]")
+ res_values = self._python_apply_general( # type: ignore[assignment]
+ alt, ser
+ )
- assert result.ndim == 1
- key = base.OutputKey(label=name, position=idx)
- output[key] = result
- idx += 1
+ if isinstance(values, Categorical):
+ # Because we only get here with known dtype-preserving
+ # reductions, we cast back to Categorical.
+ # TODO: if we ever get "rank" working, exclude it here.
+ result = type(values)._from_sequence(res_values, dtype=values.dtype)
+ else:
+ result = res_values
+ return result
- if not output:
- raise DataError("No numeric types to aggregate")
+ result = array_func(objvals)
- return self._wrap_aggregated_output(output)
+ ser = self.obj._constructor(
+ result, index=self.grouper.result_index, name=obj.name
+ )
+ return self._reindex_output(ser)
def _wrap_aggregated_output(
self,
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 7fe9d7cb49eb5..cdd2cef1f2e59 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1281,15 +1281,6 @@ def _agg_general(
)
except DataError:
pass
- except NotImplementedError as err:
- if "function is not implemented for this dtype" in str(
- err
- ) or "category dtype not supported" in str(err):
- # raised in _get_cython_function, in some cases can
- # be trimmed by implementing cython funcs for more dtypes
- pass
- else:
- raise
# apply a non-cython aggregation
if result is None:
| - make the exception-handling in SeriesGroupBy._cython_agg_general match that in DataFrameGroupBy._cython_agg_general
- remove an unnecessary for loop
- define array_func to match the pattern in DataFrameGroupBy._cython_agg_general in the hopes that we can share these methods before long | https://api.github.com/repos/pandas-dev/pandas/pulls/41271 | 2021-05-02T19:58:37Z | 2021-05-02T23:24:23Z | 2021-05-02T23:24:23Z | 2021-05-03T01:24:52Z |
CI: fix test for SSL warning | diff --git a/pandas/_testing/_warnings.py b/pandas/_testing/_warnings.py
index 391226b622a01..b1f070d1a1ccc 100644
--- a/pandas/_testing/_warnings.py
+++ b/pandas/_testing/_warnings.py
@@ -144,7 +144,7 @@ def _assert_caught_no_extra_warnings(
if _is_unexpected_warning(actual_warning, expected_warning):
unclosed = "unclosed transport <asyncio.sslproto._SSLProtocolTransport"
if isinstance(actual_warning, ResourceWarning) and unclosed in str(
- actual_warning
+ actual_warning.message
):
# FIXME: kludge because pytest.filterwarnings does not
# suppress these, xref GH#38630
| follow up to #41083 to change test | https://api.github.com/repos/pandas-dev/pandas/pulls/41270 | 2021-05-02T19:37:45Z | 2021-05-02T23:08:51Z | 2021-05-02T23:08:51Z | 2021-05-02T23:52:30Z |
ENH: make `Styler` compatible with non-unique indexes | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index a81dda4e7dfdd..fec4422bac37e 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -138,6 +138,8 @@ The :meth:`.Styler.format` has had upgrades to easily format missing data,
precision, and perform HTML escaping (:issue:`40437` :issue:`40134`). There have been numerous other bug fixes to
properly format HTML and eliminate some inconsistencies (:issue:`39942` :issue:`40356` :issue:`39807` :issue:`39889` :issue:`39627`)
+:class:`.Styler` has also been compatible with non-unique index or columns, at least for as many features as are fully compatible, others made only partially compatible (:issue:`41269`).
+
Documentation has also seen major revisions in light of new features (:issue:`39720` :issue:`39317` :issue:`40493`)
.. _whatsnew_130.dataframe_honors_copy_with_dict:
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 02e1369a05b93..8fc2825ffcfc5 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -322,6 +322,10 @@ def set_tooltips(
raise NotImplementedError(
"Tooltips can only render with 'cell_ids' is True."
)
+ if not ttips.index.is_unique or not ttips.columns.is_unique:
+ raise KeyError(
+ "Tooltips render only if `ttips` has unique index and columns."
+ )
if self.tooltips is None: # create a default instance if necessary
self.tooltips = Tooltips()
self.tooltips.tt_data = ttips
@@ -442,6 +446,10 @@ def set_td_classes(self, classes: DataFrame) -> Styler:
' </tbody>'
'</table>'
"""
+ if not classes.index.is_unique or not classes.columns.is_unique:
+ raise KeyError(
+ "Classes render only if `classes` has unique index and columns."
+ )
classes = classes.reindex_like(self.data)
for r, row_tup in enumerate(classes.itertuples()):
@@ -464,6 +472,12 @@ def _update_ctx(self, attrs: DataFrame) -> None:
Whitespace shouldn't matter and the final trailing ';' shouldn't
matter.
"""
+ if not self.index.is_unique or not self.columns.is_unique:
+ raise KeyError(
+ "`Styler.apply` and `.applymap` are not compatible "
+ "with non-unique index or columns."
+ )
+
for cn in attrs.columns:
for rn, c in attrs[[cn]].itertuples():
if not c:
@@ -986,10 +1000,11 @@ def set_table_styles(
table_styles = [
{
- "selector": str(s["selector"]) + idf + str(obj.get_loc(key)),
+ "selector": str(s["selector"]) + idf + str(idx),
"props": maybe_convert_css_to_tuples(s["props"]),
}
for key, styles in table_styles.items()
+ for idx in obj.get_indexer_for([key])
for s in styles
]
else:
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index 4aaf1eecde5e8..bd768f4f0a1d4 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -82,8 +82,6 @@ def __init__(
data = data.to_frame()
if not isinstance(data, DataFrame):
raise TypeError("``data`` must be a Series or DataFrame")
- if not data.index.is_unique or not data.columns.is_unique:
- raise ValueError("style is not supported for non-unique indices.")
self.data: DataFrame = data
self.index: Index = data.index
self.columns: Index = data.columns
@@ -481,23 +479,22 @@ def format(
subset = non_reducing_slice(subset)
data = self.data.loc[subset]
- columns = data.columns
if not isinstance(formatter, dict):
- formatter = {col: formatter for col in columns}
+ formatter = {col: formatter for col in data.columns}
- for col in columns:
+ cis = self.columns.get_indexer_for(data.columns)
+ ris = self.index.get_indexer_for(data.index)
+ for ci in cis:
format_func = _maybe_wrap_formatter(
- formatter.get(col),
+ formatter.get(self.columns[ci]),
na_rep=na_rep,
precision=precision,
decimal=decimal,
thousands=thousands,
escape=escape,
)
-
- for row, value in data[[col]].itertuples():
- i, j = self.index.get_loc(row), self.columns.get_loc(col)
- self._display_funcs[(i, j)] = format_func
+ for ri in ris:
+ self._display_funcs[(ri, ci)] = format_func
return self
diff --git a/pandas/tests/io/formats/style/test_non_unique.py b/pandas/tests/io/formats/style/test_non_unique.py
new file mode 100644
index 0000000000000..2dc7433009368
--- /dev/null
+++ b/pandas/tests/io/formats/style/test_non_unique.py
@@ -0,0 +1,124 @@
+import pytest
+
+from pandas import (
+ DataFrame,
+ IndexSlice,
+)
+
+pytest.importorskip("jinja2")
+
+from pandas.io.formats.style import Styler
+
+
+@pytest.fixture
+def df():
+ return DataFrame(
+ [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+ index=["i", "j", "j"],
+ columns=["c", "d", "d"],
+ dtype=float,
+ )
+
+
+@pytest.fixture
+def styler(df):
+ return Styler(df, uuid_len=0)
+
+
+def test_format_non_unique(df):
+ # GH 41269
+
+ # test dict
+ html = df.style.format({"d": "{:.1f}"}).render()
+ for val in ["1.000000<", "4.000000<", "7.000000<"]:
+ assert val in html
+ for val in ["2.0<", "3.0<", "5.0<", "6.0<", "8.0<", "9.0<"]:
+ assert val in html
+
+ # test subset
+ html = df.style.format(precision=1, subset=IndexSlice["j", "d"]).render()
+ for val in ["1.000000<", "4.000000<", "7.000000<", "2.000000<", "3.000000<"]:
+ assert val in html
+ for val in ["5.0<", "6.0<", "8.0<", "9.0<"]:
+ assert val in html
+
+
+@pytest.mark.parametrize("func", ["apply", "applymap"])
+def test_apply_applymap_non_unique_raises(df, func):
+ # GH 41269
+ if func == "apply":
+ op = lambda s: ["color: red;"] * len(s)
+ else:
+ op = lambda v: "color: red;"
+
+ with pytest.raises(KeyError, match="`Styler.apply` and `.applymap` are not"):
+ getattr(df.style, func)(op)._compute()
+
+
+def test_table_styles_dict_non_unique_index(styler):
+ styles = styler.set_table_styles(
+ {"j": [{"selector": "td", "props": "a: v;"}]}, axis=1
+ ).table_styles
+ assert styles == [
+ {"selector": "td.row1", "props": [("a", "v")]},
+ {"selector": "td.row2", "props": [("a", "v")]},
+ ]
+
+
+def test_table_styles_dict_non_unique_columns(styler):
+ styles = styler.set_table_styles(
+ {"d": [{"selector": "td", "props": "a: v;"}]}, axis=0
+ ).table_styles
+ assert styles == [
+ {"selector": "td.col1", "props": [("a", "v")]},
+ {"selector": "td.col2", "props": [("a", "v")]},
+ ]
+
+
+def test_tooltips_non_unique_raises(styler):
+ # ttips has unique keys
+ ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "b"])
+ styler.set_tooltips(ttips=ttips) # OK
+
+ # ttips has non-unique columns
+ ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "c"], index=["a", "b"])
+ with pytest.raises(KeyError, match="Tooltips render only if `ttips` has unique"):
+ styler.set_tooltips(ttips=ttips)
+
+ # ttips has non-unique index
+ ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "a"])
+ with pytest.raises(KeyError, match="Tooltips render only if `ttips` has unique"):
+ styler.set_tooltips(ttips=ttips)
+
+
+def test_set_td_classes_non_unique_raises(styler):
+ # classes has unique keys
+ classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "b"])
+ styler.set_td_classes(classes=classes) # OK
+
+ # classes has non-unique columns
+ classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "c"], index=["a", "b"])
+ with pytest.raises(KeyError, match="Classes render only if `classes` has unique"):
+ styler.set_td_classes(classes=classes)
+
+ # classes has non-unique index
+ classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "a"])
+ with pytest.raises(KeyError, match="Classes render only if `classes` has unique"):
+ styler.set_td_classes(classes=classes)
+
+
+def test_hide_columns_non_unique(styler):
+ ctx = styler.hide_columns(["d"])._translate()
+
+ assert ctx["head"][0][1]["display_value"] == "c"
+ assert ctx["head"][0][1]["is_visible"] is True
+
+ assert ctx["head"][0][2]["display_value"] == "d"
+ assert ctx["head"][0][2]["is_visible"] is False
+
+ assert ctx["head"][0][3]["display_value"] == "d"
+ assert ctx["head"][0][3]["is_visible"] is False
+
+ assert ctx["body"][0][1]["is_visible"] is True
+ assert ctx["body"][0][2]["is_visible"] is False
+ assert ctx["body"][0][3]["is_visible"] is False
diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py
index 3b614be770bc5..855def916c2cd 100644
--- a/pandas/tests/io/formats/style/test_style.py
+++ b/pandas/tests/io/formats/style/test_style.py
@@ -671,15 +671,6 @@ def test_set_na_rep(self):
assert ctx["body"][0][1]["display_value"] == "NA"
assert ctx["body"][0][2]["display_value"] == "-"
- def test_nonunique_raises(self):
- df = DataFrame([[1, 2]], columns=["A", "A"])
- msg = "style is not supported for non-unique indices."
- with pytest.raises(ValueError, match=msg):
- df.style
-
- with pytest.raises(ValueError, match=msg):
- Styler(df)
-
def test_caption(self):
styler = Styler(self.df, caption="foo")
result = styler.render()
| - [x] closes #41143
The PR aims to make Styler compatible with non-unique indexes/columns, for the purpose of rendering all DataFrame types (even if no styling is applied)
- [x] `Styler.format`: made FULLY compatible with some modifications to the loops, inc TESTS.
- [x] <s>`Styler.apply` and `Styler.applymap`: made PARTIALLY compatible:
- if `subset`s are unique then compatible, inc TESTS.
- if `subset`s are non-unique slices will raise a not compatible `KeyError`, inc. TESTS</s>
- [x] `Styler.apply` and `applymap` are NOT compatible. Raises KeyError.
- [x] `Styler.set_table_styles`: made FULLY compatible and will style multiple rows/columns from a non-unique key, inc TESTS.
- [x] `Styler.set_td_classes` uses `reindex` so is PARTIALLY compatible where `classes` has unique index/columns: now returns a `KeyError` in non-unique case, inc TESTS.
- [x] `Styler.set_tooltips` uses `reindex` so is PARTIALLY compatible where `ttips` has unique index/columns: now returns a `KeyError` in non-unique case, inc TESTS.
- [x] `Styler.hide_index` and `.hide_columns` are already FULLY compatible through existing code (inc TESTS)
- [x] all the `built-in` styling functions use some version of `apply` or `applymap` so are captured by the above cases.
I believe this is all relevant functionality reviewed.
| https://api.github.com/repos/pandas-dev/pandas/pulls/41269 | 2021-05-02T18:38:41Z | 2021-05-06T23:32:02Z | 2021-05-06T23:32:02Z | 2021-05-07T05:18:04Z |
Bug in setitem raising ValueError with row-slice indexer on df with list-like on rhs | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index b2f4de22ca5c1..2c2ae8cc1f88b 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -752,6 +752,7 @@ Indexing
- Bug in :meth:`RangeIndex.append` where a single object of length 1 was concatenated incorrectly (:issue:`39401`)
- Bug in setting ``numpy.timedelta64`` values into an object-dtype :class:`Series` using a boolean indexer (:issue:`39488`)
- Bug in setting numeric values into a into a boolean-dtypes :class:`Series` using ``at`` or ``iat`` failing to cast to object-dtype (:issue:`39582`)
+- Bug in :meth:`DataFrame.__setitem__` and :meth:`DataFrame.iloc.__setitem__` raising ``ValueError`` when trying to index with a row-slice and setting a list as values (:issue:`40440`)
- Bug in :meth:`DataFrame.loc.__setitem__` when setting-with-expansion incorrectly raising when the index in the expanding axis contains duplicates (:issue:`40096`)
- Bug in :meth:`DataFrame.loc` incorrectly matching non-boolean index elements (:issue:`20432`)
- Bug in :meth:`Series.__delitem__` with ``ExtensionDtype`` incorrectly casting to ``ndarray`` (:issue:`40386`)
diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py
index aa780787d58b6..d3756d6252c0a 100644
--- a/pandas/core/indexers.py
+++ b/pandas/core/indexers.py
@@ -180,7 +180,8 @@ def check_setitem_lengths(indexer, value, values) -> bool:
elif isinstance(indexer, slice):
if is_list_like(value):
- if len(value) != length_of_indexer(indexer, values):
+ if len(value) != length_of_indexer(indexer, values) and values.ndim == 1:
+ # In case of two dimensional value is used row-wise and broadcasted
raise ValueError(
"cannot set using a slice indexer with a "
"different length than the value"
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 3fa8295084718..4004e595c832f 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -791,6 +791,34 @@ def test_setitem_slice_position(self):
expected = DataFrame(arr)
tm.assert_frame_equal(df, expected)
+ @pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc])
+ @pytest.mark.parametrize("box", [Series, np.array, list])
+ @pytest.mark.parametrize("n", [1, 2, 3])
+ def test_setitem_broadcasting_rhs(self, n, box, indexer):
+ # GH#40440
+ # TODO: Add pandas array as box after GH#40933 is fixed
+ df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"])
+ indexer(df)[1:] = box([10, 11, 12])
+ expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"])
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc])
+ @pytest.mark.parametrize("box", [Series, np.array, list])
+ @pytest.mark.parametrize("n", [1, 2, 3])
+ def test_setitem_broadcasting_rhs_mixed_dtypes(self, n, box, indexer):
+ # GH#40440
+ # TODO: Add pandas array as box after GH#40933 is fixed
+ df = DataFrame(
+ [[1, 3, 5], ["x", "y", "z"]] + [[2, 4, 6]] * n, columns=["a", "b", "c"]
+ )
+ indexer(df)[1:] = box([10, 11, 12])
+ expected = DataFrame(
+ [[1, 3, 5]] + [[10, 11, 12]] * (n + 1),
+ columns=["a", "b", "c"],
+ dtype="object",
+ )
+ tm.assert_frame_equal(df, expected)
+
class TestDataFrameSetItemCallable:
def test_setitem_callable(self):
| - [x] closes #40440
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
I'll adress the IntegerArray case from #40933 after this is merged | https://api.github.com/repos/pandas-dev/pandas/pulls/41268 | 2021-05-02T17:55:43Z | 2021-05-02T23:47:54Z | 2021-05-02T23:47:54Z | 2021-05-03T18:30:08Z |
ENH: Numba engine for EWM.mean | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index b2f4de22ca5c1..ea1bc309bb041 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -197,7 +197,7 @@ Other enhancements
- Add support for dict-like names in :class:`MultiIndex.set_names` and :class:`MultiIndex.rename` (:issue:`20421`)
- :func:`pandas.read_excel` can now auto detect .xlsb files (:issue:`35416`)
- :class:`pandas.ExcelWriter` now accepts an ``if_sheet_exists`` parameter to control the behaviour of append mode when writing to existing sheets (:issue:`40230`)
-- :meth:`.Rolling.sum`, :meth:`.Expanding.sum`, :meth:`.Rolling.mean`, :meth:`.Expanding.mean`, :meth:`.Rolling.median`, :meth:`.Expanding.median`, :meth:`.Rolling.max`, :meth:`.Expanding.max`, :meth:`.Rolling.min`, and :meth:`.Expanding.min` now support ``Numba`` execution with the ``engine`` keyword (:issue:`38895`)
+- :meth:`.Rolling.sum`, :meth:`.Expanding.sum`, :meth:`.Rolling.mean`, :meth:`.Expanding.mean`, :meth:`.ExponentialMovingWindow.mean`, :meth:`.Rolling.median`, :meth:`.Expanding.median`, :meth:`.Rolling.max`, :meth:`.Expanding.max`, :meth:`.Rolling.min`, and :meth:`.Expanding.min` now support ``Numba`` execution with the ``engine`` keyword (:issue:`38895`, :issue:`41267`)
- :meth:`DataFrame.apply` can now accept NumPy unary operators as strings, e.g. ``df.apply("sqrt")``, which was already the case for :meth:`Series.apply` (:issue:`39116`)
- :meth:`DataFrame.apply` can now accept non-callable DataFrame properties as strings, e.g. ``df.apply("size")``, which was already the case for :meth:`Series.apply` (:issue:`39116`)
- :meth:`DataFrame.applymap` can now accept kwargs to pass on to func (:issue:`39987`)
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py
index 4a210d8b47e9b..08a65964f278e 100644
--- a/pandas/core/window/ewm.py
+++ b/pandas/core/window/ewm.py
@@ -29,16 +29,18 @@
args_compat,
create_section_header,
kwargs_compat,
+ numba_notes,
template_header,
template_returns,
template_see_also,
+ window_agg_numba_parameters,
)
from pandas.core.window.indexers import (
BaseIndexer,
ExponentialMovingWindowIndexer,
GroupbyIndexer,
)
-from pandas.core.window.numba_ import generate_numba_groupby_ewma_func
+from pandas.core.window.numba_ import generate_numba_ewma_func
from pandas.core.window.rolling import (
BaseWindow,
BaseWindowGroupby,
@@ -372,26 +374,41 @@ def aggregate(self, func, *args, **kwargs):
template_header,
create_section_header("Parameters"),
args_compat,
+ window_agg_numba_parameters,
kwargs_compat,
create_section_header("Returns"),
template_returns,
create_section_header("See Also"),
- template_see_also[:-1],
+ template_see_also,
+ create_section_header("Notes"),
+ numba_notes.replace("\n", "", 1),
window_method="ewm",
aggregation_description="(exponential weighted moment) mean",
agg_method="mean",
)
- def mean(self, *args, **kwargs):
- nv.validate_window_func("mean", args, kwargs)
- window_func = window_aggregations.ewma
- window_func = partial(
- window_func,
- com=self._com,
- adjust=self.adjust,
- ignore_na=self.ignore_na,
- deltas=self._deltas,
- )
- return self._apply(window_func)
+ def mean(self, *args, engine=None, engine_kwargs=None, **kwargs):
+ if maybe_use_numba(engine):
+ ewma_func = generate_numba_ewma_func(
+ engine_kwargs, self._com, self.adjust, self.ignore_na, self._deltas
+ )
+ return self._apply(
+ ewma_func,
+ numba_cache_key=(lambda x: x, "ewma"),
+ )
+ elif engine in ("cython", None):
+ if engine_kwargs is not None:
+ raise ValueError("cython engine does not accept engine_kwargs")
+ nv.validate_window_func("mean", args, kwargs)
+ window_func = partial(
+ window_aggregations.ewma,
+ com=self._com,
+ adjust=self.adjust,
+ ignore_na=self.ignore_na,
+ deltas=self._deltas,
+ )
+ return self._apply(window_func)
+ else:
+ raise ValueError("engine must be either 'numba' or 'cython'")
@doc(
template_header,
@@ -635,45 +652,3 @@ def _get_window_indexer(self) -> GroupbyIndexer:
window_indexer=ExponentialMovingWindowIndexer,
)
return window_indexer
-
- def mean(self, engine=None, engine_kwargs=None):
- """
- Parameters
- ----------
- engine : str, default None
- * ``'cython'`` : Runs mean through C-extensions from cython.
- * ``'numba'`` : Runs mean through JIT compiled code from numba.
- Only available when ``raw`` is set to ``True``.
- * ``None`` : Defaults to ``'cython'`` or globally setting
- ``compute.use_numba``
-
- .. versionadded:: 1.2.0
-
- engine_kwargs : dict, default None
- * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
- * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
- and ``parallel`` dictionary keys. The values must either be ``True`` or
- ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
- ``{'nopython': True, 'nogil': False, 'parallel': False}``.
-
- .. versionadded:: 1.2.0
-
- Returns
- -------
- Series or DataFrame
- Return type is determined by the caller.
- """
- if maybe_use_numba(engine):
- groupby_ewma_func = generate_numba_groupby_ewma_func(
- engine_kwargs, self._com, self.adjust, self.ignore_na, self._deltas
- )
- return self._apply(
- groupby_ewma_func,
- numba_cache_key=(lambda x: x, "groupby_ewma"),
- )
- elif engine in ("cython", None):
- if engine_kwargs is not None:
- raise ValueError("cython engine does not accept engine_kwargs")
- return super().mean()
- else:
- raise ValueError("engine must be either 'numba' or 'cython'")
diff --git a/pandas/core/window/numba_.py b/pandas/core/window/numba_.py
index d84dea7ee622c..9407efd0bef2b 100644
--- a/pandas/core/window/numba_.py
+++ b/pandas/core/window/numba_.py
@@ -80,7 +80,7 @@ def roll_apply(
return roll_apply
-def generate_numba_groupby_ewma_func(
+def generate_numba_ewma_func(
engine_kwargs: Optional[Dict[str, bool]],
com: float,
adjust: bool,
@@ -88,7 +88,7 @@ def generate_numba_groupby_ewma_func(
deltas: np.ndarray,
):
"""
- Generate a numba jitted groupby ewma function specified by values
+ Generate a numba jitted ewma function specified by values
from engine_kwargs.
Parameters
@@ -106,14 +106,14 @@ def generate_numba_groupby_ewma_func(
"""
nopython, nogil, parallel = get_jit_arguments(engine_kwargs)
- cache_key = (lambda x: x, "groupby_ewma")
+ cache_key = (lambda x: x, "ewma")
if cache_key in NUMBA_FUNC_CACHE:
return NUMBA_FUNC_CACHE[cache_key]
numba = import_optional_dependency("numba")
@numba.jit(nopython=nopython, nogil=nogil, parallel=parallel)
- def groupby_ewma(
+ def ewma(
values: np.ndarray,
begin: np.ndarray,
end: np.ndarray,
@@ -121,15 +121,15 @@ def groupby_ewma(
) -> np.ndarray:
result = np.empty(len(values))
alpha = 1.0 / (1.0 + com)
+ old_wt_factor = 1.0 - alpha
+ new_wt = 1.0 if adjust else alpha
+
for i in numba.prange(len(begin)):
start = begin[i]
stop = end[i]
window = values[start:stop]
sub_result = np.empty(len(window))
- old_wt_factor = 1.0 - alpha
- new_wt = 1.0 if adjust else alpha
-
weighted_avg = window[0]
nobs = int(not np.isnan(weighted_avg))
sub_result[0] = weighted_avg if nobs >= minimum_periods else np.nan
@@ -166,7 +166,7 @@ def groupby_ewma(
return result
- return groupby_ewma
+ return ewma
def generate_numba_table_func(
diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py
index 06b34201e0dba..b79c367d482ae 100644
--- a/pandas/tests/window/test_numba.py
+++ b/pandas/tests/window/test_numba.py
@@ -123,30 +123,44 @@ def func_2(x):
@td.skip_if_no("numba", "0.46.0")
-class TestGroupbyEWMMean:
- def test_invalid_engine(self):
+class TestEWMMean:
+ @pytest.mark.parametrize(
+ "grouper", [lambda x: x, lambda x: x.groupby("A")], ids=["None", "groupby"]
+ )
+ def test_invalid_engine(self, grouper):
df = DataFrame({"A": ["a", "b", "a", "b"], "B": range(4)})
with pytest.raises(ValueError, match="engine must be either"):
- df.groupby("A").ewm(com=1.0).mean(engine="foo")
+ grouper(df).ewm(com=1.0).mean(engine="foo")
- def test_invalid_engine_kwargs(self):
+ @pytest.mark.parametrize(
+ "grouper", [lambda x: x, lambda x: x.groupby("A")], ids=["None", "groupby"]
+ )
+ def test_invalid_engine_kwargs(self, grouper):
df = DataFrame({"A": ["a", "b", "a", "b"], "B": range(4)})
with pytest.raises(ValueError, match="cython engine does not"):
- df.groupby("A").ewm(com=1.0).mean(
+ grouper(df).ewm(com=1.0).mean(
engine="cython", engine_kwargs={"nopython": True}
)
- def test_cython_vs_numba(self, nogil, parallel, nopython, ignore_na, adjust):
+ @pytest.mark.parametrize(
+ "grouper", [lambda x: x, lambda x: x.groupby("A")], ids=["None", "groupby"]
+ )
+ def test_cython_vs_numba(
+ self, grouper, nogil, parallel, nopython, ignore_na, adjust
+ ):
df = DataFrame({"A": ["a", "b", "a", "b"], "B": range(4)})
- gb_ewm = df.groupby("A").ewm(com=1.0, adjust=adjust, ignore_na=ignore_na)
+ ewm = grouper(df).ewm(com=1.0, adjust=adjust, ignore_na=ignore_na)
engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
- result = gb_ewm.mean(engine="numba", engine_kwargs=engine_kwargs)
- expected = gb_ewm.mean(engine="cython")
+ result = ewm.mean(engine="numba", engine_kwargs=engine_kwargs)
+ expected = ewm.mean(engine="cython")
tm.assert_frame_equal(result, expected)
- def test_cython_vs_numba_times(self, nogil, parallel, nopython, ignore_na):
+ @pytest.mark.parametrize(
+ "grouper", [lambda x: x, lambda x: x.groupby("A")], ids=["None", "groupby"]
+ )
+ def test_cython_vs_numba_times(self, grouper, nogil, parallel, nopython, ignore_na):
# GH 40951
halflife = "23 days"
times = to_datetime(
@@ -160,13 +174,13 @@ def test_cython_vs_numba_times(self, nogil, parallel, nopython, ignore_na):
]
)
df = DataFrame({"A": ["a", "b", "a", "b", "b", "a"], "B": [0, 0, 1, 1, 2, 2]})
- gb_ewm = df.groupby("A").ewm(
+ ewm = grouper(df).ewm(
halflife=halflife, adjust=True, ignore_na=ignore_na, times=times
)
engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
- result = gb_ewm.mean(engine="numba", engine_kwargs=engine_kwargs)
- expected = gb_ewm.mean(engine="cython")
+ result = ewm.mean(engine="numba", engine_kwargs=engine_kwargs)
+ expected = ewm.mean(engine="cython")
tm.assert_frame_equal(result, expected)
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41267 | 2021-05-02T17:10:37Z | 2021-05-02T23:57:20Z | 2021-05-02T23:57:20Z | 2021-05-03T05:04:48Z |
API: make `hide_columns` and `hide_index` have a consistent signature and function in `Styler` | diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 93c3843b36846..bf4df4ff73055 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -31,7 +31,10 @@
from pandas.util._decorators import doc
import pandas as pd
-from pandas import RangeIndex
+from pandas import (
+ IndexSlice,
+ RangeIndex,
+)
from pandas.api.types import is_list_like
from pandas.core import generic
import pandas.core.common as com
@@ -682,7 +685,7 @@ def to_latex(
self.data.columns = RangeIndex(stop=len(self.data.columns))
numeric_cols = self.data._get_numeric_data().columns.to_list()
self.data.columns = _original_columns
- column_format = "" if self.hidden_index else "l" * self.data.index.nlevels
+ column_format = "" if self.hide_index_ else "l" * self.data.index.nlevels
for ci, _ in enumerate(self.data.columns):
if ci not in self.hidden_columns:
column_format += (
@@ -926,7 +929,7 @@ def _copy(self, deepcopy: bool = False) -> Styler:
)
styler.uuid = self.uuid
- styler.hidden_index = self.hidden_index
+ styler.hide_index_ = self.hide_index_
if deepcopy:
styler.ctx = copy.deepcopy(self.ctx)
@@ -965,7 +968,7 @@ def clear(self) -> None:
self.cell_context.clear()
self._todo.clear()
- self.hidden_index = False
+ self.hide_index_ = False
self.hidden_columns = []
# self.format and self.table_styles may be dependent on user
# input in self.__init__()
@@ -1096,7 +1099,7 @@ def _applymap(
) -> Styler:
func = partial(func, **kwargs) # applymap doesn't take kwargs?
if subset is None:
- subset = pd.IndexSlice[:]
+ subset = IndexSlice[:]
subset = non_reducing_slice(subset)
result = self.data.loc[subset].applymap(func)
self._update_ctx(result)
@@ -1509,37 +1512,169 @@ def set_na_rep(self, na_rep: str) -> StylerRenderer:
self.na_rep = na_rep
return self.format(na_rep=na_rep, precision=self.precision)
- def hide_index(self) -> Styler:
+ def hide_index(self, subset: Subset | None = None) -> Styler:
"""
- Hide any indices from rendering.
+ Hide the entire index, or specific keys in the index from rendering.
+
+ This method has dual functionality:
+
+ - if ``subset`` is ``None`` then the entire index will be hidden whilst
+ displaying all data-rows.
+ - if a ``subset`` is given then those specific rows will be hidden whilst the
+ index itself remains visible.
+
+ .. versionchanged:: 1.3.0
+
+ Parameters
+ ----------
+ subset : label, array-like, IndexSlice, optional
+ A valid 1d input or single key along the index axis within
+ `DataFrame.loc[<subset>, :]`, to limit ``data`` to *before* applying
+ the function.
Returns
-------
self : Styler
+
+ See Also
+ --------
+ Styler.hide_columns: Hide the entire column headers row, or specific columns.
+
+ Examples
+ --------
+ Simple application hiding specific rows:
+
+ >>> df = pd.DataFrame([[1,2], [3,4], [5,6]], index=["a", "b", "c"])
+ >>> df.style.hide_index(["a", "b"])
+ 0 1
+ c 5 6
+
+ Hide the index and retain the data values:
+
+ >>> midx = pd.MultiIndex.from_product([["x", "y"], ["a", "b", "c"]])
+ >>> df = pd.DataFrame(np.random.randn(6,6), index=midx, columns=midx)
+ >>> df.style.format("{:.1f}").hide_index()
+ x y
+ a b c a b c
+ 0.1 0.0 0.4 1.3 0.6 -1.4
+ 0.7 1.0 1.3 1.5 -0.0 -0.2
+ 1.4 -0.8 1.6 -0.2 -0.4 -0.3
+ 0.4 1.0 -0.2 -0.8 -1.2 1.1
+ -0.6 1.2 1.8 1.9 0.3 0.3
+ 0.8 0.5 -0.3 1.2 2.2 -0.8
+
+ Hide specific rows but retain the index:
+
+ >>> df.style.format("{:.1f}").hide_index(subset=(slice(None), ["a", "c"]))
+ x y
+ a b c a b c
+ x b 0.7 1.0 1.3 1.5 -0.0 -0.2
+ y b -0.6 1.2 1.8 1.9 0.3 0.3
+
+ Hide specific rows and the index:
+
+ >>> df.style.format("{:.1f}").hide_index(subset=(slice(None), ["a", "c"]))
+ ... .hide_index()
+ x y
+ a b c a b c
+ 0.7 1.0 1.3 1.5 -0.0 -0.2
+ -0.6 1.2 1.8 1.9 0.3 0.3
"""
- self.hidden_index = True
+ if subset is None:
+ self.hide_index_ = True
+ else:
+ subset_ = IndexSlice[subset, :] # new var so mypy reads not Optional
+ subset = non_reducing_slice(subset_)
+ hide = self.data.loc[subset]
+ hrows = self.index.get_indexer_for(hide.index)
+ # error: Incompatible types in assignment (expression has type
+ # "ndarray", variable has type "Sequence[int]")
+ self.hidden_rows = hrows # type: ignore[assignment]
return self
- def hide_columns(self, subset: Subset) -> Styler:
+ def hide_columns(self, subset: Subset | None = None) -> Styler:
"""
- Hide columns from rendering.
+ Hide the column headers or specific keys in the columns from rendering.
+
+ This method has dual functionality:
+
+ - if ``subset`` is ``None`` then the entire column headers row will be hidden
+ whilst the data-values remain visible.
+ - if a ``subset`` is given then those specific columns, including the
+ data-values will be hidden, whilst the column headers row remains visible.
+
+ .. versionchanged:: 1.3.0
Parameters
----------
- subset : label, array-like, IndexSlice
- A valid 1d input or single key along the appropriate axis within
- `DataFrame.loc[]`, to limit ``data`` to *before* applying the function.
+ subset : label, array-like, IndexSlice, optional
+ A valid 1d input or single key along the columns axis within
+ `DataFrame.loc[:, <subset>]`, to limit ``data`` to *before* applying
+ the function.
Returns
-------
self : Styler
+
+ See Also
+ --------
+ Styler.hide_index: Hide the entire index, or specific keys in the index.
+
+ Examples
+ --------
+ Simple application hiding specific columns:
+
+ >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "b", "c"])
+ >>> df.style.hide_columns(["a", "b"])
+ c
+ 0 3
+ 1 6
+
+ Hide column headers and retain the data values:
+
+ >>> midx = pd.MultiIndex.from_product([["x", "y"], ["a", "b", "c"]])
+ >>> df = pd.DataFrame(np.random.randn(6,6), index=midx, columns=midx)
+ >>> df.style.format("{:.1f}").hide_columns()
+ x d 0.1 0.0 0.4 1.3 0.6 -1.4
+ e 0.7 1.0 1.3 1.5 -0.0 -0.2
+ f 1.4 -0.8 1.6 -0.2 -0.4 -0.3
+ y d 0.4 1.0 -0.2 -0.8 -1.2 1.1
+ e -0.6 1.2 1.8 1.9 0.3 0.3
+ f 0.8 0.5 -0.3 1.2 2.2 -0.8
+
+ Hide specific columns but retain the column headers:
+
+ >>> df.style.format("{:.1f}").hide_columns(subset=(slice(None), ["a", "c"]))
+ x y
+ b b
+ x a 0.0 0.6
+ b 1.0 -0.0
+ c -0.8 -0.4
+ y a 1.0 -1.2
+ b 1.2 0.3
+ c 0.5 2.2
+
+ Hide specific columns and the column headers:
+
+ >>> df.style.format("{:.1f}").hide_columns(subset=(slice(None), ["a", "c"]))
+ ... .hide_columns()
+ x a 0.0 0.6
+ b 1.0 -0.0
+ c -0.8 -0.4
+ y a 1.0 -1.2
+ b 1.2 0.3
+ c 0.5 2.2
"""
- subset = non_reducing_slice(subset)
- hidden_df = self.data.loc[subset]
- hcols = self.columns.get_indexer_for(hidden_df.columns)
- # error: Incompatible types in assignment (expression has type
- # "ndarray", variable has type "Sequence[int]")
- self.hidden_columns = hcols # type: ignore[assignment]
+ if subset is None:
+ self.hide_columns_ = True
+ else:
+ subset_ = IndexSlice[:, subset] # new var so mypy reads not Optional
+ subset = non_reducing_slice(subset_)
+ hide = self.data.loc[subset]
+ hcols = self.columns.get_indexer_for(hide.columns)
+ # error: Incompatible types in assignment (expression has type
+ # "ndarray", variable has type "Sequence[int]")
+ self.hidden_columns = hcols # type: ignore[assignment]
return self
# -----------------------------------------------------------------------
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index 7686d8a340c37..514597d27a92b 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -97,7 +97,9 @@ def __init__(
self.cell_ids = cell_ids
# add rendering variables
- self.hidden_index: bool = False
+ self.hide_index_: bool = False # bools for hiding col/row headers
+ self.hide_columns_: bool = False
+ self.hidden_rows: Sequence[int] = [] # sequence for specific hidden rows/cols
self.hidden_columns: Sequence[int] = []
self.ctx: DefaultDict[tuple[int, int], CSSList] = defaultdict(list)
self.cell_context: DefaultDict[tuple[int, int], str] = defaultdict(str)
@@ -297,55 +299,56 @@ def _translate_header(
head = []
# 1) column headers
- for r in range(self.data.columns.nlevels):
- index_blanks = [
- _element("th", blank_class, blank_value, not self.hidden_index)
- ] * (self.data.index.nlevels - 1)
-
- name = self.data.columns.names[r]
- column_name = [
- _element(
- "th",
- f"{blank_class if name is None else index_name_class} level{r}",
- name if name is not None else blank_value,
- not self.hidden_index,
- )
- ]
-
- if clabels:
- column_headers = [
+ if not self.hide_columns_:
+ for r in range(self.data.columns.nlevels):
+ index_blanks = [
+ _element("th", blank_class, blank_value, not self.hide_index_)
+ ] * (self.data.index.nlevels - 1)
+
+ name = self.data.columns.names[r]
+ column_name = [
_element(
"th",
- f"{col_heading_class} level{r} col{c}",
- value,
- _is_visible(c, r, col_lengths),
- attributes=(
- f'colspan="{col_lengths.get((r, c), 0)}"'
- if col_lengths.get((r, c), 0) > 1
- else ""
- ),
+ f"{blank_class if name is None else index_name_class} level{r}",
+ name if name is not None else blank_value,
+ not self.hide_index_,
)
- for c, value in enumerate(clabels[r])
]
- if len(self.data.columns) > max_cols:
- # add an extra column with `...` value to indicate trimming
- column_headers.append(
+ if clabels:
+ column_headers = [
_element(
"th",
- f"{col_heading_class} level{r} {trimmed_col_class}",
- "...",
- True,
- attributes="",
+ f"{col_heading_class} level{r} col{c}",
+ value,
+ _is_visible(c, r, col_lengths),
+ attributes=(
+ f'colspan="{col_lengths.get((r, c), 0)}"'
+ if col_lengths.get((r, c), 0) > 1
+ else ""
+ ),
)
- )
- head.append(index_blanks + column_name + column_headers)
+ for c, value in enumerate(clabels[r])
+ ]
+
+ if len(self.data.columns) > max_cols:
+ # add an extra column with `...` value to indicate trimming
+ column_headers.append(
+ _element(
+ "th",
+ f"{col_heading_class} level{r} {trimmed_col_class}",
+ "...",
+ True,
+ attributes="",
+ )
+ )
+ head.append(index_blanks + column_name + column_headers)
# 2) index names
if (
self.data.index.names
and com.any_not_none(*self.data.index.names)
- and not self.hidden_index
+ and not self.hide_index_
):
index_names = [
_element(
@@ -411,7 +414,9 @@ def _translate_body(
The associated HTML elements needed for template rendering.
"""
# for sparsifying a MultiIndex
- idx_lengths = _get_level_lengths(self.index, sparsify_index, max_rows)
+ idx_lengths = _get_level_lengths(
+ self.index, sparsify_index, max_rows, self.hidden_rows
+ )
rlabels = self.data.index.tolist()[:max_rows] # slice to allow trimming
if self.data.index.nlevels == 1:
@@ -425,7 +430,7 @@ def _translate_body(
"th",
f"{row_heading_class} level{c} {trimmed_row_class}",
"...",
- not self.hidden_index,
+ not self.hide_index_,
attributes="",
)
for c in range(self.data.index.nlevels)
@@ -462,7 +467,7 @@ def _translate_body(
"th",
f"{row_heading_class} level{c} row{r}",
value,
- (_is_visible(r, c, idx_lengths) and not self.hidden_index),
+ (_is_visible(r, c, idx_lengths) and not self.hide_index_),
id=f"level{c}_row{r}",
attributes=(
f'rowspan="{idx_lengths.get((c, r), 0)}"'
@@ -496,7 +501,7 @@ def _translate_body(
"td",
f"{data_class} row{r} col{c}{cls}",
value,
- (c not in self.hidden_columns),
+ (c not in self.hidden_columns and r not in self.hidden_rows),
attributes="",
display_value=self._display_funcs[(r, c)](value),
)
@@ -527,7 +532,7 @@ def _translate_latex(self, d: dict) -> None:
d["head"] = [[col for col in row if col["is_visible"]] for row in d["head"]]
body = []
for r, row in enumerate(d["body"]):
- if self.hidden_index:
+ if self.hide_index_:
row_body_headers = []
else:
row_body_headers = [
@@ -842,7 +847,13 @@ def _get_level_lengths(
last_label = j
lengths[(i, last_label)] = 0
elif j not in hidden_elements:
- lengths[(i, last_label)] += 1
+ if lengths[(i, last_label)] == 0:
+ # if the previous iteration was first-of-kind but hidden then offset
+ last_label = j
+ lengths[(i, last_label)] = 1
+ else:
+ # else add to previous iteration
+ lengths[(i, last_label)] += 1
non_zero_lengths = {
element: length for element, length in lengths.items() if length >= 1
diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py
index 281170ab6c7cb..0516aa6029487 100644
--- a/pandas/tests/io/formats/style/test_style.py
+++ b/pandas/tests/io/formats/style/test_style.py
@@ -221,7 +221,7 @@ def test_copy(self, do_changes, do_render):
[{"selector": "th", "props": [("foo", "bar")]}]
)
self.styler.set_table_attributes('class="foo" data-bar')
- self.styler.hidden_index = not self.styler.hidden_index
+ self.styler.hide_index_ = not self.styler.hide_index_
self.styler.hide_columns("A")
classes = DataFrame(
[["favorite-val red", ""], [None, "blue my-val"]],
@@ -292,7 +292,7 @@ def test_copy(self, do_changes, do_render):
"table_styles",
"table_attributes",
"cell_ids",
- "hidden_index",
+ "hide_index_",
"hidden_columns",
"cell_context",
]
@@ -317,7 +317,7 @@ def test_clear(self):
assert len(s._todo) > 0
assert s.tooltips
assert len(s.cell_context) > 0
- assert s.hidden_index is True
+ assert s.hide_index_ is True
assert len(s.hidden_columns) > 0
s = s._compute()
@@ -331,7 +331,7 @@ def test_clear(self):
assert len(s._todo) == 0
assert not s.tooltips
assert len(s.cell_context) == 0
- assert s.hidden_index is False
+ assert s.hide_index_ is False
assert len(s.hidden_columns) == 0
def test_render(self):
@@ -1127,6 +1127,14 @@ def test_mi_sparse_column_names(self):
]
assert head == expected
+ def test_hide_column_headers(self):
+ ctx = self.styler.hide_columns()._translate(True, True)
+ assert len(ctx["head"]) == 0 # no header entries with an unnamed index
+
+ self.df.index.name = "some_name"
+ ctx = self.df.style.hide_columns()._translate(True, True)
+ assert len(ctx["head"]) == 1 # only a single row for index names: no col heads
+
def test_hide_single_index(self):
# GH 14194
# single unnamed index
@@ -1195,7 +1203,7 @@ def test_hide_columns_single_level(self):
assert not ctx["body"][0][1]["is_visible"] # col A, row 1
assert not ctx["body"][1][2]["is_visible"] # col B, row 1
- def test_hide_columns_mult_levels(self):
+ def test_hide_columns_index_mult_levels(self):
# GH 14194
# setup dataframe with multiple column levels and indices
i1 = MultiIndex.from_arrays(
@@ -1227,7 +1235,8 @@ def test_hide_columns_mult_levels(self):
# hide first column only
ctx = df.style.hide_columns([("b", 0)])._translate(True, True)
- assert ctx["head"][0][2]["is_visible"] # b
+ assert not ctx["head"][0][2]["is_visible"] # b
+ assert ctx["head"][0][3]["is_visible"] # b
assert not ctx["head"][1][2]["is_visible"] # 0
assert not ctx["body"][1][2]["is_visible"] # 3
assert ctx["body"][1][3]["is_visible"]
@@ -1243,6 +1252,18 @@ def test_hide_columns_mult_levels(self):
assert ctx["body"][1][2]["is_visible"]
assert ctx["body"][1][2]["display_value"] == 3
+ # hide top row level, which hides both rows
+ ctx = df.style.hide_index("a")._translate(True, True)
+ for i in [0, 1, 2, 3]:
+ assert not ctx["body"][0][i]["is_visible"]
+ assert not ctx["body"][1][i]["is_visible"]
+
+ # hide first row only
+ ctx = df.style.hide_index(("a", 0))._translate(True, True)
+ for i in [0, 1, 2, 3]:
+ assert not ctx["body"][0][i]["is_visible"]
+ assert ctx["body"][1][i]["is_visible"]
+
def test_pipe(self):
def set_caption_from_template(styler, a, b):
return styler.set_caption(f"Dataframe with a = {a} and b = {b}")
| This closes #41158 (which is an alternative PR for similar functionality)
Currently `hide_index()` and `hide_columns(subset)` have similar signatures but **different** operations. One hides the index whilst showing the data-rows, and the other hides data-columns whilst showing the column-headers row.
### This PR
- adds the `subset` keyword to give: `hide_index(subset=None)`.
- sets the default to `hide_columns(subset=None)`.
When `subset` is None the function now operates to hide the entire index, or entire column headers row respectively.
When `subset` is not None it operates to selectively hide the given rows or columns respectively, keeping the index or column headers row.
<s>We also add the `show` keyword to allow the method to operate inversely.</s>
@jreback I think you will prefer this over the `hide_values` and `hide_headers` methods suggested in #41158 since this re-uses the existing methods with minimal changes but tries to align their consistency. It is also fully backwards compatible.
| https://api.github.com/repos/pandas-dev/pandas/pulls/41266 | 2021-05-02T16:02:20Z | 2021-06-16T00:22:53Z | 2021-06-16T00:22:53Z | 2021-07-27T18:03:50Z |
REF: avoid unnecessary raise in DataFrameGroupBy._cython_agg_general | diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 1aa08356982d2..693b1832ed3c9 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -360,7 +360,10 @@ def agg_list_like(self) -> FrameOrSeriesUnion:
# raised directly in _aggregate_named
pass
elif "no results" in str(err):
- # raised directly in _aggregate_multiple_funcs
+ # reached in test_frame_apply.test_nuiscance_columns
+ # where the colg.aggregate(arg) ends up going through
+ # the selected_obj.ndim == 1 branch above with arg == ["sum"]
+ # on a datetime64[ns] column
pass
else:
raise
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index fd4b0cfa87950..27e07deb69e9c 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1110,6 +1110,7 @@ def _cython_agg_general(
# Note: we never get here with how="ohlc"; that goes through SeriesGroupBy
data: Manager2D = self._get_data_to_aggregate()
+ orig = data
if numeric_only:
data = data.get_numeric_data(copy=False)
@@ -1187,7 +1188,8 @@ def array_func(values: ArrayLike) -> ArrayLike:
# continue and exclude the block
new_mgr = data.grouped_reduce(array_func, ignore_failures=True)
- if not len(new_mgr):
+ if not len(new_mgr) and len(orig):
+ # If the original Manager was already empty, no need to raise
raise DataError("No numeric types to aggregate")
return self._wrap_agged_manager(new_mgr)
| Untangling these layered try/excepts is turning out to be an exceptional PITA, so splitting it into extra-small pieces. | https://api.github.com/repos/pandas-dev/pandas/pulls/41265 | 2021-05-02T15:40:41Z | 2021-05-03T15:14:58Z | 2021-05-03T15:14:58Z | 2021-05-03T16:51:38Z |
BUG: RangeIndex.astype('category') | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 794a7025fe218..7def8f6bdb2bc 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -780,6 +780,7 @@ Indexing
- Bug in :meth:`DatetimeIndex.insert` when inserting ``np.datetime64("NaT")`` into a timezone-aware index incorrectly treating the timezone-naive value as timezone-aware (:issue:`39769`)
- Bug in incorrectly raising in :meth:`Index.insert`, when setting a new column that cannot be held in the existing ``frame.columns``, or in :meth:`Series.reset_index` or :meth:`DataFrame.reset_index` instead of casting to a compatible dtype (:issue:`39068`)
- Bug in :meth:`RangeIndex.append` where a single object of length 1 was concatenated incorrectly (:issue:`39401`)
+- Bug in :meth:`RangeIndex.astype` where when converting to :class:`CategoricalIndex`, the categories became a :class:`Int64Index` instead of a :class:`RangeIndex` (:issue:`41263`)
- Bug in setting ``numpy.timedelta64`` values into an object-dtype :class:`Series` using a boolean indexer (:issue:`39488`)
- Bug in setting numeric values into a into a boolean-dtypes :class:`Series` using ``at`` or ``iat`` failing to cast to object-dtype (:issue:`39582`)
- Bug in :meth:`DataFrame.__setitem__` and :meth:`DataFrame.iloc.__setitem__` raising ``ValueError`` when trying to index with a row-slice and setting a list as values (:issue:`40440`)
@@ -945,6 +946,7 @@ Other
- Bug in :meth:`Series.where` with numeric dtype and ``other = None`` not casting to ``nan`` (:issue:`39761`)
- :meth:`Index.where` behavior now mirrors :meth:`Index.putmask` behavior, i.e. ``index.where(mask, other)`` matches ``index.putmask(~mask, other)`` (:issue:`39412`)
- Bug in :func:`pandas.testing.assert_series_equal`, :func:`pandas.testing.assert_frame_equal`, :func:`pandas.testing.assert_index_equal` and :func:`pandas.testing.assert_extension_array_equal` incorrectly raising when an attribute has an unrecognized NA type (:issue:`39461`)
+- Bug in :func:`pandas.testing.assert_index_equal` with ``exact=True`` not raising when comparing :class:`CategoricalIndex` instances with ``Int64Index`` and ``RangeIndex`` categories (:issue:`41263`)
- Bug in :meth:`DataFrame.equals`, :meth:`Series.equals`, :meth:`Index.equals` with object-dtype containing ``np.datetime64("NaT")`` or ``np.timedelta64("NaT")`` (:issue:`39650`)
- Bug in :func:`pandas.util.show_versions` where console JSON output was not proper JSON (:issue:`39701`)
- Bug in :meth:`DataFrame.convert_dtypes` incorrectly raised ValueError when called on an empty DataFrame (:issue:`40393`)
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index 912039b7571bc..2d695458e32e6 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -309,18 +309,22 @@ def assert_index_equal(
__tracebackhide__ = True
def _check_types(left, right, obj="Index"):
- if exact:
- assert_class_equal(left, right, exact=exact, obj=obj)
+ if not exact:
+ return
- # Skip exact dtype checking when `check_categorical` is False
- if check_categorical:
- assert_attr_equal("dtype", left, right, obj=obj)
+ assert_class_equal(left, right, exact=exact, obj=obj)
- # allow string-like to have different inferred_types
- if left.inferred_type in ("string"):
- assert right.inferred_type in ("string")
- else:
- assert_attr_equal("inferred_type", left, right, obj=obj)
+ # Skip exact dtype checking when `check_categorical` is False
+ if check_categorical:
+ assert_attr_equal("dtype", left, right, obj=obj)
+ if is_categorical_dtype(left.dtype) and is_categorical_dtype(right.dtype):
+ assert_index_equal(left.categories, right.categories, exact=exact)
+
+ # allow string-like to have different inferred_types
+ if left.inferred_type in ("string"):
+ assert right.inferred_type in ("string")
+ else:
+ assert_attr_equal("inferred_type", left, right, obj=obj)
def _get_ilevel_values(index, level):
# accept level number only
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 7779335bfd3ba..6f414c91ce94c 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -907,9 +907,7 @@ def astype(self, dtype, copy=True):
elif is_categorical_dtype(dtype):
from pandas.core.indexes.category import CategoricalIndex
- return CategoricalIndex(
- self._values, name=self.name, dtype=dtype, copy=copy
- )
+ return CategoricalIndex(self, name=self.name, dtype=dtype, copy=copy)
elif is_extension_array_dtype(dtype):
return Index(np.asarray(self), name=self.name, dtype=dtype, copy=copy)
diff --git a/pandas/tests/indexes/categorical/test_constructors.py b/pandas/tests/indexes/categorical/test_constructors.py
index 2acf79ee0bced..35620875d5a1a 100644
--- a/pandas/tests/indexes/categorical/test_constructors.py
+++ b/pandas/tests/indexes/categorical/test_constructors.py
@@ -108,8 +108,8 @@ def test_construction_with_dtype(self):
tm.assert_index_equal(result, ci, exact=True)
# make sure indexes are handled
- expected = CategoricalIndex([0, 1, 2], categories=[0, 1, 2], ordered=True)
idx = Index(range(3))
+ expected = CategoricalIndex([0, 1, 2], categories=idx, ordered=True)
result = CategoricalIndex(idx, categories=idx, ordered=True)
tm.assert_index_equal(result, expected, exact=True)
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 6139d8af48d98..8bbe8f9b9e0e2 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -667,20 +667,20 @@ def test_astype_category(self, copy, name, ordered, simple_index):
# standard categories
dtype = CategoricalDtype(ordered=ordered)
result = idx.astype(dtype, copy=copy)
- expected = CategoricalIndex(idx.values, name=name, ordered=ordered)
- tm.assert_index_equal(result, expected)
+ expected = CategoricalIndex(idx, name=name, ordered=ordered)
+ tm.assert_index_equal(result, expected, exact=True)
# non-standard categories
dtype = CategoricalDtype(idx.unique().tolist()[:-1], ordered)
result = idx.astype(dtype, copy=copy)
- expected = CategoricalIndex(idx.values, name=name, dtype=dtype)
- tm.assert_index_equal(result, expected)
+ expected = CategoricalIndex(idx, name=name, dtype=dtype)
+ tm.assert_index_equal(result, expected, exact=True)
if ordered is False:
# dtype='category' defaults to ordered=False, so only test once
result = idx.astype("category", copy=copy)
- expected = CategoricalIndex(idx.values, name=name)
- tm.assert_index_equal(result, expected)
+ expected = CategoricalIndex(idx, name=name)
+ tm.assert_index_equal(result, expected, exact=True)
def test_is_unique(self, simple_index):
# initialize a unique index
diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py
index 82a3a223b442b..1778b6fb9d832 100644
--- a/pandas/tests/util/test_assert_index_equal.py
+++ b/pandas/tests/util/test_assert_index_equal.py
@@ -3,9 +3,11 @@
from pandas import (
Categorical,
+ CategoricalIndex,
Index,
MultiIndex,
NaT,
+ RangeIndex,
)
import pandas._testing as tm
@@ -199,6 +201,28 @@ def test_index_equal_category_mismatch(check_categorical):
tm.assert_index_equal(idx1, idx2, check_categorical=check_categorical)
+@pytest.mark.parametrize("exact", [False, True])
+def test_index_equal_range_categories(check_categorical, exact):
+ # GH41263
+ msg = """\
+Index are different
+
+Index classes are different
+\\[left\\]: RangeIndex\\(start=0, stop=10, step=1\\)
+\\[right\\]: Int64Index\\(\\[0, 1, 2, 3, 4, 5, 6, 7, 8, 9\\], dtype='int64'\\)"""
+
+ rcat = CategoricalIndex(RangeIndex(10))
+ icat = CategoricalIndex(list(range(10)))
+
+ if check_categorical and exact:
+ with pytest.raises(AssertionError, match=msg):
+ tm.assert_index_equal(rcat, icat, check_categorical=True, exact=True)
+ else:
+ tm.assert_index_equal(
+ rcat, icat, check_categorical=check_categorical, exact=exact
+ )
+
+
def test_assert_index_equal_mixed_dtype():
# GH#39168
idx = Index(["foo", "bar", 42])
| There's currently inconsistent behaviour when converting `RangeIndex` to `CategoricalIndex` using different methods. This fixes that.
```python
>>> ridx = pd.RangeIndex(5)
>>> pd.CategoricalIndex(ridx).categories
RangeIndex(start=0, stop=5, step=1) # both master and this PR
>>> ridx.astype("category").categories
Int64Index([0, 1, 2, 3, 4], dtype='int64') # master
RangeIndex(start=0, stop=5, step=1) # this PR
```
In general, when supplying a Index subclass to `Categorical`/`CategoricalIndex`, the new categories should be of that type (unless the supplied index is a `CategoricalIndex` itself).
Discovered working on tests for #41153. | https://api.github.com/repos/pandas-dev/pandas/pulls/41263 | 2021-05-02T10:46:15Z | 2021-05-05T12:39:13Z | 2021-05-05T12:39:13Z | 2021-05-05T13:41:07Z |
REF: simplify libreduction | diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index 191967585c431..d0f85b75a629e 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -53,24 +53,24 @@ cdef class _BaseGrouper:
return values, index
+ cdef _init_dummy_series_and_index(self, Slider islider, Slider vslider):
+ """
+ Create Series and Index objects that we will alter in-place while iterating.
+ """
+ cached_index = self.ityp(islider.buf, dtype=self.idtype)
+ cached_series = self.typ(
+ vslider.buf, dtype=vslider.buf.dtype, index=cached_index, name=self.name
+ )
+ return cached_index, cached_series
+
cdef inline _update_cached_objs(self, object cached_typ, object cached_ityp,
Slider islider, Slider vslider):
- if cached_typ is None:
- cached_ityp = self.ityp(islider.buf, dtype=self.idtype)
- cached_typ = self.typ(
- vslider.buf, dtype=vslider.buf.dtype, index=cached_ityp, name=self.name
- )
- else:
- # See the comment in indexes/base.py about _index_data.
- # We need this for EA-backed indexes that have a reference
- # to a 1-d ndarray like datetime / timedelta / period.
- object.__setattr__(cached_ityp, '_index_data', islider.buf)
- cached_ityp._engine.clear_mapping()
- cached_ityp._cache.clear() # e.g. inferred_freq must go
- cached_typ._mgr.set_values(vslider.buf)
- object.__setattr__(cached_typ, '_index', cached_ityp)
- object.__setattr__(cached_typ, 'name', self.name)
- return cached_typ, cached_ityp
+ # See the comment in indexes/base.py about _index_data.
+ # We need this for EA-backed indexes that have a reference
+ # to a 1-d ndarray like datetime / timedelta / period.
+ cached_ityp._engine.clear_mapping()
+ cached_ityp._cache.clear() # e.g. inferred_freq must go
+ cached_typ._mgr.set_values(vslider.buf)
cdef inline object _apply_to_group(self,
object cached_typ, object cached_ityp,
@@ -81,8 +81,8 @@ cdef class _BaseGrouper:
cdef:
object res
- cached_ityp._engine.clear_mapping()
- cached_ityp._cache.clear() # e.g. inferred_freq must go
+ # NB: we assume that _update_cached_objs has already cleared cleared
+ # the cache and engine mapping
res = self.f(cached_typ)
res = extract_result(res)
if not initialized:
@@ -160,6 +160,8 @@ cdef class SeriesBinGrouper(_BaseGrouper):
result = np.empty(self.ngroups, dtype='O')
+ cached_ityp, cached_typ = self._init_dummy_series_and_index(islider, vslider)
+
start = 0
try:
for i in range(self.ngroups):
@@ -169,7 +171,7 @@ cdef class SeriesBinGrouper(_BaseGrouper):
islider.move(start, end)
vslider.move(start, end)
- cached_typ, cached_ityp = self._update_cached_objs(
+ self._update_cached_objs(
cached_typ, cached_ityp, islider, vslider)
res, initialized = self._apply_to_group(cached_typ, cached_ityp,
@@ -246,6 +248,8 @@ cdef class SeriesGrouper(_BaseGrouper):
result = np.empty(self.ngroups, dtype='O')
+ cached_ityp, cached_typ = self._init_dummy_series_and_index(islider, vslider)
+
start = 0
try:
for i in range(n):
@@ -263,7 +267,7 @@ cdef class SeriesGrouper(_BaseGrouper):
islider.move(start, end)
vslider.move(start, end)
- cached_typ, cached_ityp = self._update_cached_objs(
+ self._update_cached_objs(
cached_typ, cached_ityp, islider, vslider)
res, initialized = self._apply_to_group(cached_typ, cached_ityp,
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41262 | 2021-05-02T04:19:33Z | 2021-05-02T23:10:17Z | 2021-05-02T23:10:17Z | 2021-05-03T01:19:36Z |
COMPAT: fix _bootlocale import error on py310 | diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py
index 6731c481f8935..abc65f2f1eda1 100644
--- a/pandas/tests/io/json/test_readlines.py
+++ b/pandas/tests/io/json/test_readlines.py
@@ -192,7 +192,7 @@ def test_readjson_chunks_multiple_empty_lines(chunksize):
def test_readjson_unicode(monkeypatch):
with tm.ensure_clean("test.json") as path:
- monkeypatch.setattr("_bootlocale.getpreferredencoding", lambda l: "cp949")
+ monkeypatch.setattr("locale.getpreferredencoding", lambda l: "cp949")
with open(path, "w", encoding="utf-8") as f:
f.write('{"£©µÀÆÖÞßéöÿ":["АБВГДабвгд가"]}')
| The _bootlocale module has been removed from Python 3.10.
https://github.com/python/cpython/commit/b62bdf71ea0cd52041d49691d8ae3dc645bd48e1 | https://api.github.com/repos/pandas-dev/pandas/pulls/41261 | 2021-05-02T02:51:41Z | 2021-05-02T23:11:52Z | 2021-05-02T23:11:52Z | 2022-11-18T02:21:52Z |
TYP: ExtensionArray unique and repeat | diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 5a2643dd531ed..bd01191719143 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -794,7 +794,7 @@ def shift(self, periods: int = 1, fill_value: object = None) -> ExtensionArray:
b = empty
return self._concat_same_type([a, b])
- def unique(self):
+ def unique(self: ExtensionArrayT) -> ExtensionArrayT:
"""
Compute the ExtensionArray of unique values.
@@ -1023,7 +1023,7 @@ def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]:
@Substitution(klass="ExtensionArray")
@Appender(_extension_array_shared_docs["repeat"])
- def repeat(self, repeats, axis=None):
+ def repeat(self, repeats: int | Sequence[int], axis: int | None = None):
nv.validate_repeat((), {"axis": axis})
ind = np.arange(len(self)).repeat(repeats)
return self.take(ind)
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 50e8cc4c82e0d..95c95d98bc968 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -1518,7 +1518,11 @@ def delete(self: IntervalArrayT, loc) -> IntervalArrayT:
return self._shallow_copy(left=new_left, right=new_right)
@Appender(_extension_array_shared_docs["repeat"] % _shared_docs_kwargs)
- def repeat(self: IntervalArrayT, repeats: int, axis=None) -> IntervalArrayT:
+ def repeat(
+ self: IntervalArrayT,
+ repeats: int | Sequence[int],
+ axis: int | None = None,
+ ) -> IntervalArrayT:
nv.validate_repeat((), {"axis": axis})
left_repeat = self.left.repeat(repeats)
right_repeat = self.right.repeat(repeats)
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 42f52618eb07b..e1e36d6d226c4 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -16,6 +16,7 @@
import pandas._libs.lib as lib
from pandas._typing import (
+ ArrayLike,
Dtype,
DtypeObj,
IndexLabel,
@@ -996,7 +997,7 @@ def unique(self):
values = self._values
if not isinstance(values, np.ndarray):
- result = values.unique()
+ result: ArrayLike = values.unique()
if self.dtype.kind in ["m", "M"] and isinstance(self, ABCSeries):
# GH#31182 Series._values returns EA, unpack for backward-compat
if getattr(self.dtype, "tz", None) is None:
| Typing fixes for `ExtensionArray.unique()` and `ExtensionArray.repeat()`
| https://api.github.com/repos/pandas-dev/pandas/pulls/41260 | 2021-05-02T01:33:00Z | 2021-05-03T12:46:14Z | 2021-05-03T12:46:14Z | 2021-05-03T13:00:03Z |
fix(documentation/user_guides/indexing): Highlight `where`, add Todo for "wrong" example | diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst
index dc66303a44f53..20c608cb44802 100644
--- a/doc/source/user_guide/indexing.rst
+++ b/doc/source/user_guide/indexing.rst
@@ -1093,10 +1093,11 @@ partial setting via ``.loc`` (but on the contents rather than the axis labels).
.. ipython:: python
df2 = df.copy()
+ #TODO: replace with example actually using ``where`` like in info text above
df2[df2[1:4] > 0] = 3
df2
-Where can also accept ``axis`` and ``level`` parameters to align the input when
+``where`` can also accept ``axis`` and ``level`` parameters to align the input when
performing the ``where``.
.. ipython:: python
| - [X] add Todo marker for "wrong" example (description said `where` should be used but actually it isn't)
- [ ] add actual example using `where` (beyond my skillset)
| https://api.github.com/repos/pandas-dev/pandas/pulls/41259 | 2021-05-02T00:16:53Z | 2021-05-24T19:31:03Z | null | 2021-05-24T19:31:03Z |
TYP: Typing for ExtensionArray.__getitem__ | diff --git a/pandas/_typing.py b/pandas/_typing.py
index 93d49497a85e0..5077e659410e3 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -206,10 +206,16 @@
# indexing
# PositionalIndexer -> valid 1D positional indexer, e.g. can pass
# to ndarray.__getitem__
+# ScalarIndexer is for a single value as the index
+# SequenceIndexer is for list like or slices (but not tuples)
+# PositionalIndexerTuple is extends the PositionalIndexer for 2D arrays
+# These are used in various __getitem__ overloads
# TODO: add Ellipsis, see
# https://github.com/python/typing/issues/684#issuecomment-548203158
# https://bugs.python.org/issue41810
-PositionalIndexer = Union[int, np.integer, slice, Sequence[int], np.ndarray]
-PositionalIndexer2D = Union[
- PositionalIndexer, Tuple[PositionalIndexer, PositionalIndexer]
-]
+# Using List[int] here rather than Sequence[int] to disallow tuples.
+ScalarIndexer = Union[int, np.integer]
+SequenceIndexer = Union[slice, List[int], np.ndarray]
+PositionalIndexer = Union[ScalarIndexer, SequenceIndexer]
+PositionalIndexerTuple = Tuple[PositionalIndexer, PositionalIndexer]
+PositionalIndexer2D = Union[PositionalIndexer, PositionalIndexerTuple]
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index f13f1a418c2e9..4c7ccc2f16477 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -4,9 +4,11 @@
from typing import (
TYPE_CHECKING,
Any,
+ Literal,
Sequence,
TypeVar,
cast,
+ overload,
)
import numpy as np
@@ -16,6 +18,9 @@
from pandas._typing import (
F,
PositionalIndexer2D,
+ PositionalIndexerTuple,
+ ScalarIndexer,
+ SequenceIndexer,
Shape,
npt,
type_t,
@@ -48,7 +53,6 @@
)
if TYPE_CHECKING:
- from typing import Literal
from pandas._typing import (
NumpySorter,
@@ -205,6 +209,17 @@ def __setitem__(self, key, value):
def _validate_setitem_value(self, value):
return value
+ @overload
+ def __getitem__(self, key: ScalarIndexer) -> Any:
+ ...
+
+ @overload
+ def __getitem__(
+ self: NDArrayBackedExtensionArrayT,
+ key: SequenceIndexer | PositionalIndexerTuple,
+ ) -> NDArrayBackedExtensionArrayT:
+ ...
+
def __getitem__(
self: NDArrayBackedExtensionArrayT,
key: PositionalIndexer2D,
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index b0b7b81d059e6..40837ccad6ac8 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -30,6 +30,8 @@
Dtype,
FillnaOptions,
PositionalIndexer,
+ ScalarIndexer,
+ SequenceIndexer,
Shape,
npt,
)
@@ -298,8 +300,17 @@ def _from_factorized(cls, values, original):
# ------------------------------------------------------------------------
# Must be a Sequence
# ------------------------------------------------------------------------
+ @overload
+ def __getitem__(self, item: ScalarIndexer) -> Any:
+ ...
+
+ @overload
+ def __getitem__(self: ExtensionArrayT, item: SequenceIndexer) -> ExtensionArrayT:
+ ...
- def __getitem__(self, item: PositionalIndexer) -> ExtensionArray | Any:
+ def __getitem__(
+ self: ExtensionArrayT, item: PositionalIndexer
+ ) -> ExtensionArrayT | Any:
"""
Select a subset of self.
@@ -313,6 +324,8 @@ def __getitem__(self, item: PositionalIndexer) -> ExtensionArray | Any:
* ndarray: A 1-d boolean NumPy ndarray the same length as 'self'
+ * list[int]: A list of int
+
Returns
-------
item : scalar or ExtensionArray
@@ -761,7 +774,7 @@ def fillna(
new_values = self.copy()
return new_values
- def dropna(self):
+ def dropna(self: ExtensionArrayT) -> ExtensionArrayT:
"""
Return ExtensionArray without NA values.
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index b8ceef3d52e41..543b018c07ea5 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -6,6 +6,7 @@
from shutil import get_terminal_size
from typing import (
TYPE_CHECKING,
+ Any,
Hashable,
Sequence,
TypeVar,
@@ -37,7 +38,11 @@
Dtype,
NpDtype,
Ordered,
+ PositionalIndexer2D,
+ PositionalIndexerTuple,
Scalar,
+ ScalarIndexer,
+ SequenceIndexer,
Shape,
npt,
type_t,
@@ -2017,7 +2022,18 @@ def __repr__(self) -> str:
# ------------------------------------------------------------------
- def __getitem__(self, key):
+ @overload
+ def __getitem__(self, key: ScalarIndexer) -> Any:
+ ...
+
+ @overload
+ def __getitem__(
+ self: CategoricalT,
+ key: SequenceIndexer | PositionalIndexerTuple,
+ ) -> CategoricalT:
+ ...
+
+ def __getitem__(self: CategoricalT, key: PositionalIndexer2D) -> CategoricalT | Any:
"""
Return an item.
"""
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index ad3120c9c27d3..63ba9fdd59fc6 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -49,6 +49,9 @@
DtypeObj,
NpDtype,
PositionalIndexer2D,
+ PositionalIndexerTuple,
+ ScalarIndexer,
+ SequenceIndexer,
npt,
)
from pandas.compat.numpy import function as nv
@@ -313,17 +316,33 @@ def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
return np.array(list(self), dtype=object)
return self._ndarray
+ @overload
+ def __getitem__(self, item: ScalarIndexer) -> DTScalarOrNaT:
+ ...
+
+ @overload
def __getitem__(
- self, key: PositionalIndexer2D
- ) -> DatetimeLikeArrayMixin | DTScalarOrNaT:
+ self: DatetimeLikeArrayT,
+ item: SequenceIndexer | PositionalIndexerTuple,
+ ) -> DatetimeLikeArrayT:
+ ...
+
+ def __getitem__(
+ self: DatetimeLikeArrayT, key: PositionalIndexer2D
+ ) -> DatetimeLikeArrayT | DTScalarOrNaT:
"""
This getitem defers to the underlying array, which by-definition can
only handle list-likes, slices, and integer scalars
"""
- result = super().__getitem__(key)
+ # Use cast as we know we will get back a DatetimeLikeArray or DTScalar
+ result = cast(
+ Union[DatetimeLikeArrayT, DTScalarOrNaT], super().__getitem__(key)
+ )
if lib.is_scalar(result):
return result
-
+ else:
+ # At this point we know the result is an array.
+ result = cast(DatetimeLikeArrayT, result)
result._freq = self._get_getitem_freq(key)
return result
@@ -1768,11 +1787,7 @@ def factorize(self, na_sentinel=-1, sort: bool = False):
uniques = self.copy() # TODO: copy or view?
if sort and self.freq.n < 0:
codes = codes[::-1]
- # TODO: overload __getitem__, a slice indexer returns same type as self
- # error: Incompatible types in assignment (expression has type
- # "Union[DatetimeLikeArrayMixin, Union[Any, Any]]", variable
- # has type "TimelikeOps")
- uniques = uniques[::-1] # type: ignore[assignment]
+ uniques = uniques[::-1]
return codes, uniques
# FIXME: shouldn't get here; we are ignoring sort
return super().factorize(na_sentinel=na_sentinel)
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index e82b81d55807d..823103181bb82 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -9,7 +9,6 @@
from typing import (
TYPE_CHECKING,
Literal,
- cast,
overload,
)
import warnings
@@ -478,11 +477,9 @@ def _generate_range(
index = cls._simple_new(arr, freq=None, dtype=dtype)
if not left_closed and len(index) and index[0] == start:
- # TODO: overload DatetimeLikeArrayMixin.__getitem__
- index = cast(DatetimeArray, index[1:])
+ index = index[1:]
if not right_closed and len(index) and index[-1] == end:
- # TODO: overload DatetimeLikeArrayMixin.__getitem__
- index = cast(DatetimeArray, index[:-1])
+ index = index[:-1]
dtype = tz_to_dtype(tz)
return cls._simple_new(index._ndarray, freq=freq, dtype=dtype)
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 41998218acd7d..732bdb112b8c3 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -9,7 +9,9 @@
from typing import (
Sequence,
TypeVar,
+ Union,
cast,
+ overload,
)
import numpy as np
@@ -31,6 +33,9 @@
ArrayLike,
Dtype,
NpDtype,
+ PositionalIndexer,
+ ScalarIndexer,
+ SequenceIndexer,
)
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender
@@ -89,6 +94,7 @@
)
IntervalArrayT = TypeVar("IntervalArrayT", bound="IntervalArray")
+IntervalOrNA = Union[Interval, float]
_interval_shared_docs: dict[str, str] = {}
@@ -635,7 +641,17 @@ def __iter__(self):
def __len__(self) -> int:
return len(self._left)
- def __getitem__(self, key):
+ @overload
+ def __getitem__(self, key: ScalarIndexer) -> IntervalOrNA:
+ ...
+
+ @overload
+ def __getitem__(self: IntervalArrayT, key: SequenceIndexer) -> IntervalArrayT:
+ ...
+
+ def __getitem__(
+ self: IntervalArrayT, key: PositionalIndexer
+ ) -> IntervalArrayT | IntervalOrNA:
key = check_array_indexer(self, key)
left = self._left[key]
right = self._right[key]
@@ -1633,10 +1649,11 @@ def _from_combined(self, combined: np.ndarray) -> IntervalArray:
return self._shallow_copy(left=new_left, right=new_right)
def unique(self) -> IntervalArray:
- # Invalid index type "Tuple[slice, int]" for "Union[ExtensionArray,
- # ndarray[Any, Any]]"; expected type "Union[int, integer[Any], slice,
- # Sequence[int], ndarray[Any, Any]]"
- nc = unique(self._combined.view("complex128")[:, 0]) # type: ignore[index]
+ # No overload variant of "__getitem__" of "ExtensionArray" matches argument
+ # type "Tuple[slice, int]"
+ nc = unique(
+ self._combined.view("complex128")[:, 0] # type: ignore[call-overload]
+ )
nc = nc[:, None]
return self._from_combined(nc)
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index cccfd58aa914d..877babe4f18e8 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -20,6 +20,8 @@
NpDtype,
PositionalIndexer,
Scalar,
+ ScalarIndexer,
+ SequenceIndexer,
npt,
type_t,
)
@@ -139,7 +141,17 @@ def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False):
def dtype(self) -> BaseMaskedDtype:
raise AbstractMethodError(self)
- def __getitem__(self, item: PositionalIndexer) -> BaseMaskedArray | Any:
+ @overload
+ def __getitem__(self, item: ScalarIndexer) -> Any:
+ ...
+
+ @overload
+ def __getitem__(self: BaseMaskedArrayT, item: SequenceIndexer) -> BaseMaskedArrayT:
+ ...
+
+ def __getitem__(
+ self: BaseMaskedArrayT, item: PositionalIndexer
+ ) -> BaseMaskedArrayT | Any:
if is_integer(item):
if self._mask[item]:
return self.dtype.na_value
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 2db1f00e237ee..84e611659b165 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -6,6 +6,7 @@
TYPE_CHECKING,
Any,
Callable,
+ Literal,
Sequence,
)
@@ -76,7 +77,6 @@
import pandas.core.common as com
if TYPE_CHECKING:
- from typing import Literal
from pandas._typing import (
NumpySorter,
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 6dce9b4475d1b..77142ef450487 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -10,8 +10,11 @@
TYPE_CHECKING,
Any,
Callable,
+ Literal,
Sequence,
TypeVar,
+ cast,
+ overload,
)
import warnings
@@ -30,7 +33,10 @@
AstypeArg,
Dtype,
NpDtype,
+ PositionalIndexer,
Scalar,
+ ScalarIndexer,
+ SequenceIndexer,
npt,
)
from pandas.compat.numpy import function as nv
@@ -81,11 +87,21 @@
import pandas.io.formats.printing as printing
+# See https://github.com/python/typing/issues/684
if TYPE_CHECKING:
- from typing import Literal
+ from enum import Enum
+
+ class ellipsis(Enum):
+ Ellipsis = "..."
+
+ Ellipsis = ellipsis.Ellipsis
from pandas._typing import NumpySorter
+else:
+ ellipsis = type(Ellipsis)
+
+
# ----------------------------------------------------------------------------
# Array
@@ -813,8 +829,21 @@ def value_counts(self, dropna: bool = True):
# --------
# Indexing
# --------
+ @overload
+ def __getitem__(self, key: ScalarIndexer) -> Any:
+ ...
+
+ @overload
+ def __getitem__(
+ self: SparseArrayT,
+ key: SequenceIndexer | tuple[int | ellipsis, ...],
+ ) -> SparseArrayT:
+ ...
- def __getitem__(self, key):
+ def __getitem__(
+ self: SparseArrayT,
+ key: PositionalIndexer | tuple[int | ellipsis, ...],
+ ) -> SparseArrayT | Any:
if isinstance(key, tuple):
if len(key) > 1:
@@ -824,6 +853,8 @@ def __getitem__(self, key):
key = key[:-1]
if len(key) > 1:
raise IndexError("too many indices for array.")
+ if key[0] is Ellipsis:
+ raise ValueError("Cannot slice with Ellipsis")
key = key[0]
if is_integer(key):
@@ -852,7 +883,8 @@ def __getitem__(self, key):
key = check_array_indexer(self, key)
if com.is_bool_indexer(key):
-
+ # mypy doesn't know we have an array here
+ key = cast(np.ndarray, key)
return self.take(np.arange(len(key), dtype=np.int32)[key])
elif hasattr(key, "__len__"):
return self.take(key)
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index ab8599f0f05ba..4be7f4eb0c521 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -6,17 +6,24 @@
TYPE_CHECKING,
Any,
Sequence,
+ Union,
cast,
+ overload,
)
import numpy as np
-from pandas._libs import lib
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+)
from pandas._typing import (
Dtype,
NpDtype,
PositionalIndexer,
Scalar,
+ ScalarIndexer,
+ SequenceIndexer,
)
from pandas.compat import (
pa_version_under1p0,
@@ -77,6 +84,8 @@
if TYPE_CHECKING:
from pandas import Series
+ArrowStringScalarOrNAT = Union[str, libmissing.NAType]
+
def _chk_pyarrow_available() -> None:
if pa_version_under1p0:
@@ -260,7 +269,17 @@ def _concat_same_type(cls, to_concat) -> ArrowStringArray:
)
)
- def __getitem__(self, item: PositionalIndexer) -> Any:
+ @overload
+ def __getitem__(self, item: ScalarIndexer) -> ArrowStringScalarOrNAT:
+ ...
+
+ @overload
+ def __getitem__(self: ArrowStringArray, item: SequenceIndexer) -> ArrowStringArray:
+ ...
+
+ def __getitem__(
+ self: ArrowStringArray, item: PositionalIndexer
+ ) -> ArrowStringArray | ArrowStringScalarOrNAT:
"""Select a subset of self.
Parameters
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 0e358e611f418..ec8775cf78571 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -2984,10 +2984,9 @@ def blk_func(values: ArrayLike) -> ArrayLike:
if real_2d and values.ndim == 1:
assert result.shape[1] == 1, result.shape
- # error: Invalid index type "Tuple[slice, int]" for
- # "Union[ExtensionArray, ndarray[Any, Any]]"; expected type
- # "Union[int, integer[Any], slice, Sequence[int], ndarray[Any, Any]]"
- result = result[:, 0] # type: ignore[index]
+ # error: No overload variant of "__getitem__" of "ExtensionArray"
+ # matches argument type "Tuple[slice, int]"
+ result = result[:, 0] # type: ignore[call-overload]
if needs_mask:
mask = mask[:, 0]
@@ -3001,11 +3000,9 @@ def blk_func(values: ArrayLike) -> ArrayLike:
if needs_2d and not real_2d:
if result.ndim == 2:
assert result.shape[1] == 1
- # error: Invalid index type "Tuple[slice, int]" for
- # "Union[ExtensionArray, Any, ndarray[Any, Any]]"; expected
- # type "Union[int, integer[Any], slice, Sequence[int],
- # ndarray[Any, Any]]"
- result = result[:, 0] # type: ignore[index]
+ # error: No overload variant of "__getitem__" of "ExtensionArray"
+ # matches argument type "Tuple[slice, int]"
+ result = result[:, 0] # type: ignore[call-overload]
return result.T
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 645fab0d76a73..c73b3e99600d6 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4803,11 +4803,7 @@ def __getitem__(self, key):
result = getitem(key)
if not is_scalar(result):
- # error: Argument 1 to "ndim" has incompatible type "Union[ExtensionArray,
- # Any]"; expected "Union[Union[int, float, complex, str, bytes, generic],
- # Sequence[Union[int, float, complex, str, bytes, generic]],
- # Sequence[Sequence[Any]], _SupportsArray]"
- if np.ndim(result) > 1: # type: ignore[arg-type]
+ if np.ndim(result) > 1:
deprecate_ndim_indexing(result)
return result
# NB: Using _constructor._simple_new would break if MultiIndex
@@ -5122,13 +5118,17 @@ def asof_locs(self, where: Index, mask: np.ndarray) -> npt.NDArray[np.intp]:
which correspond to the return values of the `asof` function
for every element in `where`.
"""
- locs = self._values[mask].searchsorted(where._values, side="right")
+ # error: No overload variant of "searchsorted" of "ndarray" matches argument
+ # types "Union[ExtensionArray, ndarray[Any, Any]]", "str"
+ # TODO: will be fixed when ExtensionArray.searchsorted() is fixed
+ locs = self._values[mask].searchsorted(
+ where._values, side="right" # type: ignore[call-overload]
+ )
locs = np.where(locs > 0, locs - 1, 0)
result = np.arange(len(self), dtype=np.intp)[mask].take(locs)
- # TODO: overload return type of ExtensionArray.__getitem__
- first_value = cast(Any, self._values[mask.argmax()])
+ first_value = self._values[mask.argmax()]
result[(locs == 0) & (where._values < first_value)] = -1
return result
diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py
index 920af5a13baba..b446dfe045e62 100644
--- a/pandas/core/indexes/extension.py
+++ b/pandas/core/indexes/extension.py
@@ -6,6 +6,7 @@
from typing import (
TYPE_CHECKING,
Hashable,
+ Literal,
TypeVar,
overload,
)
@@ -47,7 +48,6 @@
from pandas.core.ops import get_op_result_name
if TYPE_CHECKING:
- from typing import Literal
from pandas._typing import (
NumpySorter,
diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index 475bfe958ea06..f645cc81e8171 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -315,10 +315,9 @@ def apply_with_block(self: T, f, align_keys=None, swap_axis=True, **kwargs) -> T
if self.ndim == 2 and arr.ndim == 2:
# 2D for np.ndarray or DatetimeArray/TimedeltaArray
assert len(arr) == 1
- # error: Invalid index type "Tuple[int, slice]" for
- # "Union[ndarray, ExtensionArray]"; expected type
- # "Union[int, slice, ndarray]"
- arr = arr[0, :] # type: ignore[index]
+ # error: No overload variant of "__getitem__" of "ExtensionArray"
+ # matches argument type "Tuple[int, slice]"
+ arr = arr[0, :] # type: ignore[call-overload]
result_arrays.append(arr)
return type(self)(result_arrays, self._axes)
@@ -841,10 +840,9 @@ def iset(self, loc: int | slice | np.ndarray, value: ArrayLike):
assert value.shape[0] == len(self._axes[0])
for value_idx, mgr_idx in enumerate(indices):
- # error: Invalid index type "Tuple[slice, int]" for
- # "Union[ExtensionArray, ndarray]"; expected type
- # "Union[int, slice, ndarray]"
- value_arr = value[:, value_idx] # type: ignore[index]
+ # error: No overload variant of "__getitem__" of "ExtensionArray" matches
+ # argument type "Tuple[slice, int]"
+ value_arr = value[:, value_idx] # type: ignore[call-overload]
self.arrays[mgr_idx] = value_arr
return
@@ -864,10 +862,9 @@ def insert(self, loc: int, item: Hashable, value: ArrayLike) -> None:
value = extract_array(value, extract_numpy=True)
if value.ndim == 2:
if value.shape[0] == 1:
- # error: Invalid index type "Tuple[int, slice]" for
- # "Union[Any, ExtensionArray, ndarray]"; expected type
- # "Union[int, slice, ndarray]"
- value = value[0, :] # type: ignore[index]
+ # error: No overload variant of "__getitem__" of "ExtensionArray"
+ # matches argument type "Tuple[int, slice]"
+ value = value[0, :] # type: ignore[call-overload]
else:
raise ValueError(
f"Expected a 1D array, got an array with shape {value.shape}"
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 6b41d7a26080d..b34d3590f6a71 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -538,10 +538,10 @@ def _concatenate_join_units(
# concatting with at least one EA means we are concatting a single column
# the non-EA values are 2D arrays with shape (1, n)
- # error: Invalid index type "Tuple[int, slice]" for
- # "Union[ExtensionArray, ndarray]"; expected type "Union[int, slice, ndarray]"
+ # error: No overload variant of "__getitem__" of "ExtensionArray" matches
+ # argument type "Tuple[int, slice]"
to_concat = [
- t if is_1d_only_ea_obj(t) else t[0, :] # type: ignore[index]
+ t if is_1d_only_ea_obj(t) else t[0, :] # type: ignore[call-overload]
for t in to_concat
]
concat_values = concat_compat(to_concat, axis=0, ea_compat_axis=True)
diff --git a/pandas/core/internals/ops.py b/pandas/core/internals/ops.py
index 5f03d6709dfa4..35caeea9b9067 100644
--- a/pandas/core/internals/ops.py
+++ b/pandas/core/internals/ops.py
@@ -106,28 +106,28 @@ def _get_same_shape_values(
# TODO(EA2D): with 2D EAs only this first clause would be needed
if not (left_ea or right_ea):
- # error: Invalid index type "Tuple[Any, slice]" for "Union[ndarray,
- # ExtensionArray]"; expected type "Union[int, slice, ndarray]"
- lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[index]
+ # error: No overload variant of "__getitem__" of "ExtensionArray" matches
+ # argument type "Tuple[Union[ndarray, slice], slice]"
+ lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[call-overload]
assert lvals.shape == rvals.shape, (lvals.shape, rvals.shape)
elif left_ea and right_ea:
assert lvals.shape == rvals.shape, (lvals.shape, rvals.shape)
elif right_ea:
# lvals are 2D, rvals are 1D
- # error: Invalid index type "Tuple[Any, slice]" for "Union[ndarray,
- # ExtensionArray]"; expected type "Union[int, slice, ndarray]"
- lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[index]
+ # error: No overload variant of "__getitem__" of "ExtensionArray" matches
+ # argument type "Tuple[Union[ndarray, slice], slice]"
+ lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[call-overload]
assert lvals.shape[0] == 1, lvals.shape
- # error: Invalid index type "Tuple[int, slice]" for "Union[Any,
- # ExtensionArray]"; expected type "Union[int, slice, ndarray]"
- lvals = lvals[0, :] # type: ignore[index]
+ # error: No overload variant of "__getitem__" of "ExtensionArray" matches
+ # argument type "Tuple[int, slice]"
+ lvals = lvals[0, :] # type: ignore[call-overload]
else:
# lvals are 1D, rvals are 2D
assert rvals.shape[0] == 1, rvals.shape
- # error: Invalid index type "Tuple[int, slice]" for "Union[ndarray,
- # ExtensionArray]"; expected type "Union[int, slice, ndarray]"
- rvals = rvals[0, :] # type: ignore[index]
+ # error: No overload variant of "__getitem__" of "ExtensionArray" matches
+ # argument type "Tuple[int, slice]"
+ rvals = rvals[0, :] # type: ignore[call-overload]
return lvals, rvals
| Changes for typing of `ExtensionArray.__getitem__()`.
Required changes to `DateTimeLikeArrayMixin` for correct compatibility.
| https://api.github.com/repos/pandas-dev/pandas/pulls/41258 | 2021-05-02T00:02:01Z | 2021-09-08T22:12:21Z | 2021-09-08T22:12:21Z | 2021-09-08T22:21:42Z |
Backport PR #40994: REGR: memory_map with non-UTF8 encoding | diff --git a/doc/source/whatsnew/v1.2.5.rst b/doc/source/whatsnew/v1.2.5.rst
index 16f9284802407..60e146b2212eb 100644
--- a/doc/source/whatsnew/v1.2.5.rst
+++ b/doc/source/whatsnew/v1.2.5.rst
@@ -15,7 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Regression in :func:`concat` between two :class:`DataFrames` where one has an :class:`Index` that is all-None and the other is :class:`DatetimeIndex` incorrectly raising (:issue:`40841`)
--
+- Regression in :func:`read_csv` when using ``memory_map=True`` with an non-UTF8 encoding (:issue:`40986`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/common.py b/pandas/io/common.py
index be353fefdd1ef..e6b6471294ac7 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -568,7 +568,12 @@ def get_handle(
# memory mapping needs to be the first step
handle, memory_map, handles = _maybe_memory_map(
- handle, memory_map, ioargs.encoding, ioargs.mode, errors
+ handle,
+ memory_map,
+ ioargs.encoding,
+ ioargs.mode,
+ errors,
+ ioargs.compression["method"] not in _compression_to_extension,
)
is_path = isinstance(handle, str)
@@ -759,7 +764,18 @@ class _MMapWrapper(abc.Iterator):
"""
- def __init__(self, f: IO):
+ def __init__(
+ self,
+ f: IO,
+ encoding: str = "utf-8",
+ errors: str = "strict",
+ decode: bool = True,
+ ):
+ self.encoding = encoding
+ self.errors = errors
+ self.decoder = codecs.getincrementaldecoder(encoding)(errors=errors)
+ self.decode = decode
+
self.attributes = {}
for attribute in ("seekable", "readable", "writeable"):
if not hasattr(f, attribute):
@@ -775,19 +791,31 @@ def __getattr__(self, name: str):
def __iter__(self) -> "_MMapWrapper":
return self
+ def read(self, size: int = -1) -> Union[str, bytes]:
+ # CSV c-engine uses read instead of iterating
+ content: bytes = self.mmap.read(size)
+ if self.decode:
+ errors = self.errors if self.errors is not None else "strict"
+ # memory mapping is applied before compression. Encoding should
+ # be applied to the de-compressed data.
+ return content.decode(self.encoding, errors=errors)
+ return content
+
def __next__(self) -> str:
newbytes = self.mmap.readline()
# readline returns bytes, not str, but Python's CSV reader
# expects str, so convert the output to str before continuing
- newline = newbytes.decode("utf-8")
+ newline = self.decoder.decode(newbytes)
# mmap doesn't raise if reading past the allocated
# data but instead returns an empty string, so raise
# if that is returned
if newline == "":
raise StopIteration
- return newline
+
+ # IncrementalDecoder seems to push newline to the next line
+ return newline.lstrip("\n")
def _maybe_memory_map(
@@ -796,6 +824,7 @@ def _maybe_memory_map(
encoding: str,
mode: str,
errors: Optional[str],
+ decode: bool,
) -> Tuple[FileOrBuffer, bool, List[Buffer]]:
"""Try to memory map file/buffer."""
handles: List[Buffer] = []
@@ -814,7 +843,10 @@ def _maybe_memory_map(
handles.append(handle)
try:
- wrapped = cast(mmap.mmap, _MMapWrapper(handle)) # type: ignore[arg-type]
+ wrapped = cast(
+ mmap.mmap,
+ _MMapWrapper(handle, encoding, errors, decode), # type: ignore[arg-type]
+ )
handle.close()
handles.remove(handle)
handles.append(wrapped)
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 8ad86fd0a0dce..bbff9dfe1ddd0 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -1868,31 +1868,6 @@ def __init__(self, src: FilePathOrBuffer, **kwds):
assert self.handles is not None
for key in ("storage_options", "encoding", "memory_map", "compression"):
kwds.pop(key, None)
- if self.handles.is_mmap and hasattr(self.handles.handle, "mmap"):
- # pandas\io\parsers.py:1861: error: Item "IO[Any]" of
- # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
- # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr]
-
- # pandas\io\parsers.py:1861: error: Item "RawIOBase" of
- # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
- # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr]
-
- # pandas\io\parsers.py:1861: error: Item "BufferedIOBase" of
- # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
- # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr]
-
- # pandas\io\parsers.py:1861: error: Item "TextIOBase" of
- # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
- # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr]
-
- # pandas\io\parsers.py:1861: error: Item "TextIOWrapper" of
- # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
- # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr]
-
- # pandas\io\parsers.py:1861: error: Item "mmap" of "Union[IO[Any],
- # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap]" has
- # no attribute "mmap" [union-attr]
- self.handles.handle = self.handles.handle.mmap # type: ignore[union-attr]
try:
self._reader = parsers.TextReader(self.handles.handle, **kwds)
diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py
index e74265da3e966..41e1964086dce 100644
--- a/pandas/tests/io/parser/test_encoding.py
+++ b/pandas/tests/io/parser/test_encoding.py
@@ -217,3 +217,20 @@ def test_parse_encoded_special_characters(encoding):
expected = DataFrame(data=[[":foo", 0], ["bar", 1], ["baz", 2]], columns=["a", "b"])
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("encoding", ["utf-8", None, "utf-16", "cp1255", "latin-1"])
+def test_encoding_memory_map(all_parsers, encoding):
+ # GH40986
+ parser = all_parsers
+ expected = DataFrame(
+ {
+ "name": ["Raphael", "Donatello", "Miguel Angel", "Leonardo"],
+ "mask": ["red", "purple", "orange", "blue"],
+ "weapon": ["sai", "bo staff", "nunchunk", "katana"],
+ }
+ )
+ with tm.ensure_clean() as file:
+ expected.to_csv(file, index=False, encoding=encoding)
+ df = parser.read_csv(file, encoding=encoding, memory_map=True)
+ tm.assert_frame_equal(df, expected)
| Backport PR #40994 | https://api.github.com/repos/pandas-dev/pandas/pulls/41257 | 2021-05-01T23:58:40Z | 2021-05-25T13:22:36Z | 2021-05-25T13:22:36Z | 2021-06-05T20:50:08Z |
REF: avoid unnecessary casting in algorithms | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 16ec2bb5f253c..2c4477056a112 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -37,19 +37,17 @@
from pandas.core.dtypes.cast import (
construct_1d_object_array_from_listlike,
infer_dtype_from_array,
+ sanitize_to_nanoseconds,
)
from pandas.core.dtypes.common import (
ensure_float64,
- ensure_int64,
ensure_object,
ensure_platform_int,
- ensure_uint64,
is_array_like,
is_bool_dtype,
is_categorical_dtype,
is_complex_dtype,
is_datetime64_dtype,
- is_datetime64_ns_dtype,
is_extension_array_dtype,
is_float_dtype,
is_integer,
@@ -57,11 +55,8 @@
is_list_like,
is_numeric_dtype,
is_object_dtype,
- is_period_dtype,
is_scalar,
- is_signed_integer_dtype,
is_timedelta64_dtype,
- is_unsigned_integer_dtype,
needs_i8_conversion,
pandas_dtype,
)
@@ -134,71 +129,49 @@ def _ensure_data(values: ArrayLike) -> tuple[np.ndarray, DtypeObj]:
values = extract_array(values, extract_numpy=True)
# we check some simple dtypes first
- if is_object_dtype(values):
+ if is_object_dtype(values.dtype):
return ensure_object(np.asarray(values)), np.dtype("object")
- try:
- if is_bool_dtype(values):
- # we are actually coercing to uint64
- # until our algos support uint8 directly (see TODO)
- return np.asarray(values).astype("uint64"), np.dtype("bool")
- elif is_signed_integer_dtype(values):
- return ensure_int64(values), values.dtype
- elif is_unsigned_integer_dtype(values):
- return ensure_uint64(values), values.dtype
- elif is_float_dtype(values):
+ elif is_bool_dtype(values.dtype):
+ if isinstance(values, np.ndarray):
+ # i.e. actually dtype == np.dtype("bool")
+ return np.asarray(values).view("uint8"), values.dtype
+ else:
+ # i.e. all-bool Categorical, BooleanArray
+ return np.asarray(values).astype("uint8", copy=False), values.dtype
+
+ elif is_integer_dtype(values.dtype):
+ return np.asarray(values), values.dtype
+
+ elif is_float_dtype(values.dtype):
+ # Note: checking `values.dtype == "float128"` raises on Windows and 32bit
+ # error: Item "ExtensionDtype" of "Union[Any, ExtensionDtype, dtype[Any]]"
+ # has no attribute "itemsize"
+ if values.dtype.itemsize in [2, 12, 16]: # type: ignore[union-attr]
+ # we dont (yet) have float128 hashtable support
return ensure_float64(values), values.dtype
- elif is_complex_dtype(values):
-
- # ignore the fact that we are casting to float
- # which discards complex parts
- with catch_warnings():
- simplefilter("ignore", np.ComplexWarning)
- values = ensure_float64(values)
- return values, np.dtype("float64")
+ return np.asarray(values), values.dtype
- except (TypeError, ValueError, OverflowError):
- # if we are trying to coerce to a dtype
- # and it is incompatible this will fall through to here
- return ensure_object(values), np.dtype("object")
+ elif is_complex_dtype(values.dtype):
+ # ignore the fact that we are casting to float
+ # which discards complex parts
+ with catch_warnings():
+ simplefilter("ignore", np.ComplexWarning)
+ values = ensure_float64(values)
+ return values, np.dtype("float64")
# datetimelike
- if needs_i8_conversion(values.dtype):
- if is_period_dtype(values.dtype):
- from pandas import PeriodIndex
-
- values = PeriodIndex(values)._data
- elif is_timedelta64_dtype(values.dtype):
- from pandas import TimedeltaIndex
-
- values = TimedeltaIndex(values)._data
- else:
- # Datetime
- if values.ndim > 1 and is_datetime64_ns_dtype(values.dtype):
- # Avoid calling the DatetimeIndex constructor as it is 1D only
- # Note: this is reached by DataFrame.rank calls GH#27027
- # TODO(EA2D): special case not needed with 2D EAs
- asi8 = values.view("i8")
- dtype = values.dtype
- # error: Incompatible return value type (got "Tuple[Any,
- # Union[dtype, ExtensionDtype, None]]", expected
- # "Tuple[ndarray, Union[dtype, ExtensionDtype]]")
- return asi8, dtype # type: ignore[return-value]
-
- from pandas import DatetimeIndex
-
- values = DatetimeIndex(values)._data
- dtype = values.dtype
- return values.asi8, dtype
+ elif needs_i8_conversion(values.dtype):
+ if isinstance(values, np.ndarray):
+ values = sanitize_to_nanoseconds(values)
+ npvalues = values.view("i8")
+ npvalues = cast(np.ndarray, npvalues)
+ return npvalues, values.dtype
elif is_categorical_dtype(values.dtype):
values = cast("Categorical", values)
values = values.codes
dtype = pandas_dtype("category")
-
- # we are actually coercing to int64
- # until our algos support int* directly (not all do)
- values = ensure_int64(values)
return values, dtype
# we have failed, return object
@@ -268,8 +241,15 @@ def _ensure_arraylike(values) -> ArrayLike:
_hashtables = {
"float64": htable.Float64HashTable,
+ "float32": htable.Float32HashTable,
"uint64": htable.UInt64HashTable,
+ "uint32": htable.UInt32HashTable,
+ "uint16": htable.UInt16HashTable,
+ "uint8": htable.UInt8HashTable,
"int64": htable.Int64HashTable,
+ "int32": htable.Int32HashTable,
+ "int16": htable.Int16HashTable,
+ "int8": htable.Int8HashTable,
"string": htable.StringHashTable,
"object": htable.PyObjectHashTable,
}
@@ -298,6 +278,10 @@ def _get_values_for_rank(values: ArrayLike) -> np.ndarray:
values = cast("Categorical", values)._values_for_rank()
values, _ = _ensure_data(values)
+ if values.dtype.kind in ["i", "u", "f"]:
+ # rank_t includes only object, int64, uint64, float64
+ dtype = values.dtype.kind + "8"
+ values = values.astype(dtype, copy=False)
return values
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 091efa68c67da..4847372f18239 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -550,7 +550,7 @@ def _from_factorized(cls, values, original):
# Data
# ------------------------------------------------------------------------
@property
- def sp_index(self):
+ def sp_index(self) -> SparseIndex:
"""
The SparseIndex containing the location of non- ``fill_value`` points.
"""
@@ -570,7 +570,7 @@ def sp_values(self) -> np.ndarray:
return self._sparse_values
@property
- def dtype(self):
+ def dtype(self) -> SparseDtype:
return self._dtype
@property
@@ -597,7 +597,7 @@ def kind(self) -> str:
return "block"
@property
- def _valid_sp_values(self):
+ def _valid_sp_values(self) -> np.ndarray:
sp_vals = self.sp_values
mask = notna(sp_vals)
return sp_vals[mask]
@@ -620,7 +620,7 @@ def nbytes(self) -> int:
return self.sp_values.nbytes + self.sp_index.nbytes
@property
- def density(self):
+ def density(self) -> float:
"""
The percent of non- ``fill_value`` points, as decimal.
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index c7af104f62770..964dd9bdd0e0a 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -1756,14 +1756,15 @@ def _check(arr):
_check(np.array([np.nan, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 3, np.nan]))
_check(np.array([4.0, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 4.0, np.nan]))
- def test_basic(self, writable):
+ @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
+ def test_basic(self, writable, dtype):
exp = np.array([1, 2], dtype=np.float64)
- for dtype in np.typecodes["AllInteger"]:
- data = np.array([1, 100], dtype=dtype)
- data.setflags(write=writable)
- s = Series(data)
- tm.assert_numpy_array_equal(algos.rank(s), exp)
+ data = np.array([1, 100], dtype=dtype)
+ data.setflags(write=writable)
+ ser = Series(data)
+ result = algos.rank(ser)
+ tm.assert_numpy_array_equal(result, exp)
def test_uint64_overflow(self):
exp = np.array([1, 2], dtype=np.float64)
| Sparse annotations are unrelated, were figured out in the process of getting this working. | https://api.github.com/repos/pandas-dev/pandas/pulls/41256 | 2021-05-01T23:39:46Z | 2021-05-02T23:16:56Z | 2021-05-02T23:16:56Z | 2021-05-03T01:12:41Z |
TYP: Simple type fixes for ExtensionArray | diff --git a/pandas/_typing.py b/pandas/_typing.py
index a58dc0dba1bf1..1e1fffdd60676 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -37,6 +37,7 @@
# https://mypy.readthedocs.io/en/latest/common_issues.html#import-cycles
if TYPE_CHECKING:
from typing import (
+ Literal,
TypedDict,
final,
)
@@ -189,6 +190,12 @@
str, int, Sequence[Union[str, int]], Mapping[Hashable, Union[str, int]]
]
+# Arguments for fillna()
+if TYPE_CHECKING:
+ FillnaOptions = Literal["backfill", "bfill", "ffill", "pad"]
+else:
+ FillnaOptions = str
+
# internals
Manager = Union[
"ArrayManager", "SingleArrayManager", "BlockManager", "SingleBlockManager"
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index bd01191719143..16d42e4a51927 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -13,6 +13,7 @@
TYPE_CHECKING,
Any,
Callable,
+ Iterator,
Sequence,
TypeVar,
cast,
@@ -24,6 +25,7 @@
from pandas._typing import (
ArrayLike,
Dtype,
+ FillnaOptions,
PositionalIndexer,
Shape,
)
@@ -69,6 +71,7 @@
)
if TYPE_CHECKING:
+ from typing import Literal
class ExtensionArraySupportsAnyAll("ExtensionArray"):
def any(self, *, skipna: bool = True) -> bool:
@@ -375,7 +378,7 @@ def __len__(self) -> int:
"""
raise AbstractMethodError(self)
- def __iter__(self):
+ def __iter__(self) -> Iterator[Any]:
"""
Iterate over elements of the array.
"""
@@ -385,7 +388,7 @@ def __iter__(self):
for i in range(len(self)):
yield self[i]
- def __contains__(self, item) -> bool | np.bool_:
+ def __contains__(self, item: object) -> bool | np.bool_:
"""
Return for `item in self`.
"""
@@ -400,7 +403,9 @@ def __contains__(self, item) -> bool | np.bool_:
else:
return False
else:
- return (item == self).any()
+ # error: Item "ExtensionArray" of "Union[ExtensionArray, ndarray]" has no
+ # attribute "any"
+ return (item == self).any() # type: ignore[union-attr]
# error: Signature of "__eq__" incompatible with supertype "object"
def __eq__(self, other: Any) -> ArrayLike: # type: ignore[override]
@@ -680,7 +685,12 @@ def argmax(self, skipna: bool = True) -> int:
raise NotImplementedError
return nargminmax(self, "argmax")
- def fillna(self, value=None, method=None, limit=None):
+ def fillna(
+ self,
+ value: object | ArrayLike | None = None,
+ method: FillnaOptions | None = None,
+ limit: int | None = None,
+ ):
"""
Fill NA/NaN values using the specified method.
@@ -1207,7 +1217,7 @@ def _formatter(self, boxed: bool = False) -> Callable[[Any], str | None]:
# Reshaping
# ------------------------------------------------------------------------
- def transpose(self, *axes) -> ExtensionArray:
+ def transpose(self, *axes: int) -> ExtensionArray:
"""
Return a transposed view on this array.
@@ -1220,7 +1230,7 @@ def transpose(self, *axes) -> ExtensionArray:
def T(self) -> ExtensionArray:
return self.transpose()
- def ravel(self, order="C") -> ExtensionArray:
+ def ravel(self, order: Literal["C", "F", "A", "K"] | None = "C") -> ExtensionArray:
"""
Return a flattened view on this array.
@@ -1294,7 +1304,7 @@ def _reduce(self, name: str, *, skipna: bool = True, **kwargs):
"""
raise TypeError(f"cannot perform {name} with type {self.dtype}")
- def __hash__(self):
+ def __hash__(self) -> int:
raise TypeError(f"unhashable type: {repr(type(self).__name__)}")
# ------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 50837e1b3ed50..a508b3db2f038 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -54,6 +54,7 @@
CompressionOptions,
Dtype,
FilePathOrBuffer,
+ FillnaOptions,
FloatFormatType,
FormattersType,
FrameOrSeriesUnion,
@@ -5015,7 +5016,7 @@ def rename(
def fillna(
self,
value=...,
- method: str | None = ...,
+ method: FillnaOptions | None = ...,
axis: Axis | None = ...,
inplace: Literal[False] = ...,
limit=...,
@@ -5027,7 +5028,7 @@ def fillna(
def fillna(
self,
value,
- method: str | None,
+ method: FillnaOptions | None,
axis: Axis | None,
inplace: Literal[True],
limit=...,
@@ -5060,7 +5061,7 @@ def fillna(
def fillna(
self,
*,
- method: str | None,
+ method: FillnaOptions | None,
inplace: Literal[True],
limit=...,
downcast=...,
@@ -5082,7 +5083,7 @@ def fillna(
def fillna(
self,
*,
- method: str | None,
+ method: FillnaOptions | None,
axis: Axis | None,
inplace: Literal[True],
limit=...,
@@ -5106,7 +5107,7 @@ def fillna(
def fillna(
self,
value,
- method: str | None,
+ method: FillnaOptions | None,
*,
inplace: Literal[True],
limit=...,
@@ -5118,7 +5119,7 @@ def fillna(
def fillna(
self,
value=...,
- method: str | None = ...,
+ method: FillnaOptions | None = ...,
axis: Axis | None = ...,
inplace: bool = ...,
limit=...,
@@ -5129,8 +5130,8 @@ def fillna(
@doc(NDFrame.fillna, **_shared_doc_kwargs)
def fillna(
self,
- value=None,
- method: str | None = None,
+ value: object | ArrayLike | None = None,
+ method: FillnaOptions | None = None,
axis: Axis | None = None,
inplace: bool = False,
limit=None,
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 240f678960969..c8e9898f9462a 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -38,6 +38,7 @@
Axis,
Dtype,
DtypeObj,
+ FillnaOptions,
FrameOrSeriesUnion,
IndexKeyFunc,
NpDtype,
@@ -4594,7 +4595,7 @@ def drop(
def fillna(
self,
value=...,
- method: str | None = ...,
+ method: FillnaOptions | None = ...,
axis: Axis | None = ...,
inplace: Literal[False] = ...,
limit=...,
@@ -4606,7 +4607,7 @@ def fillna(
def fillna(
self,
value,
- method: str | None,
+ method: FillnaOptions | None,
axis: Axis | None,
inplace: Literal[True],
limit=...,
@@ -4639,7 +4640,7 @@ def fillna(
def fillna(
self,
*,
- method: str | None,
+ method: FillnaOptions | None,
inplace: Literal[True],
limit=...,
downcast=...,
@@ -4661,7 +4662,7 @@ def fillna(
def fillna(
self,
*,
- method: str | None,
+ method: FillnaOptions | None,
axis: Axis | None,
inplace: Literal[True],
limit=...,
@@ -4685,7 +4686,7 @@ def fillna(
def fillna(
self,
value,
- method: str | None,
+ method: FillnaOptions | None,
*,
inplace: Literal[True],
limit=...,
@@ -4697,7 +4698,7 @@ def fillna(
def fillna(
self,
value=...,
- method: str | None = ...,
+ method: FillnaOptions | None = ...,
axis: Axis | None = ...,
inplace: bool = ...,
limit=...,
@@ -4709,8 +4710,8 @@ def fillna(
@doc(NDFrame.fillna, **_shared_doc_kwargs) # type: ignore[has-type]
def fillna(
self,
- value=None,
- method=None,
+ value: object | ArrayLike | None = None,
+ method: FillnaOptions | None = None,
axis=None,
inplace=False,
limit=None,
| Typing changes for the following methods in `ExtensionArray`
- `__iter__`
- `__contains__`
- `fillna`
- `transpose`
- `ravel`
- `__hash__` | https://api.github.com/repos/pandas-dev/pandas/pulls/41255 | 2021-05-01T23:16:21Z | 2021-05-06T01:39:35Z | 2021-05-06T01:39:35Z | 2021-05-06T02:19:02Z |
CLN: Move stuff in tests.indexes.test_numeric.py to more logical locations | diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 6139d8af48d98..45c9dda1d1b38 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -1,3 +1,4 @@
+from datetime import datetime
import gc
from typing import Type
@@ -5,6 +6,7 @@
import pytest
from pandas._libs import iNaT
+from pandas._libs.tslibs import Timestamp
from pandas.core.dtypes.common import is_datetime64tz_dtype
from pandas.core.dtypes.dtypes import CategoricalDtype
@@ -13,6 +15,7 @@
from pandas import (
CategoricalIndex,
DatetimeIndex,
+ Float64Index,
Index,
Int64Index,
IntervalIndex,
@@ -29,7 +32,9 @@
class Base:
- """ base class for index sub-class tests """
+ """
+ Base class for index sub-class tests.
+ """
_index_cls: Type[Index]
@@ -738,3 +743,91 @@ def test_shallow_copy_shares_cache(self, simple_index):
shallow_copy = idx._shallow_copy(idx._data)
assert shallow_copy._cache is not idx._cache
assert shallow_copy._cache == {}
+
+ def test_index_groupby(self, simple_index):
+ idx = simple_index[:5]
+ to_groupby = np.array([1, 2, np.nan, 2, 1])
+ tm.assert_dict_equal(
+ idx.groupby(to_groupby), {1.0: idx[[0, 4]], 2.0: idx[[1, 3]]}
+ )
+
+ to_groupby = DatetimeIndex(
+ [
+ datetime(2011, 11, 1),
+ datetime(2011, 12, 1),
+ pd.NaT,
+ datetime(2011, 12, 1),
+ datetime(2011, 11, 1),
+ ],
+ tz="UTC",
+ ).values
+
+ ex_keys = [Timestamp("2011-11-01"), Timestamp("2011-12-01")]
+ expected = {ex_keys[0]: idx[[0, 4]], ex_keys[1]: idx[[1, 3]]}
+ tm.assert_dict_equal(idx.groupby(to_groupby), expected)
+
+
+class NumericBase(Base):
+ """
+ Base class for numeric index (incl. RangeIndex) sub-class tests.
+ """
+
+ def test_where(self):
+ # Tested in numeric.test_indexing
+ pass
+
+ def test_can_hold_identifiers(self, simple_index):
+ idx = simple_index
+ key = idx[0]
+ assert idx._can_hold_identifiers_and_holds_name(key) is False
+
+ def test_format(self, simple_index):
+ # GH35439
+ idx = simple_index
+ max_width = max(len(str(x)) for x in idx)
+ expected = [str(x).ljust(max_width) for x in idx]
+ assert idx.format() == expected
+
+ def test_numeric_compat(self):
+ pass # override Base method
+
+ def test_insert_na(self, nulls_fixture, simple_index):
+ # GH 18295 (test missing)
+ index = simple_index
+ na_val = nulls_fixture
+
+ if na_val is pd.NaT:
+ expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object)
+ else:
+ expected = Float64Index([index[0], np.nan] + list(index[1:]))
+
+ result = index.insert(1, na_val)
+ tm.assert_index_equal(result, expected)
+
+ def test_arithmetic_explicit_conversions(self):
+ # GH 8608
+ # add/sub are overridden explicitly for Float/Int Index
+ index_cls = self._index_cls
+ if index_cls is RangeIndex:
+ idx = RangeIndex(5)
+ else:
+ idx = index_cls(np.arange(5, dtype="int64"))
+
+ # float conversions
+ arr = np.arange(5, dtype="int64") * 3.2
+ expected = Float64Index(arr)
+ fidx = idx * 3.2
+ tm.assert_index_equal(fidx, expected)
+ fidx = 3.2 * idx
+ tm.assert_index_equal(fidx, expected)
+
+ # interops with numpy arrays
+ expected = Float64Index(arr)
+ a = np.zeros(5, dtype="float64")
+ result = fidx - a
+ tm.assert_index_equal(result, expected)
+
+ expected = Float64Index(-arr)
+ a = np.zeros(5, dtype="float64")
+ result = a - fidx
+ tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/numeric/test_numeric.py
similarity index 84%
rename from pandas/tests/indexes/test_numeric.py
rename to pandas/tests/indexes/numeric/test_numeric.py
index c5dc84dac0fd2..bfe06d74570da 100644
--- a/pandas/tests/indexes/test_numeric.py
+++ b/pandas/tests/indexes/numeric/test_numeric.py
@@ -1,5 +1,3 @@
-from datetime import datetime
-
import numpy as np
import pytest
@@ -15,107 +13,10 @@
UInt64Index,
)
import pandas._testing as tm
-from pandas.tests.indexes.common import Base
-
-
-class TestArithmetic:
- @pytest.mark.parametrize(
- "klass", [Float64Index, Int64Index, UInt64Index, RangeIndex]
- )
- def test_arithmetic_explicit_conversions(self, klass):
-
- # GH 8608
- # add/sub are overridden explicitly for Float/Int Index
- if klass is RangeIndex:
- idx = RangeIndex(5)
- else:
- idx = klass(np.arange(5, dtype="int64"))
-
- # float conversions
- arr = np.arange(5, dtype="int64") * 3.2
- expected = Float64Index(arr)
- fidx = idx * 3.2
- tm.assert_index_equal(fidx, expected)
- fidx = 3.2 * idx
- tm.assert_index_equal(fidx, expected)
-
- # interops with numpy arrays
- expected = Float64Index(arr)
- a = np.zeros(5, dtype="float64")
- result = fidx - a
- tm.assert_index_equal(result, expected)
-
- expected = Float64Index(-arr)
- a = np.zeros(5, dtype="float64")
- result = a - fidx
- tm.assert_index_equal(result, expected)
-
-
-class TestNumericIndex:
- def test_index_groupby(self):
- int_idx = Index(range(6))
- float_idx = Index(np.arange(0, 0.6, 0.1))
- obj_idx = Index("A B C D E F".split())
- dt_idx = pd.date_range("2013-01-01", freq="M", periods=6)
-
- for idx in [int_idx, float_idx, obj_idx, dt_idx]:
- to_groupby = np.array([1, 2, np.nan, np.nan, 2, 1])
- tm.assert_dict_equal(
- idx.groupby(to_groupby), {1.0: idx[[0, 5]], 2.0: idx[[1, 4]]}
- )
-
- to_groupby = pd.DatetimeIndex(
- [
- datetime(2011, 11, 1),
- datetime(2011, 12, 1),
- pd.NaT,
- pd.NaT,
- datetime(2011, 12, 1),
- datetime(2011, 11, 1),
- ],
- tz="UTC",
- ).values
-
- ex_keys = [Timestamp("2011-11-01"), Timestamp("2011-12-01")]
- expected = {ex_keys[0]: idx[[0, 5]], ex_keys[1]: idx[[1, 4]]}
- tm.assert_dict_equal(idx.groupby(to_groupby), expected)
-
-
-class Numeric(Base):
- def test_where(self):
- # Tested in numeric.test_indexing
- pass
-
- def test_can_hold_identifiers(self, simple_index):
- idx = simple_index
- key = idx[0]
- assert idx._can_hold_identifiers_and_holds_name(key) is False
-
- def test_format(self, simple_index):
- # GH35439
- idx = simple_index
- max_width = max(len(str(x)) for x in idx)
- expected = [str(x).ljust(max_width) for x in idx]
- assert idx.format() == expected
-
- def test_numeric_compat(self):
- pass # override Base method
-
- def test_insert_na(self, nulls_fixture, simple_index):
- # GH 18295 (test missing)
- index = simple_index
- na_val = nulls_fixture
-
- if na_val is pd.NaT:
- expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object)
- else:
- expected = Float64Index([index[0], np.nan] + list(index[1:]))
-
- result = index.insert(1, na_val)
- tm.assert_index_equal(result, expected)
+from pandas.tests.indexes.common import NumericBase
-class TestFloat64Index(Numeric):
+class TestFloat64Index(NumericBase):
_index_cls = Float64Index
_dtype = np.float64
@@ -387,7 +288,7 @@ def test_fillna_float64(self):
tm.assert_index_equal(idx.fillna("obj"), exp)
-class NumericInt(Numeric):
+class NumericInt(NumericBase):
def test_view(self):
index_cls = self._index_cls
diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py
index f7313f100d429..3a4aa29ea620e 100644
--- a/pandas/tests/indexes/ranges/test_range.py
+++ b/pandas/tests/indexes/ranges/test_range.py
@@ -11,7 +11,7 @@
RangeIndex,
)
import pandas._testing as tm
-from pandas.tests.indexes.test_numeric import Numeric
+from pandas.tests.indexes.common import NumericBase
# aliases to make some tests easier to read
RI = RangeIndex
@@ -20,7 +20,7 @@
OI = Index
-class TestRangeIndex(Numeric):
+class TestRangeIndex(NumericBase):
_index_cls = RangeIndex
@pytest.fixture
| This does four things to better organize the numeric index's tests:
1. Moves test method `test_index_groupby` from `tests.indexes.test_numeric.py::TestNumericIndex` to `tests.indexes.common.py::Base` and makes it use a fixture. This means this tests will be used for all index types. Also deletes `TestNumericIndex`, as its empty now.
2. Moves the `Numeric` class from `test_numeric.py` to `common.py` and renames it `NumericBase`.
3. Moves the `tests.indexes.numeric.py::TestArithmetic::test_arithmetic_explicit_conversions` tests to the new `common.py::NumericBase` and delete `test_numeric.py::TestArithmetic` class, as it's now empty.
4. Moves the file `tests.indexes.test_numeric.py` to `tests.indexes.numeric.test_numeric.py`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/41254 | 2021-05-01T21:19:03Z | 2021-05-04T12:59:25Z | 2021-05-04T12:59:25Z | 2021-05-05T16:33:16Z |
COMPAT: more error msg compat for py310 | diff --git a/pandas/tests/indexes/ranges/test_constructors.py b/pandas/tests/indexes/ranges/test_constructors.py
index 9539b0ff7cdba..e306b6e67cf7f 100644
--- a/pandas/tests/indexes/ranges/test_constructors.py
+++ b/pandas/tests/indexes/ranges/test_constructors.py
@@ -119,7 +119,9 @@ def test_constructor_range(self):
expected = RangeIndex(1, 5, 2)
tm.assert_index_equal(result, expected, exact=True)
- msg = r"^from_range\(\) got an unexpected keyword argument"
+ msg = (
+ r"(RangeIndex.)?from_range\(\) got an unexpected keyword argument( 'copy')?"
+ )
with pytest.raises(TypeError, match=msg):
RangeIndex.from_range(range(10), copy=True)
diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py
index 5f02f9625a9e6..c5dc84dac0fd2 100644
--- a/pandas/tests/indexes/test_numeric.py
+++ b/pandas/tests/indexes/test_numeric.py
@@ -242,7 +242,9 @@ def test_constructor_invalid(self):
with pytest.raises((TypeError, ValueError), match=msg):
index_cls(["a", "b", 0.0])
- msg = r"float\(\) argument must be a string or a number, not 'Timestamp'"
+ msg = (
+ r"float\(\) argument must be a string or a( real)? number, not 'Timestamp'"
+ )
with pytest.raises(TypeError, match=msg):
index_cls([Timestamp("20130101")])
diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py
index a44d47470eb5e..805f6b8dbe461 100644
--- a/pandas/tests/io/json/test_ujson.py
+++ b/pandas/tests/io/json/test_ujson.py
@@ -828,65 +828,65 @@ def test_0d_array(self):
(
[{}, []],
ValueError,
- "nesting not supported for object or variable length dtypes",
+ r"nesting not supported for object or variable length dtypes",
{},
),
(
[42, None],
TypeError,
- "int() argument must be a string, a bytes-like object or a number, "
- "not 'NoneType'",
+ r"int\(\) argument must be a string, a bytes-like object or a( real)? "
+ r"number, not 'NoneType'",
{},
),
(
[["a"], 42],
ValueError,
- "Cannot decode multidimensional arrays with variable length elements "
- "to numpy",
+ r"Cannot decode multidimensional arrays with variable length elements "
+ r"to numpy",
{},
),
(
[42, {}, "a"],
TypeError,
- "int() argument must be a string, a bytes-like object or a number, "
- "not 'dict'",
+ r"int\(\) argument must be a string, a bytes-like object or a( real)? "
+ r"number, not 'dict'",
{},
),
(
[42, ["a"], 42],
ValueError,
- "invalid literal for int() with base 10: 'a'",
+ r"invalid literal for int\(\) with base 10: 'a'",
{},
),
(
["a", "b", [], "c"],
ValueError,
- "nesting not supported for object or variable length dtypes",
+ r"nesting not supported for object or variable length dtypes",
{},
),
(
[{"a": "b"}],
ValueError,
- "Cannot decode multidimensional arrays with variable length elements "
- "to numpy",
+ r"Cannot decode multidimensional arrays with variable length elements "
+ r"to numpy",
{"labelled": True},
),
(
{"a": {"b": {"c": 42}}},
ValueError,
- "labels only supported up to 2 dimensions",
+ r"labels only supported up to 2 dimensions",
{"labelled": True},
),
(
[{"a": 42, "b": 23}, {"c": 17}],
ValueError,
- "cannot reshape array of size 3 into shape (2,1)",
+ r"cannot reshape array of size 3 into shape \(2,1\)",
{"labelled": True},
),
],
)
def test_array_numpy_except(self, bad_input, exc_type, err_msg, kwargs):
- with pytest.raises(exc_type, match=re.escape(err_msg)):
+ with pytest.raises(exc_type, match=err_msg):
ujson.decode(ujson.dumps(bad_input), numpy=True, **kwargs)
def test_array_numpy_labelled(self):
diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py
index 98ec4de614a07..2340d154e9e10 100644
--- a/pandas/tests/scalar/timestamp/test_constructors.py
+++ b/pandas/tests/scalar/timestamp/test_constructors.py
@@ -10,6 +10,7 @@
import pytest
import pytz
+from pandas.compat import PY310
from pandas.errors import OutOfBoundsDatetime
from pandas import (
@@ -223,7 +224,11 @@ def test_constructor_tz_or_tzinfo(self):
def test_constructor_positional(self):
# see gh-10758
- msg = "an integer is required"
+ msg = (
+ "'NoneType' object cannot be interpreted as an integer"
+ if PY310
+ else "an integer is required"
+ )
with pytest.raises(TypeError, match=msg):
Timestamp(2000, 1)
| https://api.github.com/repos/pandas-dev/pandas/pulls/41253 | 2021-05-01T21:18:12Z | 2021-05-02T23:22:23Z | 2021-05-02T23:22:23Z | 2021-06-18T02:30:41Z | |
CLN: minor cleanup of bad pattern | diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index 0253852fbb39a..4aaf1eecde5e8 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -486,13 +486,8 @@ def format(
formatter = {col: formatter for col in columns}
for col in columns:
- try:
- format_func = formatter[col]
- except KeyError:
- format_func = None
-
format_func = _maybe_wrap_formatter(
- format_func,
+ formatter.get(col),
na_rep=na_rep,
precision=precision,
decimal=decimal,
| can approve as quickly as possible to hide terrible coding.
| https://api.github.com/repos/pandas-dev/pandas/pulls/41252 | 2021-05-01T20:56:27Z | 2021-05-01T23:53:08Z | 2021-05-01T23:53:08Z | 2021-05-02T06:27:45Z |
TYP: Typing changes for ExtensionArray.astype | diff --git a/pandas/_typing.py b/pandas/_typing.py
index 433f8645d35a8..93d49497a85e0 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -126,10 +126,9 @@
]
# dtypes
-NpDtype = Union[str, np.dtype]
-Dtype = Union[
- "ExtensionDtype", NpDtype, type_t[Union[str, float, int, complex, bool, object]]
-]
+NpDtype = Union[str, np.dtype, type_t[Union[str, float, int, complex, bool, object]]]
+Dtype = Union["ExtensionDtype", NpDtype]
+AstypeArg = Union["ExtensionDtype", "npt.DTypeLike"]
# DtypeArg specifies all allowable dtypes in a functions its dtype argument
DtypeArg = Union[Dtype, Dict[Hashable, Dtype]]
DtypeObj = Union[np.dtype, "ExtensionDtype"]
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 4cc0d4185b22c..b0b7b81d059e6 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -18,6 +18,7 @@
Sequence,
TypeVar,
cast,
+ overload,
)
import numpy as np
@@ -25,6 +26,7 @@
from pandas._libs import lib
from pandas._typing import (
ArrayLike,
+ AstypeArg,
Dtype,
FillnaOptions,
PositionalIndexer,
@@ -520,9 +522,21 @@ def nbytes(self) -> int:
# Additional Methods
# ------------------------------------------------------------------------
- def astype(self, dtype, copy=True):
+ @overload
+ def astype(self, dtype: npt.DTypeLike, copy: bool = ...) -> np.ndarray:
+ ...
+
+ @overload
+ def astype(self, dtype: ExtensionDtype, copy: bool = ...) -> ExtensionArray:
+ ...
+
+ @overload
+ def astype(self, dtype: AstypeArg, copy: bool = ...) -> ArrayLike:
+ ...
+
+ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
"""
- Cast to a NumPy array with 'dtype'.
+ Cast to a NumPy array or ExtensionArray with 'dtype'.
Parameters
----------
@@ -535,8 +549,10 @@ def astype(self, dtype, copy=True):
Returns
-------
- array : ndarray
- NumPy ndarray with 'dtype' for its dtype.
+ array : np.ndarray or ExtensionArray
+ An ExtensionArray if dtype is StringDtype,
+ or same as that of underlying array.
+ Otherwise a NumPy ndarray with 'dtype' for its dtype.
"""
from pandas.core.arrays.string_ import StringDtype
@@ -552,7 +568,11 @@ def astype(self, dtype, copy=True):
# allow conversion to StringArrays
return dtype.construct_array_type()._from_sequence(self, copy=False)
- return np.array(self, dtype=dtype, copy=copy)
+ # error: Argument "dtype" to "array" has incompatible type
+ # "Union[ExtensionDtype, dtype[Any]]"; expected "Union[dtype[Any], None, type,
+ # _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int,
+ # Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]"
+ return np.array(self, dtype=dtype, copy=copy) # type: ignore[arg-type]
def isna(self) -> np.ndarray | ExtensionArraySupportsAnyAll:
"""
@@ -863,6 +883,8 @@ def searchsorted(
# 2. Values between the values in the `data_for_sorting` fixture
# 3. Missing values.
arr = self.astype(object)
+ if isinstance(value, ExtensionArray):
+ value = value.astype(object)
return arr.searchsorted(value, side=side, sorter=sorter)
def equals(self, other: object) -> bool:
diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py
index 14d059c04b7c0..6f473249c9a7e 100644
--- a/pandas/core/arrays/boolean.py
+++ b/pandas/core/arrays/boolean.py
@@ -1,7 +1,10 @@
from __future__ import annotations
import numbers
-from typing import TYPE_CHECKING
+from typing import (
+ TYPE_CHECKING,
+ overload,
+)
import warnings
import numpy as np
@@ -12,7 +15,9 @@
)
from pandas._typing import (
ArrayLike,
+ AstypeArg,
Dtype,
+ npt,
type_t,
)
from pandas.compat.numpy import function as nv
@@ -33,6 +38,7 @@
from pandas.core.dtypes.missing import isna
from pandas.core import ops
+from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.masked import (
BaseMaskedArray,
BaseMaskedDtype,
@@ -392,7 +398,20 @@ def reconstruct(x):
def _coerce_to_array(self, value) -> tuple[np.ndarray, np.ndarray]:
return coerce_to_array(value)
- def astype(self, dtype, copy: bool = True) -> ArrayLike:
+ @overload
+ def astype(self, dtype: npt.DTypeLike, copy: bool = ...) -> np.ndarray:
+ ...
+
+ @overload
+ def astype(self, dtype: ExtensionDtype, copy: bool = ...) -> ExtensionArray:
+ ...
+
+ @overload
+ def astype(self, dtype: AstypeArg, copy: bool = ...) -> ArrayLike:
+ ...
+
+ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
+
"""
Cast to a NumPy array or ExtensionArray with 'dtype'.
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index c6be9e5886a1d..b8ceef3d52e41 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -11,6 +11,7 @@
TypeVar,
Union,
cast,
+ overload,
)
from warnings import (
catch_warnings,
@@ -32,6 +33,7 @@
from pandas._libs.lib import no_default
from pandas._typing import (
ArrayLike,
+ AstypeArg,
Dtype,
NpDtype,
Ordered,
@@ -482,7 +484,19 @@ def _constructor(self) -> type[Categorical]:
def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy=False):
return Categorical(scalars, dtype=dtype, copy=copy)
- def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
+ @overload
+ def astype(self, dtype: npt.DTypeLike, copy: bool = ...) -> np.ndarray:
+ ...
+
+ @overload
+ def astype(self, dtype: ExtensionDtype, copy: bool = ...) -> ExtensionArray:
+ ...
+
+ @overload
+ def astype(self, dtype: AstypeArg, copy: bool = ...) -> ArrayLike:
+ ...
+
+ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
"""
Coerce this type to another dtype
@@ -2458,11 +2472,7 @@ def _str_get_dummies(self, sep="|"):
# sep may not be in categories. Just bail on this.
from pandas.core.arrays import PandasArray
- # error: Argument 1 to "PandasArray" has incompatible type
- # "ExtensionArray"; expected "Union[ndarray, PandasArray]"
- return PandasArray(self.astype(str))._str_get_dummies( # type: ignore[arg-type]
- sep
- )
+ return PandasArray(self.astype(str))._str_get_dummies(sep)
# The Series.cat accessor
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py
index 1acbcf17dfffd..25b4076bd23c6 100644
--- a/pandas/core/arrays/floating.py
+++ b/pandas/core/arrays/floating.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from typing import overload
import warnings
import numpy as np
@@ -10,7 +11,9 @@
)
from pandas._typing import (
ArrayLike,
+ AstypeArg,
DtypeObj,
+ npt,
)
from pandas.compat.numpy import function as nv
from pandas.util._decorators import cache_readonly
@@ -31,6 +34,7 @@
)
from pandas.core.dtypes.missing import isna
+from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.numeric import (
NumericArray,
NumericDtype,
@@ -271,7 +275,19 @@ def _from_sequence_of_strings(
def _coerce_to_array(self, value) -> tuple[np.ndarray, np.ndarray]:
return coerce_to_array(value, dtype=self.dtype)
- def astype(self, dtype, copy: bool = True) -> ArrayLike:
+ @overload
+ def astype(self, dtype: npt.DTypeLike, copy: bool = ...) -> np.ndarray:
+ ...
+
+ @overload
+ def astype(self, dtype: ExtensionDtype, copy: bool = ...) -> ExtensionArray:
+ ...
+
+ @overload
+ def astype(self, dtype: AstypeArg, copy: bool = ...) -> ArrayLike:
+ ...
+
+ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
"""
Cast to a NumPy array or ExtensionArray with 'dtype'.
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py
index c9ba762a271bd..e62a2f95b0340 100644
--- a/pandas/core/arrays/integer.py
+++ b/pandas/core/arrays/integer.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from typing import overload
import warnings
import numpy as np
@@ -11,8 +12,10 @@
)
from pandas._typing import (
ArrayLike,
+ AstypeArg,
Dtype,
DtypeObj,
+ npt,
)
from pandas.compat.numpy import function as nv
from pandas.util._decorators import cache_readonly
@@ -33,6 +36,7 @@
)
from pandas.core.dtypes.missing import isna
+from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.masked import (
BaseMaskedArray,
BaseMaskedDtype,
@@ -333,7 +337,19 @@ def _from_sequence_of_strings(
def _coerce_to_array(self, value) -> tuple[np.ndarray, np.ndarray]:
return coerce_to_array(value, dtype=self.dtype)
- def astype(self, dtype, copy: bool = True) -> ArrayLike:
+ @overload
+ def astype(self, dtype: npt.DTypeLike, copy: bool = ...) -> np.ndarray:
+ ...
+
+ @overload
+ def astype(self, dtype: ExtensionDtype, copy: bool = ...) -> ExtensionArray:
+ ...
+
+ @overload
+ def astype(self, dtype: AstypeArg, copy: bool = ...) -> ArrayLike:
+ ...
+
+ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
"""
Cast to a NumPy array or ExtensionArray with 'dtype'.
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 718e135464385..cccfd58aa914d 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -5,6 +5,7 @@
Any,
Sequence,
TypeVar,
+ overload,
)
import numpy as np
@@ -15,10 +16,11 @@
)
from pandas._typing import (
ArrayLike,
- Dtype,
+ AstypeArg,
NpDtype,
PositionalIndexer,
Scalar,
+ npt,
type_t,
)
from pandas.errors import AbstractMethodError
@@ -282,9 +284,7 @@ def to_numpy( # type: ignore[override]
if na_value is lib.no_default:
na_value = libmissing.NA
if dtype is None:
- # error: Incompatible types in assignment (expression has type
- # "Type[object]", variable has type "Union[str, dtype[Any], None]")
- dtype = object # type: ignore[assignment]
+ dtype = object
if self._hasna:
if (
not is_object_dtype(dtype)
@@ -303,7 +303,19 @@ def to_numpy( # type: ignore[override]
data = self._data.astype(dtype, copy=copy)
return data
- def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
+ @overload
+ def astype(self, dtype: npt.DTypeLike, copy: bool = ...) -> np.ndarray:
+ ...
+
+ @overload
+ def astype(self, dtype: ExtensionDtype, copy: bool = ...) -> ExtensionArray:
+ ...
+
+ @overload
+ def astype(self, dtype: AstypeArg, copy: bool = ...) -> ArrayLike:
+ ...
+
+ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
dtype = pandas_dtype(dtype)
if is_dtype_equal(dtype, self.dtype):
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 488981bcc9687..2db1f00e237ee 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -351,9 +351,7 @@ def freq(self) -> BaseOffset:
def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
if dtype == "i8":
return self.asi8
- # error: Non-overlapping equality check (left operand type: "Optional[Union[str,
- # dtype[Any]]]", right operand type: "Type[bool]")
- elif dtype == bool: # type: ignore[comparison-overlap]
+ elif dtype == bool:
return ~self._isnan
# This will raise TypeError for non-object dtypes
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index b1c794ac03b31..6dce9b4475d1b 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -27,6 +27,7 @@
from pandas._libs.tslibs import NaT
from pandas._typing import (
ArrayLike,
+ AstypeArg,
Dtype,
NpDtype,
Scalar,
@@ -527,9 +528,7 @@ def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
try:
dtype = np.result_type(self.sp_values.dtype, type(fill_value))
except TypeError:
- # error: Incompatible types in assignment (expression has type
- # "Type[object]", variable has type "Union[str, dtype[Any], None]")
- dtype = object # type: ignore[assignment]
+ dtype = object
out = np.full(self.shape, fill_value, dtype=dtype)
out[self.sp_index.to_int_index().indices] = self.sp_values
@@ -1072,7 +1071,7 @@ def _concat_same_type(
return cls(data, sparse_index=sp_index, fill_value=fill_value)
- def astype(self, dtype: Dtype | None = None, copy=True):
+ def astype(self, dtype: AstypeArg | None = None, copy=True):
"""
Change the dtype of a SparseArray.
diff --git a/pandas/core/common.py b/pandas/core/common.py
index b32614577393d..2bf925466e176 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -232,12 +232,7 @@ def asarray_tuplesafe(values, dtype: NpDtype | None = None) -> np.ndarray:
# expected "ndarray")
return values._values # type: ignore[return-value]
- # error: Non-overlapping container check (element type: "Union[str, dtype[Any],
- # None]", container item type: "type")
- if isinstance(values, list) and dtype in [ # type: ignore[comparison-overlap]
- np.object_,
- object,
- ]:
+ if isinstance(values, list) and dtype in [np.object_, object]:
return construct_1d_object_array_from_listlike(values)
result = np.asarray(values, dtype=dtype)
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index bf1f5d37f07dc..6be2e803b5910 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -29,8 +29,8 @@
from pandas._typing import (
Dtype,
DtypeObj,
- NpDtype,
Ordered,
+ npt,
type_t,
)
@@ -1294,7 +1294,7 @@ class PandasDtype(ExtensionDtype):
_metadata = ("_dtype",)
- def __init__(self, dtype: NpDtype | PandasDtype | None):
+ def __init__(self, dtype: npt.DTypeLike | PandasDtype | None):
if isinstance(dtype, PandasDtype):
# make constructor univalent
dtype = dtype.numpy_dtype
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 0010624609907..e3fcff1557ca9 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1369,7 +1369,7 @@ def get_values(self, dtype: DtypeObj | None = None) -> np.ndarray:
"""
return object dtype as boxed values, such as Timestamps/Timedelta
"""
- values = self.values
+ values: ArrayLike = self.values
if dtype == _dtype_obj:
values = values.astype(object)
# TODO(EA2D): reshape not needed with 2D EAs
| Minimal (hopefully) typing changes for `ExtensionArray.astype` .
| https://api.github.com/repos/pandas-dev/pandas/pulls/41251 | 2021-05-01T19:37:45Z | 2021-09-06T19:48:28Z | 2021-09-06T19:48:28Z | 2021-09-06T19:48:58Z |
TYP: assorted annotations | diff --git a/pandas/_libs/hashtable.pyx b/pandas/_libs/hashtable.pyx
index 1e2a336f12444..4566f22be2c36 100644
--- a/pandas/_libs/hashtable.pyx
+++ b/pandas/_libs/hashtable.pyx
@@ -163,7 +163,7 @@ cdef class Int64Factorizer:
@cython.wraparound(False)
@cython.boundscheck(False)
-def unique_label_indices(const int64_t[:] labels):
+def unique_label_indices(const int64_t[:] labels) -> ndarray:
"""
Indices of the first occurrences of the unique labels
*excluding* -1. equivalent to:
diff --git a/pandas/_libs/indexing.pyx b/pandas/_libs/indexing.pyx
index 7966fe8d4f045..bdbaa05138072 100644
--- a/pandas/_libs/indexing.pyx
+++ b/pandas/_libs/indexing.pyx
@@ -3,9 +3,10 @@ cdef class NDFrameIndexerBase:
A base class for _NDFrameIndexer for fast instantiation and attribute access.
"""
cdef public:
- object obj, name, _ndim
+ str name
+ object obj, _ndim
- def __init__(self, name, obj):
+ def __init__(self, name: str, obj):
self.obj = obj
self.name = name
self._ndim = None
diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx
index f3bc70ad8a26b..77bb462c6df4a 100644
--- a/pandas/_libs/internals.pyx
+++ b/pandas/_libs/internals.pyx
@@ -372,7 +372,9 @@ cdef slice indexer_as_slice(intp_t[:] vals):
@cython.boundscheck(False)
@cython.wraparound(False)
-def get_blkno_indexers(int64_t[:] blknos, bint group=True):
+def get_blkno_indexers(
+ int64_t[:] blknos, bint group=True
+) -> list[tuple[int, slice | np.ndarray]]:
"""
Enumerate contiguous runs of integers in ndarray.
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4469869a5a929..69e88cd221f6d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -6219,7 +6219,6 @@ def sort_values( # type: ignore[override]
indexer = lexsort_indexer(
keys, orders=ascending, na_position=na_position, key=key
)
- indexer = ensure_platform_int(indexer)
elif len(by):
by = by[0]
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 1bae9947bd875..7779335bfd3ba 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -3414,7 +3414,7 @@ def get_indexer(
limit: int | None = None,
tolerance=None,
) -> np.ndarray:
-
+ # returned ndarray is np.intp
method = missing.clean_reindex_fill_method(method)
target = ensure_index(target)
@@ -4099,7 +4099,10 @@ def _join_multi(self, other: Index, how: str_t):
return result
@final
- def _join_non_unique(self, other, how="left"):
+ def _join_non_unique(
+ self, other: Index, how: str_t = "left"
+ ) -> tuple[Index, np.ndarray, np.ndarray]:
+ # returned ndarrays are np.intp
from pandas.core.reshape.merge import get_join_indexers
# We only get here if dtypes match
@@ -4125,7 +4128,10 @@ def _join_non_unique(self, other, how="left"):
return join_index, left_idx, right_idx
@final
- def _join_level(self, other, level, how="left", keep_order=True):
+ def _join_level(
+ self, other: Index, level, how: str_t = "left", keep_order: bool = True
+ ) -> tuple[MultiIndex, np.ndarray | None, np.ndarray | None]:
+ # Any returned ndarrays are np.intp
"""
The join method *only* affects the level of the resulting
MultiIndex. Otherwise it just exactly aligns the Index data to the
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index eac2579e7dfa5..73f463997c085 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1470,9 +1470,9 @@ def _interleave(
if isinstance(dtype, SparseDtype):
dtype = dtype.subtype
elif isinstance(dtype, ExtensionDtype):
- dtype = "object"
+ dtype = np.dtype("object")
elif is_dtype_equal(dtype, str):
- dtype = "object"
+ dtype = np.dtype("object")
# error: Argument "dtype" to "empty" has incompatible type
# "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index 1a4d8dbe2885e..d1e076da9293d 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -131,7 +131,12 @@ def __init__(self, index: MultiIndex, level=-1, constructor=None):
self._make_selectors()
@cache_readonly
- def _indexer_and_to_sort(self):
+ def _indexer_and_to_sort(
+ self,
+ ) -> tuple[
+ np.ndarray, # np.ndarray[np.intp]
+ list[np.ndarray], # each has _some_ signed integer dtype
+ ]:
v = self.level
codes = list(self.index.codes)
@@ -143,7 +148,6 @@ def _indexer_and_to_sort(self):
ngroups = len(obs_ids)
indexer = get_group_index_sorter(comp_index, ngroups)
- indexer = ensure_platform_int(indexer)
return indexer, to_sort
@cache_readonly
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 6a3e997a58754..ed9ce848678a0 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -113,15 +113,15 @@
from pandas.core.indexes.accessors import CombinedDatetimelikeProperties
from pandas.core.indexes.api import (
CategoricalIndex,
+ DatetimeIndex,
Float64Index,
Index,
MultiIndex,
+ PeriodIndex,
+ TimedeltaIndex,
ensure_index,
)
import pandas.core.indexes.base as ibase
-from pandas.core.indexes.datetimes import DatetimeIndex
-from pandas.core.indexes.period import PeriodIndex
-from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.core.indexing import check_bool_indexer
from pandas.core.internals import (
SingleArrayManager,
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 7c867487e92b0..1c85385c587a5 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -381,10 +381,11 @@ def _apply_series(
"""
obj = self._create_data(self._selected_obj)
- try:
+ if name == "count":
# GH 12541: Special case for count where we support date-like types
- input = obj.values if name != "count" else notna(obj.values).astype(int)
- values = self._prep_values(input)
+ obj = notna(obj).astype(int)
+ try:
+ values = self._prep_values(obj._values)
except (TypeError, NotImplementedError) as err:
raise DataError("No numeric types to aggregate") from err
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41250 | 2021-05-01T16:39:07Z | 2021-05-02T23:21:32Z | 2021-05-02T23:21:32Z | 2021-05-03T01:22:24Z |
CLN: remove outdated arrow compat | diff --git a/pandas/core/arrays/_arrow_utils.py b/pandas/core/arrays/_arrow_utils.py
index 51e5f36b88c79..6214693f22975 100644
--- a/pandas/core/arrays/_arrow_utils.py
+++ b/pandas/core/arrays/_arrow_utils.py
@@ -1,4 +1,3 @@
-from distutils.version import LooseVersion
import json
import numpy as np
@@ -6,8 +5,6 @@
from pandas.core.arrays.interval import VALID_CLOSED
-_pyarrow_version_ge_015 = LooseVersion(pyarrow.__version__) >= LooseVersion("0.15")
-
def pyarrow_array_to_numpy_and_mask(arr, dtype):
"""
@@ -48,97 +45,97 @@ def pyarrow_array_to_numpy_and_mask(arr, dtype):
return data, mask
-if _pyarrow_version_ge_015:
- # the pyarrow extension types are only available for pyarrow 0.15+
-
- class ArrowPeriodType(pyarrow.ExtensionType):
- def __init__(self, freq):
- # attributes need to be set first before calling
- # super init (as that calls serialize)
- self._freq = freq
- pyarrow.ExtensionType.__init__(self, pyarrow.int64(), "pandas.period")
-
- @property
- def freq(self):
- return self._freq
-
- def __arrow_ext_serialize__(self):
- metadata = {"freq": self.freq}
- return json.dumps(metadata).encode()
-
- @classmethod
- def __arrow_ext_deserialize__(cls, storage_type, serialized):
- metadata = json.loads(serialized.decode())
- return ArrowPeriodType(metadata["freq"])
-
- def __eq__(self, other):
- if isinstance(other, pyarrow.BaseExtensionType):
- return type(self) == type(other) and self.freq == other.freq
- else:
- return NotImplemented
-
- def __hash__(self):
- return hash((str(self), self.freq))
-
- def to_pandas_dtype(self):
- import pandas as pd
-
- return pd.PeriodDtype(freq=self.freq)
-
- # register the type with a dummy instance
- _period_type = ArrowPeriodType("D")
- pyarrow.register_extension_type(_period_type)
-
- class ArrowIntervalType(pyarrow.ExtensionType):
- def __init__(self, subtype, closed):
- # attributes need to be set first before calling
- # super init (as that calls serialize)
- assert closed in VALID_CLOSED
- self._closed = closed
- if not isinstance(subtype, pyarrow.DataType):
- subtype = pyarrow.type_for_alias(str(subtype))
- self._subtype = subtype
-
- storage_type = pyarrow.struct([("left", subtype), ("right", subtype)])
- pyarrow.ExtensionType.__init__(self, storage_type, "pandas.interval")
-
- @property
- def subtype(self):
- return self._subtype
-
- @property
- def closed(self):
- return self._closed
-
- def __arrow_ext_serialize__(self):
- metadata = {"subtype": str(self.subtype), "closed": self.closed}
- return json.dumps(metadata).encode()
-
- @classmethod
- def __arrow_ext_deserialize__(cls, storage_type, serialized):
- metadata = json.loads(serialized.decode())
- subtype = pyarrow.type_for_alias(metadata["subtype"])
- closed = metadata["closed"]
- return ArrowIntervalType(subtype, closed)
-
- def __eq__(self, other):
- if isinstance(other, pyarrow.BaseExtensionType):
- return (
- type(self) == type(other)
- and self.subtype == other.subtype
- and self.closed == other.closed
- )
- else:
- return NotImplemented
-
- def __hash__(self):
- return hash((str(self), str(self.subtype), self.closed))
-
- def to_pandas_dtype(self):
- import pandas as pd
-
- return pd.IntervalDtype(self.subtype.to_pandas_dtype(), self.closed)
-
- # register the type with a dummy instance
- _interval_type = ArrowIntervalType(pyarrow.int64(), "left")
- pyarrow.register_extension_type(_interval_type)
+class ArrowPeriodType(pyarrow.ExtensionType):
+ def __init__(self, freq):
+ # attributes need to be set first before calling
+ # super init (as that calls serialize)
+ self._freq = freq
+ pyarrow.ExtensionType.__init__(self, pyarrow.int64(), "pandas.period")
+
+ @property
+ def freq(self):
+ return self._freq
+
+ def __arrow_ext_serialize__(self):
+ metadata = {"freq": self.freq}
+ return json.dumps(metadata).encode()
+
+ @classmethod
+ def __arrow_ext_deserialize__(cls, storage_type, serialized):
+ metadata = json.loads(serialized.decode())
+ return ArrowPeriodType(metadata["freq"])
+
+ def __eq__(self, other):
+ if isinstance(other, pyarrow.BaseExtensionType):
+ return type(self) == type(other) and self.freq == other.freq
+ else:
+ return NotImplemented
+
+ def __hash__(self):
+ return hash((str(self), self.freq))
+
+ def to_pandas_dtype(self):
+ import pandas as pd
+
+ return pd.PeriodDtype(freq=self.freq)
+
+
+# register the type with a dummy instance
+_period_type = ArrowPeriodType("D")
+pyarrow.register_extension_type(_period_type)
+
+
+class ArrowIntervalType(pyarrow.ExtensionType):
+ def __init__(self, subtype, closed):
+ # attributes need to be set first before calling
+ # super init (as that calls serialize)
+ assert closed in VALID_CLOSED
+ self._closed = closed
+ if not isinstance(subtype, pyarrow.DataType):
+ subtype = pyarrow.type_for_alias(str(subtype))
+ self._subtype = subtype
+
+ storage_type = pyarrow.struct([("left", subtype), ("right", subtype)])
+ pyarrow.ExtensionType.__init__(self, storage_type, "pandas.interval")
+
+ @property
+ def subtype(self):
+ return self._subtype
+
+ @property
+ def closed(self):
+ return self._closed
+
+ def __arrow_ext_serialize__(self):
+ metadata = {"subtype": str(self.subtype), "closed": self.closed}
+ return json.dumps(metadata).encode()
+
+ @classmethod
+ def __arrow_ext_deserialize__(cls, storage_type, serialized):
+ metadata = json.loads(serialized.decode())
+ subtype = pyarrow.type_for_alias(metadata["subtype"])
+ closed = metadata["closed"]
+ return ArrowIntervalType(subtype, closed)
+
+ def __eq__(self, other):
+ if isinstance(other, pyarrow.BaseExtensionType):
+ return (
+ type(self) == type(other)
+ and self.subtype == other.subtype
+ and self.closed == other.closed
+ )
+ else:
+ return NotImplemented
+
+ def __hash__(self):
+ return hash((str(self), str(self.subtype), self.closed))
+
+ def to_pandas_dtype(self):
+ import pandas as pd
+
+ return pd.IntervalDtype(self.subtype.to_pandas_dtype(), self.closed)
+
+
+# register the type with a dummy instance
+_interval_type = ArrowIntervalType(pyarrow.int64(), "left")
+pyarrow.register_extension_type(_interval_type)
| precursor of #41207
| https://api.github.com/repos/pandas-dev/pandas/pulls/41249 | 2021-05-01T12:24:39Z | 2021-05-01T15:00:05Z | 2021-05-01T15:00:05Z | 2021-06-18T02:30:04Z |
[ArrowStringArray] PERF: use pyarrow.compute.utf8_length if available | diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index fabb3974728de..4dc291c0fe084 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -41,6 +41,7 @@
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays.base import ExtensionArray
from pandas.core.arrays.boolean import BooleanDtype
+from pandas.core.arrays.integer import Int64Dtype
from pandas.core.indexers import (
check_array_indexer,
validate_indices,
@@ -858,6 +859,14 @@ def _str_isupper(self):
else:
return super()._str_isupper()
+ def _str_len(self):
+ # utf8_length added in pyarrow 4.0.0
+ if hasattr(pc, "utf8_length"):
+ result = pc.utf8_length(self._data)
+ return Int64Dtype().__from_arrow__(result)
+ else:
+ return super()._str_len()
+
def _str_lower(self):
return type(self)(pc.utf8_lower(self._data))
diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py
index f218d5333b415..a013dd6ed4df1 100644
--- a/pandas/tests/strings/test_strings.py
+++ b/pandas/tests/strings/test_strings.py
@@ -14,7 +14,6 @@
MultiIndex,
Series,
isna,
- notna,
)
import pandas._testing as tm
@@ -402,14 +401,19 @@ def test_join():
tm.assert_almost_equal(rs, xp)
-def test_len():
- values = Series(["foo", "fooo", "fooooo", np.nan, "fooooooo"])
+def test_len(any_string_dtype):
+ values = Series(
+ ["foo", "fooo", "fooooo", np.nan, "fooooooo", "foo\n", "あ"],
+ dtype=any_string_dtype,
+ )
result = values.str.len()
- exp = values.map(lambda x: len(x) if notna(x) else np.nan)
- tm.assert_series_equal(result, exp)
+ expected_dtype = "float64" if any_string_dtype == "object" else "Int64"
+ expected = Series([3, 4, 6, np.nan, 8, 4, 1], dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
- # mixed
+
+def test_len_mixed():
mixed = Series(
[
"a_b",
| ```
[ 25.00%] ··· strings.Methods.time_len ok
[ 25.00%] ··· ============== ==========
dtype
-------------- ----------
str 19.1±0ms
string 6.82±0ms
arrow_string 1.93±0ms
============== ==========
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/41248 | 2021-05-01T09:36:34Z | 2021-05-04T16:24:35Z | 2021-05-04T16:24:35Z | 2021-05-04T18:15:50Z |
CLN: standardize naming in core.groupby | diff --git a/pandas/core/groupby/categorical.py b/pandas/core/groupby/categorical.py
index 297681f1e10f5..2a2671374efc4 100644
--- a/pandas/core/groupby/categorical.py
+++ b/pandas/core/groupby/categorical.py
@@ -1,7 +1,4 @@
-from typing import (
- Optional,
- Tuple,
-)
+from __future__ import annotations
import numpy as np
@@ -16,7 +13,7 @@
def recode_for_groupby(
c: Categorical, sort: bool, observed: bool
-) -> Tuple[Categorical, Optional[Categorical]]:
+) -> tuple[Categorical, Categorical | None]:
"""
Code the categories to ensure we can groupby for categoricals.
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index fd4b0cfa87950..8c402cf345095 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -366,7 +366,7 @@ def array_func(values: ArrayLike) -> ArrayLike:
)
except NotImplementedError:
ser = Series(values) # equiv 'obj' from outer frame
- if self.grouper.ngroups > 0:
+ if self.ngroups > 0:
res_values, _ = self.grouper.agg_series(ser, alt)
else:
# equiv: res_values = self._python_agg_general(alt)
@@ -604,12 +604,12 @@ def _transform_fast(self, result) -> Series:
fast version of transform, only applicable to
builtin/cythonizable functions
"""
- ids, _, ngroup = self.grouper.group_info
+ ids, _, _ = self.grouper.group_info
result = result.reindex(self.grouper.result_index, copy=False)
out = algorithms.take_nd(result._values, ids)
return self.obj._constructor(out, index=self.obj.index, name=self.obj.name)
- def filter(self, func, dropna=True, *args, **kwargs):
+ def filter(self, func, dropna: bool = True, *args, **kwargs):
"""
Return a copy of a Series excluding elements from groups that
do not satisfy the boolean criterion specified by func.
@@ -1445,7 +1445,7 @@ def _transform_fast(self, result: DataFrame) -> DataFrame:
obj = self._obj_with_exclusions
# for each col, reshape to size of original frame by take operation
- ids, _, ngroup = self.grouper.group_info
+ ids, _, _ = self.grouper.group_info
result = result.reindex(self.grouper.result_index, copy=False)
output = [
algorithms.take_nd(result.iloc[:, i].values, ids)
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 55c3bfd316462..620668dadc32d 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1103,13 +1103,13 @@ def _numba_prep(self, func, data):
raise NotImplementedError(
"Numba engine can only be used with a single function."
)
- labels, _, n_groups = self.grouper.group_info
- sorted_index = get_group_index_sorter(labels, n_groups)
- sorted_labels = algorithms.take_nd(labels, sorted_index, allow_fill=False)
+ ids, _, ngroups = self.grouper.group_info
+ sorted_index = get_group_index_sorter(ids, ngroups)
+ sorted_ids = algorithms.take_nd(ids, sorted_index, allow_fill=False)
sorted_data = data.take(sorted_index, axis=self.axis).to_numpy()
- starts, ends = lib.generate_slices(sorted_labels, n_groups)
+ starts, ends = lib.generate_slices(sorted_ids, ngroups)
return starts, ends, sorted_index, sorted_data
@final
@@ -1253,11 +1253,12 @@ def _python_agg_general(self, func, *args, **kwargs):
# iterate through "columns" ex exclusions to populate output dict
output: dict[base.OutputKey, ArrayLike] = {}
+ if self.ngroups == 0:
+ # agg_series below assumes ngroups > 0
+ return self._python_apply_general(f, self._selected_obj)
+
for idx, obj in enumerate(self._iterate_slices()):
name = obj.name
- if self.grouper.ngroups == 0:
- # agg_series below assumes ngroups > 0
- continue
try:
# if this function is invalid for this dtype, we will ignore it.
@@ -1368,7 +1369,7 @@ def _apply_filter(self, indices, dropna):
return filtered
@final
- def _cumcount_array(self, ascending: bool = True):
+ def _cumcount_array(self, ascending: bool = True) -> np.ndarray:
"""
Parameters
----------
@@ -2721,7 +2722,7 @@ def _get_cythonized_result(
grouper = self.grouper
- labels, _, ngroups = grouper.group_info
+ ids, _, ngroups = grouper.group_info
output: dict[base.OutputKey, np.ndarray] = {}
base_func = getattr(libgroupby, how)
@@ -2754,15 +2755,15 @@ def _get_cythonized_result(
if pre_processing:
try:
vals, inferences = pre_processing(vals)
- except TypeError as e:
- error_msg = str(e)
+ except TypeError as err:
+ error_msg = str(err)
continue
vals = vals.astype(cython_dtype, copy=False)
if needs_2d:
vals = vals.reshape((-1, 1))
func = partial(func, vals)
- func = partial(func, labels)
+ func = partial(func, ids)
if min_count is not None:
func = partial(func, min_count)
diff --git a/pandas/core/groupby/numba_.py b/pandas/core/groupby/numba_.py
index 3ba70baec1561..26070fcb5e89c 100644
--- a/pandas/core/groupby/numba_.py
+++ b/pandas/core/groupby/numba_.py
@@ -1,11 +1,10 @@
"""Common utilities for Numba operations with groupby ops"""
+from __future__ import annotations
+
import inspect
from typing import (
Any,
Callable,
- Dict,
- Optional,
- Tuple,
)
import numpy as np
@@ -57,10 +56,10 @@ def f(values, index, ...):
def generate_numba_agg_func(
- args: Tuple,
- kwargs: Dict[str, Any],
+ args: tuple,
+ kwargs: dict[str, Any],
func: Callable[..., Scalar],
- engine_kwargs: Optional[Dict[str, bool]],
+ engine_kwargs: dict[str, bool] | None,
) -> Callable[[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int], np.ndarray]:
"""
Generate a numba jitted agg function specified by values from engine_kwargs.
@@ -117,10 +116,10 @@ def group_agg(
def generate_numba_transform_func(
- args: Tuple,
- kwargs: Dict[str, Any],
+ args: tuple,
+ kwargs: dict[str, Any],
func: Callable[..., np.ndarray],
- engine_kwargs: Optional[Dict[str, bool]],
+ engine_kwargs: dict[str, bool] | None,
) -> Callable[[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int], np.ndarray]:
"""
Generate a numba jitted transform function specified by values from engine_kwargs.
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 9edbeb412026d..975a902f49db9 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -723,8 +723,8 @@ def _get_splitter(self, data: FrameOrSeries, axis: int = 0) -> DataSplitter:
__finalize__ has not been called for the subsetted objects returned.
"""
- comp_ids, _, ngroups = self.group_info
- return get_splitter(data, comp_ids, ngroups, axis=axis)
+ ids, _, ngroups = self.group_info
+ return get_splitter(data, ids, ngroups, axis=axis)
def _get_grouper(self):
"""
@@ -740,10 +740,10 @@ def _get_group_keys(self):
if len(self.groupings) == 1:
return self.levels[0]
else:
- comp_ids, _, ngroups = self.group_info
+ ids, _, ngroups = self.group_info
# provide "flattened" iterator for multi-group setting
- return get_flattened_list(comp_ids, ngroups, self.levels, self.codes)
+ return get_flattened_list(ids, ngroups, self.levels, self.codes)
@final
def apply(self, f: F, data: FrameOrSeries, axis: int = 0):
@@ -846,9 +846,9 @@ def size(self) -> Series:
"""
Compute group sizes.
"""
- ids, _, ngroup = self.group_info
- if ngroup:
- out = np.bincount(ids[ids != -1], minlength=ngroup)
+ ids, _, ngroups = self.group_info
+ if ngroups:
+ out = np.bincount(ids[ids != -1], minlength=ngroups)
else:
out = []
return Series(out, index=self.result_index, dtype="int64")
@@ -882,11 +882,11 @@ def group_info(self):
@cache_readonly
def codes_info(self) -> np.ndarray:
# return the codes of items in original grouped axis
- codes, _, _ = self.group_info
+ ids, _, _ = self.group_info
if self.indexer is not None:
- sorter = np.lexsort((codes, self.indexer))
- codes = codes[sorter]
- return codes
+ sorter = np.lexsort((ids, self.indexer))
+ ids = ids[sorter]
+ return ids
@final
def _get_compressed_codes(self) -> tuple[np.ndarray, np.ndarray]:
@@ -906,8 +906,8 @@ def ngroups(self) -> int:
@property
def reconstructed_codes(self) -> list[np.ndarray]:
codes = self.codes
- comp_ids, obs_ids, _ = self.group_info
- return decons_obs_group_ids(comp_ids, obs_ids, self.shape, codes, xnull=True)
+ ids, obs_ids, _ = self.group_info
+ return decons_obs_group_ids(ids, obs_ids, self.shape, codes, xnull=True)
@cache_readonly
def result_index(self) -> Index:
@@ -954,13 +954,13 @@ def _cython_operation(
cy_op = WrappedCythonOp(kind=kind, how=how)
- comp_ids, _, _ = self.group_info
+ ids, _, _ = self.group_info
ngroups = self.ngroups
return cy_op.cython_operation(
values=values,
axis=axis,
min_count=min_count,
- comp_ids=comp_ids,
+ comp_ids=ids,
ngroups=ngroups,
**kwargs,
)
@@ -997,26 +997,26 @@ def _aggregate_series_fast(
# - ngroups != 0
func = com.is_builtin_func(func)
- group_index, _, ngroups = self.group_info
+ ids, _, ngroups = self.group_info
# avoids object / Series creation overhead
- indexer = get_group_index_sorter(group_index, ngroups)
+ indexer = get_group_index_sorter(ids, ngroups)
obj = obj.take(indexer)
- group_index = group_index.take(indexer)
- sgrouper = libreduction.SeriesGrouper(obj, func, group_index, ngroups)
+ ids = ids.take(indexer)
+ sgrouper = libreduction.SeriesGrouper(obj, func, ids, ngroups)
result, counts = sgrouper.get_result()
return result, counts
@final
def _aggregate_series_pure_python(self, obj: Series, func: F):
- group_index, _, ngroups = self.group_info
+ ids, _, ngroups = self.group_info
counts = np.zeros(ngroups, dtype=int)
result = np.empty(ngroups, dtype="O")
initialized = False
# equiv: splitter = self._get_splitter(obj, axis=0)
- splitter = get_splitter(obj, group_index, ngroups, axis=0)
+ splitter = get_splitter(obj, ids, ngroups, axis=0)
for i, group in enumerate(splitter):
@@ -1152,7 +1152,7 @@ def indices(self):
@cache_readonly
def group_info(self):
ngroups = self.ngroups
- obs_group_ids = np.arange(ngroups)
+ obs_group_ids = np.arange(ngroups, dtype=np.int64)
rep = np.diff(np.r_[0, self.bins])
rep = ensure_platform_int(rep)
@@ -1163,7 +1163,7 @@ def group_info(self):
return (
ensure_platform_int(comp_ids),
- obs_group_ids.astype("int64", copy=False),
+ obs_group_ids,
ngroups,
)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41247 | 2021-05-01T01:42:03Z | 2021-05-03T03:25:46Z | 2021-05-03T03:25:46Z | 2021-05-03T03:27:24Z |
TYP: _libs.hashtable | diff --git a/pandas/_libs/hashtable.pyi b/pandas/_libs/hashtable.pyi
new file mode 100644
index 0000000000000..b6278b3956a1d
--- /dev/null
+++ b/pandas/_libs/hashtable.pyi
@@ -0,0 +1,242 @@
+from typing import (
+ Any,
+ Hashable,
+ Literal,
+)
+
+import numpy as np
+
+def unique_label_indices(
+ labels: np.ndarray, # const int64_t[:]
+) -> np.ndarray: ...
+
+
+class Factorizer:
+ table: PyObjectHashTable
+ uniques: ObjectVector
+ count: int
+
+ def __init__(self, size_hint: int): ...
+ def get_count(self) -> int: ...
+
+ def factorize(
+ self,
+ values: np.ndarray, # np.ndarray[object]
+ sort: bool = ...,
+ na_sentinel=...,
+ na_value=...,
+ ) -> np.ndarray: ... # np.ndarray[intp]
+
+ def unique(
+ self,
+ values: np.ndarray, # np.ndarray[object]
+ ) -> np.ndarray: ... # np.ndarray[object]
+
+
+class Int64Factorizer:
+ table: Int64HashTable
+ uniques: Int64Vector
+ count: int
+
+ def __init__(self, size_hint: int): ...
+ def get_count(self) -> int: ...
+
+ def factorize(
+ self,
+ values: np.ndarray, # const int64_t[:]
+ sort: bool = ...,
+ na_sentinel=...,
+ na_value=...,
+ ) -> np.ndarray: ... # np.ndarray[intp]
+
+
+class Int64Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.int64]
+
+class Int32Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.int32]
+
+class Int16Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.int16]
+
+class Int8Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.int8]
+
+class UInt64Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.uint64]
+
+class UInt32Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.uint32]
+
+class UInt16Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.uint16]
+
+class UInt8Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.uint8]
+
+class Float64Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.float64]
+
+class Float32Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.float32]
+
+class Complex128Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.complex128]
+
+class Complex64Vector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[np.complex64]
+
+class StringVector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[object]
+
+class ObjectVector:
+ def __init__(self): ...
+ def __len__(self) -> int: ...
+ def to_array(self) -> np.ndarray: ... # np.ndarray[object]
+
+
+class HashTable:
+ # NB: The base HashTable class does _not_ actually have these methods;
+ # we are putting the here for the sake of mypy to avoid
+ # reproducing them in each subclass below.
+ def __init__(self, size_hint: int = ...): ...
+ def __len__(self) -> int: ...
+ def __contains__(self, key: Hashable) -> bool: ...
+ def sizeof(self, deep: bool = ...) -> int: ...
+ def get_state(self) -> dict[str, int]: ...
+
+ # TODO: `item` type is subclass-specific
+ def get_item(self, item): ... # TODO: return type?
+ def set_item(self, item) -> None: ...
+
+ # FIXME: we don't actually have this for StringHashTable or ObjectHashTable?
+ def map(
+ self,
+ keys: np.ndarray, # np.ndarray[subclass-specific]
+ values: np.ndarray, # const int64_t[:] values
+ ) -> None: ...
+
+ def map_locations(
+ self,
+ values: np.ndarray, # np.ndarray[subclass-specific]
+ ) -> None: ...
+
+ def lookup(
+ self,
+ values: np.ndarray, # np.ndarray[subclass-specific]
+ ) -> np.ndarray: ... # np.ndarray[np.intp]
+
+ def get_labels(
+ self,
+ values: np.ndarray, # np.ndarray[subclass-specific]
+ uniques, # SubclassTypeVector
+ count_prior: int = ...,
+ na_sentinel: int = ...,
+ na_value: object = ...,
+ ) -> np.ndarray: ... # np.ndarray[intp_t]
+
+ def unique(
+ self,
+ values: np.ndarray, # np.ndarray[subclass-specific]
+ return_inverse: bool = ...,
+ ) -> tuple[
+ np.ndarray, # np.ndarray[subclass-specific]
+ np.ndarray, # np.ndarray[np.intp],
+ ] | np.ndarray: ... # np.ndarray[subclass-specific]
+
+ def _unique(
+ self,
+ values: np.ndarray, # np.ndarray[subclass-specific]
+ uniques, # FooVector
+ count_prior: int = ...,
+ na_sentinel: int = ...,
+ na_value: object = ...,
+ ignore_na: bool = ...,
+ return_inverse: bool = ...,
+ ) -> tuple[
+ np.ndarray, # np.ndarray[subclass-specific]
+ np.ndarray, # np.ndarray[np.intp],
+ ] | np.ndarray: ... # np.ndarray[subclass-specific]
+
+ def factorize(
+ self,
+ values: np.ndarray, # np.ndarray[subclass-specific]
+ na_sentinel: int = ...,
+ na_value: object = ...,
+ mask=...,
+ ) -> tuple[
+ np.ndarray, # np.ndarray[subclass-specific]
+ np.ndarray, # np.ndarray[np.intp],
+ ]: ...
+
+class Complex128HashTable(HashTable): ...
+class Complex64HashTable(HashTable): ...
+class Float64HashTable(HashTable): ...
+class Float32HashTable(HashTable): ...
+
+class Int64HashTable(HashTable):
+ # Only Int64HashTable has get_labels_groupby
+ def get_labels_groupby(
+ self,
+ values: np.ndarray, # const int64_t[:]
+ ) -> tuple[
+ np.ndarray, # np.ndarray[np.intp]
+ np.ndarray, # np.ndarray[np.int64]
+ ]: ...
+
+class Int32HashTable(HashTable): ...
+class Int16HashTable(HashTable): ...
+class Int8HashTable(HashTable): ...
+class UInt64HashTable(HashTable): ...
+class UInt32HashTable(HashTable): ...
+class UInt16HashTable(HashTable): ...
+class UInt8HashTable(HashTable): ...
+
+class StringHashTable(HashTable): ...
+class PyObjectHashTable(HashTable): ...
+
+
+def duplicated_int64(
+ values: np.ndarray, # const int64_t[:] values
+ keep: Literal["last", "first", False] = ...,
+) -> np.ndarray: ... # np.ndarray[bool]
+# TODO: Is it actually bool or is it uint8?
+
+def mode_int64(
+ values: np.ndarray, # const int64_t[:] values
+ dropna: bool,
+) -> np.ndarray: ... # np.ndarray[np.int64]
+
+def value_count_int64(
+ values: np.ndarray, # const int64_t[:]
+ dropna: bool,
+) -> tuple[
+ np.ndarray, # np.ndarray[np.int64]
+ np.ndarray, # np.ndarray[np.int64]
+]: ...
diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in
index a25867c4a3b0c..4cacd3245f9d8 100644
--- a/pandas/_libs/hashtable_class_helper.pxi.in
+++ b/pandas/_libs/hashtable_class_helper.pxi.in
@@ -680,6 +680,7 @@ cdef class {{name}}HashTable(HashTable):
def get_labels(self, const {{dtype}}_t[:] values, {{name}}Vector uniques,
Py_ssize_t count_prior=0, Py_ssize_t na_sentinel=-1,
object na_value=None):
+ # -> np.ndarray[np.intp]
_, labels = self._unique(values, uniques, count_prior=count_prior,
na_sentinel=na_sentinel, na_value=na_value,
ignore_na=True, return_inverse=True)
@@ -1012,7 +1013,7 @@ cdef class StringHashTable(HashTable):
-------
uniques : ndarray[object]
Unique values of input, not sorted
- labels : ndarray[int64] (if return_inverse)
+ labels : ndarray[intp_t] (if return_inverse)
The labels from values to uniques
"""
uniques = ObjectVector()
@@ -1045,7 +1046,7 @@ cdef class StringHashTable(HashTable):
-------
uniques : ndarray[object]
Unique values of input, not sorted
- labels : ndarray[int64]
+ labels : ndarray[intp]
The labels from values to uniques
"""
uniques_vector = ObjectVector()
@@ -1056,6 +1057,7 @@ cdef class StringHashTable(HashTable):
def get_labels(self, ndarray[object] values, ObjectVector uniques,
Py_ssize_t count_prior=0, Py_ssize_t na_sentinel=-1,
object na_value=None):
+ # -> np.ndarray[np.intp]
_, labels = self._unique(values, uniques, count_prior=count_prior,
na_sentinel=na_sentinel, na_value=na_value,
ignore_na=True, return_inverse=True)
@@ -1310,6 +1312,7 @@ cdef class PyObjectHashTable(HashTable):
def get_labels(self, ndarray[object] values, ObjectVector uniques,
Py_ssize_t count_prior=0, Py_ssize_t na_sentinel=-1,
object na_value=None):
+ # -> np.ndarray[np.intp]
_, labels = self._unique(values, uniques, count_prior=count_prior,
na_sentinel=na_sentinel, na_value=na_value,
ignore_na=True, return_inverse=True)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 2c4477056a112..95aed9cff123b 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -555,7 +555,7 @@ def factorize_array(
Returns
-------
- codes : ndarray
+ codes : ndarray[np.intp]
uniques : ndarray
"""
hash_klass, values = get_data_algo(values)
@@ -907,9 +907,9 @@ def value_counts_arraylike(values, dropna: bool):
f = getattr(htable, f"value_count_{ndtype}")
keys, counts = f(values, dropna)
- keys = _reconstruct_data(keys, original.dtype, original)
+ res_keys = _reconstruct_data(keys, original.dtype, original)
- return keys, counts
+ return res_keys, counts
def duplicated(values: ArrayLike, keep: str | bool = "first") -> np.ndarray:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 8e12a8cb18b68..0f14dcf0df0bb 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5954,7 +5954,7 @@ def dropna(
def drop_duplicates(
self,
subset: Hashable | Sequence[Hashable] | None = None,
- keep: str | bool = "first",
+ keep: Literal["first"] | Literal["last"] | Literal[False] = "first",
inplace: bool = False,
ignore_index: bool = False,
) -> DataFrame | None:
@@ -6051,7 +6051,7 @@ def drop_duplicates(
def duplicated(
self,
subset: Hashable | Sequence[Hashable] | None = None,
- keep: str | bool = "first",
+ keep: Literal["first"] | Literal["last"] | Literal[False] = "first",
) -> Series:
"""
Return boolean Series denoting duplicate rows.
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index cdb2702e7f867..8478e2a17efa5 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -2138,6 +2138,7 @@ def _factorize_keys(
# "_values_for_factorize"
rk, _ = rk._values_for_factorize() # type: ignore[union-attr,assignment]
+ klass: type[libhashtable.Factorizer] | type[libhashtable.Int64Factorizer]
if is_integer_dtype(lk.dtype) and is_integer_dtype(rk.dtype):
# GH#23917 TODO: needs tests for case where lk is integer-dtype
# and rk is datetime-dtype
| https://api.github.com/repos/pandas-dev/pandas/pulls/41246 | 2021-05-01T01:23:40Z | 2021-05-05T13:02:20Z | 2021-05-05T13:02:20Z | 2021-05-05T14:46:37Z | |
REF: de-lazify Resampler init | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 7fe9d7cb49eb5..f6532aea757de 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -546,6 +546,7 @@ class BaseGroupBy(PandasObject, SelectionMixin, Generic[FrameOrSeries]):
axis: int
grouper: ops.BaseGrouper
obj: FrameOrSeries
+ group_keys: bool
@final
def __len__(self) -> int:
@@ -556,26 +557,17 @@ def __repr__(self) -> str:
# TODO: Better repr for GroupBy object
return object.__repr__(self)
- def _assure_grouper(self) -> None:
- """
- We create the grouper on instantiation sub-classes may have a
- different policy.
- """
- pass
-
@final
@property
def groups(self) -> dict[Hashable, np.ndarray]:
"""
Dict {group name -> group labels}.
"""
- self._assure_grouper()
return self.grouper.groups
@final
@property
def ngroups(self) -> int:
- self._assure_grouper()
return self.grouper.ngroups
@final
@@ -584,7 +576,6 @@ def indices(self):
"""
Dict {group name -> group indices}.
"""
- self._assure_grouper()
return self.grouper.indices
@final
@@ -721,6 +712,7 @@ def get_group(self, name, obj=None):
return obj._take_with_is_copy(inds, axis=self.axis)
+ @final
def __iter__(self) -> Iterator[tuple[Hashable, FrameOrSeries]]:
"""
Groupby iterator.
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index d241132e4d960..213c20294025d 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -6,6 +6,7 @@
from typing import (
TYPE_CHECKING,
Callable,
+ Hashable,
no_type_check,
)
@@ -101,8 +102,8 @@ class Resampler(BaseGroupBy, PandasObject):
Parameters
----------
- obj : pandas object
- groupby : a TimeGrouper object
+ obj : Series or DataFrame
+ groupby : TimeGrouper
axis : int, default 0
kind : str or None
'period', 'timestamp' to override default index treatment
@@ -116,10 +117,8 @@ class Resampler(BaseGroupBy, PandasObject):
After resampling, see aggregate, apply, and transform functions.
"""
- # error: Incompatible types in assignment (expression has type
- # "Optional[BinGrouper]", base class "BaseGroupBy" defined the type as
- # "BaseGrouper")
- grouper: BinGrouper | None # type: ignore[assignment]
+ grouper: BinGrouper
+ exclusions: frozenset[Hashable] = frozenset() # for SelectionMixin compat
# to the groupby descriptor
_attributes = [
@@ -134,7 +133,14 @@ class Resampler(BaseGroupBy, PandasObject):
"offset",
]
- def __init__(self, obj, groupby=None, axis=0, kind=None, **kwargs):
+ def __init__(
+ self,
+ obj: FrameOrSeries,
+ groupby: TimeGrouper,
+ axis: int = 0,
+ kind=None,
+ **kwargs,
+ ):
self.groupby = groupby
self.keys = None
self.sort = True
@@ -143,12 +149,9 @@ def __init__(self, obj, groupby=None, axis=0, kind=None, **kwargs):
self.squeeze = False
self.group_keys = True
self.as_index = True
- self.exclusions = set()
- self.binner = None
- self.grouper = None
- if self.groupby is not None:
- self.groupby._set_grouper(self._convert_obj(obj), sort=True)
+ self.groupby._set_grouper(self._convert_obj(obj), sort=True)
+ self.binner, self.grouper = self._get_binner()
@final
def _shallow_copy(self, obj, **kwargs):
@@ -183,25 +186,12 @@ def __getattr__(self, attr: str):
return object.__getattribute__(self, attr)
- def __iter__(self):
- """
- Resampler iterator.
-
- Returns
- -------
- Generator yielding sequence of (name, subsetted object)
- for each group.
-
- See Also
- --------
- GroupBy.__iter__ : Generator yielding sequence for each group.
- """
- self._set_binner()
- return super().__iter__()
-
+ # error: Signature of "obj" incompatible with supertype "BaseGroupBy"
@property
- def obj(self):
- return self.groupby.obj
+ def obj(self) -> FrameOrSeries: # type: ignore[override]
+ # error: Incompatible return value type (got "Optional[Any]",
+ # expected "FrameOrSeries")
+ return self.groupby.obj # type: ignore[return-value]
@property
def ax(self):
@@ -218,32 +208,24 @@ def _from_selection(self) -> bool:
self.groupby.key is not None or self.groupby.level is not None
)
- def _convert_obj(self, obj):
+ def _convert_obj(self, obj: FrameOrSeries) -> FrameOrSeries:
"""
Provide any conversions for the object in order to correctly handle.
Parameters
----------
- obj : the object to be resampled
+ obj : Series or DataFrame
Returns
-------
- obj : converted object
+ Series or DataFrame
"""
return obj._consolidate()
def _get_binner_for_time(self):
raise AbstractMethodError(self)
- def _set_binner(self):
- """
- Setup our binners.
-
- Cache these as we are an immutable object
- """
- if self.binner is None:
- self.binner, self.grouper = self._get_binner()
-
+ @final
def _get_binner(self):
"""
Create the BinGrouper, assume that self.set_grouper(obj)
@@ -254,12 +236,6 @@ def _get_binner(self):
bin_grouper = BinGrouper(bins, binlabels, indexer=self.groupby.indexer)
return binner, bin_grouper
- def _assure_grouper(self):
- """
- Make sure that we are creating our binner & grouper.
- """
- self._set_binner()
-
@Substitution(
klass="Resampler",
examples="""
@@ -349,7 +325,6 @@ def pipe(
)
def aggregate(self, func, *args, **kwargs):
- self._set_binner()
result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg()
if result is None:
how = func
@@ -400,7 +375,6 @@ def _gotitem(self, key, ndim: int, subset=None):
subset : object, default None
subset to act on
"""
- self._set_binner()
grouper = self.grouper
if subset is None:
subset = self.obj
@@ -417,7 +391,6 @@ def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs):
Re-evaluate the obj with a groupby aggregation.
"""
if grouper is None:
- self._set_binner()
grouper = self.grouper
obj = self._selected_obj
@@ -1050,8 +1023,8 @@ def __init__(self, obj, parent=None, groupby=None, **kwargs):
for attr in self._attributes:
setattr(self, attr, kwargs.get(attr, getattr(parent, attr)))
- # error: Too many arguments for "__init__" of "object"
- super().__init__(None) # type: ignore[call-arg]
+ self.binner = parent.binner
+
self._groupby = groupby
self._groupby.mutated = True
self._groupby.grouper.mutated = True
@@ -1137,7 +1110,6 @@ def _downsample(self, how, **kwargs):
how : string / cython mapped function
**kwargs : kw args passed to how function
"""
- self._set_binner()
how = com.get_cython_func(how) or how
ax = self.ax
obj = self._selected_obj
@@ -1154,7 +1126,7 @@ def _downsample(self, how, **kwargs):
# error: Item "None" of "Optional[Any]" has no attribute "binlabels"
if (
(ax.freq is not None or ax.inferred_freq is not None)
- and len(self.grouper.binlabels) > len(ax) # type: ignore[union-attr]
+ and len(self.grouper.binlabels) > len(ax)
and how is None
):
@@ -1196,7 +1168,6 @@ def _upsample(self, method, limit=None, fill_value=None):
.fillna: Fill NA/NaN values using the specified method.
"""
- self._set_binner()
if self.axis:
raise AssertionError("axis must be 0")
if self._from_selection:
@@ -1257,7 +1228,7 @@ def _get_binner_for_time(self):
return super()._get_binner_for_time()
return self.groupby._get_period_bins(self.ax)
- def _convert_obj(self, obj):
+ def _convert_obj(self, obj: FrameOrSeries) -> FrameOrSeries:
obj = super()._convert_obj(obj)
if self._from_selection:
@@ -1336,7 +1307,6 @@ def _upsample(self, method, limit=None, fill_value=None):
if self.kind == "timestamp":
return super()._upsample(method, limit=limit, fill_value=fill_value)
- self._set_binner()
ax = self.ax
obj = self.obj
new_index = self.binner
@@ -1349,9 +1319,7 @@ def _upsample(self, method, limit=None, fill_value=None):
new_obj = _take_new_index(
obj,
indexer,
- # error: Argument 3 to "_take_new_index" has incompatible type
- # "Optional[Any]"; expected "Index"
- new_index, # type: ignore[arg-type]
+ new_index,
axis=self.axis,
)
return self._wrap_result(new_obj)
@@ -1511,20 +1479,20 @@ def __init__(
else:
try:
self.origin = Timestamp(origin)
- except Exception as e:
+ except (ValueError, TypeError) as err:
raise ValueError(
"'origin' should be equal to 'epoch', 'start', 'start_day', "
"'end', 'end_day' or "
f"should be a Timestamp convertible type. Got '{origin}' instead."
- ) from e
+ ) from err
try:
self.offset = Timedelta(offset) if offset is not None else None
- except Exception as e:
+ except (ValueError, TypeError) as err:
raise ValueError(
"'offset' should be a Timedelta convertible type. "
f"Got '{offset}' instead."
- ) from e
+ ) from err
# always sort time groupers
kwargs["sort"] = True
@@ -1585,10 +1553,9 @@ def _get_resampler(self, obj, kind=None):
def _get_grouper(self, obj, validate: bool = True):
# create the resampler and return our binner
r = self._get_resampler(obj)
- r._set_binner()
return r.binner, r.grouper, r.obj
- def _get_time_bins(self, ax):
+ def _get_time_bins(self, ax: DatetimeIndex):
if not isinstance(ax, DatetimeIndex):
raise TypeError(
"axis must be a DatetimeIndex, but got "
@@ -1964,13 +1931,13 @@ def _insert_nat_bin(
def _adjust_dates_anchored(
- first,
- last,
- freq,
+ first: Timestamp,
+ last: Timestamp,
+ freq: Tick,
closed: Literal["right", "left"] = "right",
origin="start_day",
offset: Timedelta | None = None,
-):
+) -> tuple[Timestamp, Timestamp]:
# First and last offsets should be calculated from the start day to fix an
# error cause by resampling across multiple days when a one day period is
# not a multiple of the frequency. See GH 8683
| AFAICT the only reason `Resampler.__init__` has a lazy component is bc we call `super().__init__(None)` in `GroupByMixin.__init__`. By avoiding that (and directly setting the one attribute we need that super call to set), we can de-lazify `Resampler.__init__`, which in turn allows simplifying a bunch of other methods | https://api.github.com/repos/pandas-dev/pandas/pulls/41245 | 2021-04-30T22:38:50Z | 2021-05-02T23:29:02Z | 2021-05-02T23:29:02Z | 2021-05-03T01:29:35Z |
REGR: Avoid error when defining non existing usecols with python engine | diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index a6d38eab99977..62c511c0edf55 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -299,10 +299,10 @@ def _exclude_implicit_index(self, alldata):
# error: Cannot determine type of 'index_col'
offset = len(self.index_col) # type: ignore[has-type]
- if self._col_indices is not None and len(names) != len(self._col_indices):
- names = [names[i] for i in sorted(self._col_indices)]
-
- return {name: alldata[i + offset] for i, name in enumerate(names)}, names
+ len_alldata = len(alldata)
+ return {
+ name: alldata[i + offset] for i, name in enumerate(names) if i < len_alldata
+ }, names
# legacy
def get_chunk(self, size=None):
@@ -473,7 +473,12 @@ def _infer_columns(self):
self._handle_usecols(columns, names)
else:
num_original_columns = len(names)
- columns = [names]
+ if self._col_indices is not None and len(names) != len(
+ self._col_indices
+ ):
+ columns = [[names[i] for i in sorted(self._col_indices)]]
+ else:
+ columns = [names]
else:
columns = self._handle_usecols(columns, columns[0])
else:
diff --git a/pandas/tests/io/parser/usecols/test_usecols_basic.py b/pandas/tests/io/parser/usecols/test_usecols_basic.py
index 27bad29550d82..371b8bea7def2 100644
--- a/pandas/tests/io/parser/usecols/test_usecols_basic.py
+++ b/pandas/tests/io/parser/usecols/test_usecols_basic.py
@@ -373,3 +373,18 @@ def test_usecols_subset_names_mismatch_orig_columns(all_parsers, usecols):
result = parser.read_csv(StringIO(data), header=0, names=names, usecols=usecols)
expected = DataFrame({"A": [1, 5], "C": [3, 7]})
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("names", [None, ["a", "b"]])
+def test_usecols_indices_out_of_bounds(all_parsers, names):
+ # GH#25623
+ parser = all_parsers
+ data = """
+a,b
+1,2
+ """
+ result = parser.read_csv(StringIO(data), usecols=[0, 2], names=names, header=0)
+ expected = DataFrame({"a": [1], "b": [None]})
+ if names is None and parser.engine == "python":
+ expected = DataFrame({"a": [1]})
+ tm.assert_frame_equal(result, expected)
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
Regression on master so no whatsnew. Restored behaviro of 1.2.4
cc @gfyoung | https://api.github.com/repos/pandas-dev/pandas/pulls/41244 | 2021-04-30T22:09:32Z | 2021-05-12T01:26:19Z | 2021-05-12T01:26:19Z | 2021-05-12T09:19:02Z |
REF: remove unnecessary consolidate in GroupBy.describe | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 7fe9d7cb49eb5..36c7f53d23098 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1817,9 +1817,7 @@ def describe(self, **kwargs):
result = self.apply(lambda x: x.describe(**kwargs))
if self.axis == 1:
return result.T
- # FIXME: not being consolidated breaks
- # test_describe_with_duplicate_output_column_names
- return result._consolidate().unstack()
+ return result.unstack()
@final
def resample(self, rule, *args, **kwargs):
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index 40f8135637292..163303168c240 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -1077,6 +1077,7 @@ def test_describe_with_duplicate_output_column_names(as_index):
"c": [10, 20, 30, 40, 50, 60],
},
columns=["a", "b", "b"],
+ copy=False,
)
expected = (
| <b>update</b> reverted most of this in favor of #41271 | https://api.github.com/repos/pandas-dev/pandas/pulls/41243 | 2021-04-30T22:01:48Z | 2021-05-02T23:30:45Z | 2021-05-02T23:30:45Z | 2021-05-03T01:18:39Z |
REF: make libreduction behavior match _aggregate_series_pure_python | diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index 5b958163159aa..191967585c431 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -27,11 +27,11 @@ from pandas._libs.lib import (
)
-cpdef check_result_array(object obj, Py_ssize_t cnt):
+cpdef check_result_array(object obj):
if (is_array(obj) or
- (isinstance(obj, list) and len(obj) == cnt) or
- getattr(obj, 'shape', None) == (cnt,)):
+ (isinstance(obj, list) and len(obj) == 0) or
+ getattr(obj, 'shape', None) == (0,)):
raise ValueError('Must produce aggregated value')
@@ -89,9 +89,7 @@ cdef class _BaseGrouper:
# On the first pass, we check the output shape to see
# if this looks like a reduction.
initialized = True
- # In all tests other than test_series_grouper and
- # test_series_bin_grouper, we have len(self.dummy_arr) == 0
- check_result_array(res, len(self.dummy_arr))
+ check_result_array(res)
return res, initialized
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 80351a832ec7e..da803badee8c0 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -511,6 +511,8 @@ def _get_index() -> Index:
return self._reindex_output(result)
def _aggregate_named(self, func, *args, **kwargs):
+ # Note: this is very similar to _aggregate_series_pure_python,
+ # but that does not pin group.name
result = {}
initialized = False
@@ -523,7 +525,7 @@ def _aggregate_named(self, func, *args, **kwargs):
output = libreduction.extract_result(output)
if not initialized:
# We only do this validation on the first iteration
- libreduction.check_result_array(output, 0)
+ libreduction.check_result_array(output)
initialized = True
result[name] = output
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index ed3b6d68b71cd..9edbeb412026d 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -985,15 +985,7 @@ def agg_series(self, obj: Series, func: F) -> tuple[ArrayLike, np.ndarray]:
# Preempt TypeError in _aggregate_series_fast
return self._aggregate_series_pure_python(obj, func)
- try:
- return self._aggregate_series_fast(obj, func)
- except ValueError as err:
- if "Must produce aggregated value" in str(err):
- # raised in libreduction
- pass
- else:
- raise
- return self._aggregate_series_pure_python(obj, func)
+ return self._aggregate_series_fast(obj, func)
def _aggregate_series_fast(
self, obj: Series, func: F
@@ -1023,9 +1015,10 @@ def _aggregate_series_pure_python(self, obj: Series, func: F):
result = np.empty(ngroups, dtype="O")
initialized = False
+ # equiv: splitter = self._get_splitter(obj, axis=0)
splitter = get_splitter(obj, group_index, ngroups, axis=0)
- for label, group in enumerate(splitter):
+ for i, group in enumerate(splitter):
# Each step of this loop corresponds to
# libreduction._BaseGrouper._apply_to_group
@@ -1034,11 +1027,11 @@ def _aggregate_series_pure_python(self, obj: Series, func: F):
if not initialized:
# We only do this validation on the first iteration
- libreduction.check_result_array(res, 0)
+ libreduction.check_result_array(res)
initialized = True
- counts[label] = group.shape[0]
- result[label] = res
+ counts[i] = group.shape[0]
+ result[i] = res
npvalues = lib.maybe_convert_objects(result, try_float=False)
out = maybe_cast_pointwise_result(npvalues, obj.dtype, numeric_only=True)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41242 | 2021-04-30T20:34:52Z | 2021-04-30T22:12:16Z | 2021-04-30T22:12:16Z | 2021-04-30T22:36:37Z |
CLN: no need to catch libgroupby validation ValueError | diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 6fa5ce0a201ae..d241132e4d960 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -430,16 +430,23 @@ def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs):
result = grouped._aggregate_item_by_item(how, *args, **kwargs)
else:
result = grouped.aggregate(how, *args, **kwargs)
- except (DataError, AttributeError, KeyError):
+ except DataError:
+ # got TypeErrors on aggregation
+ result = grouped.apply(how, *args, **kwargs)
+ except (AttributeError, KeyError):
# we have a non-reducing function; try to evaluate
# alternatively we want to evaluate only a column of the input
+
+ # test_apply_to_one_column_of_df the function being applied references
+ # a DataFrame column, but aggregate_item_by_item operates column-wise
+ # on Series, raising AttributeError or KeyError
+ # (depending on whether the column lookup uses getattr/__getitem__)
result = grouped.apply(how, *args, **kwargs)
+
except ValueError as err:
if "Must produce aggregated value" in str(err):
# raised in _aggregate_named
- pass
- elif "len(index) != len(labels)" in str(err):
- # raised in libgroupby validation
+ # see test_apply_without_aggregation, test_apply_with_mutated_index
pass
else:
raise
diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py
index 999d8a6c90ba2..f5fc1888d611c 100644
--- a/pandas/tests/resample/test_resampler_grouper.py
+++ b/pandas/tests/resample/test_resampler_grouper.py
@@ -354,11 +354,15 @@ def test_apply_to_one_column_of_df():
{"col": range(10), "col1": range(10, 20)},
index=date_range("2012-01-01", periods=10, freq="20min"),
)
+
+ # access "col" via getattr -> make sure we handle AttributeError
result = df.resample("H").apply(lambda group: group.col.sum())
expected = Series(
[3, 12, 21, 9], index=date_range("2012-01-01", periods=4, freq="H")
)
tm.assert_series_equal(result, expected)
+
+ # access "col" via _getitem__ -> make sure we handle KeyErrpr
result = df.resample("H").apply(lambda group: group["col"].sum())
tm.assert_series_equal(result, expected)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41240 | 2021-04-30T18:23:54Z | 2021-04-30T22:12:53Z | 2021-04-30T22:12:53Z | 2021-04-30T22:32:23Z |
CLN: remove Resampler._typ | diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 141ea4babe970..6fa5ce0a201ae 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -207,15 +207,6 @@ def obj(self):
def ax(self):
return self.groupby.ax
- @property
- def _typ(self) -> str:
- """
- Masquerade for compat as a Series or a DataFrame.
- """
- if isinstance(self._selected_obj, ABCSeries):
- return "series"
- return "dataframe"
-
@property
def _from_selection(self) -> bool:
"""
| ATM `isinstance(resampler, ABCDataFrame)` can be True, which I wasn't aware of until recently. This strikes me as a grade-A footgun. | https://api.github.com/repos/pandas-dev/pandas/pulls/41239 | 2021-04-30T15:57:45Z | 2021-04-30T16:52:15Z | 2021-04-30T16:52:15Z | 2021-04-30T18:12:47Z |
Optimising Series.nunique for Nan values #40865 | diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py
index 65167e6467fd5..760da36a30075 100644
--- a/asv_bench/benchmarks/frame_methods.py
+++ b/asv_bench/benchmarks/frame_methods.py
@@ -563,6 +563,14 @@ def time_frame_nunique(self):
self.df.nunique()
+class SeriesNuniqueWithNan:
+ def setup(self):
+ self.ser = Series(100000 * (100 * [np.nan] + list(range(100)))).astype(float)
+
+ def time_series_nunique_nan(self):
+ self.ser.nunique()
+
+
class Duplicated:
def setup(self):
n = 1 << 20
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 74710ca48308c..be2dbd83dd23d 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -635,7 +635,7 @@ Performance improvements
- Performance improvement in the conversion of pyarrow boolean array to a pandas nullable boolean array (:issue:`41051`)
- Performance improvement for concatenation of data with type :class:`CategoricalDtype` (:issue:`40193`)
- Performance improvement in :meth:`.GroupBy.cummin` and :meth:`.GroupBy.cummax` with nullable data types (:issue:`37493`)
--
+- Performance improvement in :meth:`Series.nunique` with nan values (:issue:`40865`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 42f52618eb07b..36a90468eff7f 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -1040,8 +1040,10 @@ def nunique(self, dropna: bool = True) -> int:
>>> s.nunique()
4
"""
- obj = remove_na_arraylike(self) if dropna else self
- return len(obj.unique())
+ uniqs = self.unique()
+ if dropna:
+ uniqs = remove_na_arraylike(uniqs)
+ return len(uniqs)
@property
def is_unique(self) -> bool:
| - [ ] closes #40865
| https://api.github.com/repos/pandas-dev/pandas/pulls/41236 | 2021-04-30T14:08:32Z | 2021-05-03T15:12:33Z | 2021-05-03T15:12:32Z | 2021-05-03T15:12:37Z |
REF: simplify kwargs unpacking in resample | diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 14d065de7f77f..3dc11d72ed28c 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -1046,11 +1046,9 @@ class _GroupByMixin(PandasObject):
_attributes: list[str] # in practice the same as Resampler._attributes
- def __init__(self, obj, **kwargs):
+ def __init__(self, obj, parent=None, groupby=None, **kwargs):
# reached via ._gotitem and _get_resampler_for_grouping
- parent = kwargs.pop("parent", None)
- groupby = kwargs.pop("groupby", None)
if parent is None:
parent = obj
@@ -1416,15 +1414,13 @@ def get_resampler(obj, kind=None, **kwds):
def get_resampler_for_grouping(
- groupby, rule, how=None, fill_method=None, limit=None, kind=None, **kwargs
+ groupby, rule, how=None, fill_method=None, limit=None, kind=None, on=None, **kwargs
):
"""
Return our appropriate resampler when grouping as well.
"""
# .resample uses 'on' similar to how .groupby uses 'key'
- kwargs["key"] = kwargs.pop("on", None)
-
- tg = TimeGrouper(freq=rule, **kwargs)
+ tg = TimeGrouper(freq=rule, key=on, **kwargs)
resampler = tg._get_resampler(groupby.obj, kind=kind)
return resampler._get_resampler_for_grouping(groupby=groupby)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
Simplified kwargs unpacking in resample, by utilizing keyword-only arguments. | https://api.github.com/repos/pandas-dev/pandas/pulls/41235 | 2021-04-30T13:13:04Z | 2021-04-30T14:55:38Z | 2021-04-30T14:55:38Z | 2021-04-30T14:55:42Z |
ENH: Add formatters parameter for the xlsxwriter engine | diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 719a4472fb9e3..87db1c46e8af6 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -672,6 +672,13 @@ class ExcelWriter(metaclass=abc.ABCMeta):
datetime_format : str, default None
Format string for datetime objects written into Excel files.
(e.g. 'YYYY-MM-DD HH:MM:SS').
+ formatters : dict, default None
+ Add formats to columns of type date and datetime.
+ Accepts a dictionary of column name(key) and format strings(value).
+ Formats for columns specified here will take precedence over the
+ ``datetime_format`` and ``date_format`` parameters for the specified columns.
+ Not supported for multiindex columns.
+ Supported only for engine 'xlsxwriter'.
mode : {'w', 'a'}, default 'w'
File mode to use (write or append). Append does not work with fsspec URLs.
storage_options : dict, optional
@@ -749,6 +756,12 @@ class ExcelWriter(metaclass=abc.ABCMeta):
... ) as writer:
... df.to_excel(writer)
+ You can use formatters for date/datetime columns when the engine is xlsxwriter:
+
+ >>> with ExcelWriter("path_to_file.xlsx",
+ ... formatters={"col1":"YYYY-MM-DD","col2":"MMM"}) as writer:
+ ... df.to_excel(writer)
+
You can also append to an existing Excel file:
>>> with ExcelWriter("path_to_file.xlsx", mode="a", engine="openpyxl") as writer:
@@ -799,6 +812,7 @@ def __new__(
engine=None,
date_format=None,
datetime_format=None,
+ formatters: dict | None = None,
mode: str = "w",
storage_options: StorageOptions = None,
if_sheet_exists: str | None = None,
@@ -849,6 +863,28 @@ def __new__(
stacklevel=4,
)
+ if engine != "xlsxwriter" and formatters is not None:
+ raise NotImplementedError
+
+ if engine == "xlsxwriter":
+ if date_format is not None:
+ warnings.warn(
+ "Use of date_format is deprecated with the xlsxwriter "
+ "engine and will be removed in a future version. "
+ "Use formatters instead.",
+ FutureWarning,
+ stacklevel=2,
+ )
+
+ if datetime_format is not None:
+ warnings.warn(
+ "Use of datetime_format is deprecated with the xlsxwriter "
+ "engine and will be removed in a future version. "
+ "Use formatters instead.",
+ FutureWarning,
+ stacklevel=2,
+ )
+
cls = get_writer(engine)
return object.__new__(cls)
@@ -901,6 +937,7 @@ def __init__(
engine=None,
date_format=None,
datetime_format=None,
+ formatters: dict | None = None,
mode: str = "w",
storage_options: StorageOptions = None,
if_sheet_exists: str | None = None,
@@ -937,6 +974,17 @@ def __init__(
else:
self.datetime_format = datetime_format
+ if formatters is not None:
+ if not isinstance(formatters, dict):
+ raise TypeError(
+ f"Invalid type {type(formatters).__name__}, "
+ "formatters must be dict."
+ )
+ for col_name, fmt in formatters.items():
+ if not isinstance(fmt, str):
+ raise TypeError(f"Format for '{col_name}' is not a string.")
+
+ self.formatters = formatters
self.mode = mode
if if_sheet_exists not in [None, "error", "new", "replace"]:
@@ -960,22 +1008,28 @@ def _get_sheet_name(self, sheet_name):
raise ValueError("Must pass explicit sheet_name or set cur_sheet property")
return sheet_name
- def _value_with_fmt(self, val):
+ def _value_with_fmt(self, val, col: int | None = None) -> tuple:
"""
Convert numpy types to Python types for the Excel writers.
Parameters
----------
val : object
- Value to be written into cells
+ Value to be written into cells.
+ col : int, optional
+ Column number of the cell.
Returns
-------
Tuple with the first element being the converted value and the second
being an optional format
"""
+ col_format = None
fmt = None
+ if self.formatters and isinstance(self.formatters, dict):
+ col_format = self.formatters.get(col, None)
+
if is_integer(val):
val = int(val)
elif is_float(val):
@@ -983,9 +1037,9 @@ def _value_with_fmt(self, val):
elif is_bool(val):
val = bool(val)
elif isinstance(val, datetime.datetime):
- fmt = self.datetime_format
+ fmt = col_format if col_format else self.datetime_format
elif isinstance(val, datetime.date):
- fmt = self.date_format
+ fmt = col_format if col_format else self.date_format
elif isinstance(val, datetime.timedelta):
val = val.total_seconds() / 86400
fmt = "0"
diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py
index efef86329314b..2675be5b7384a 100644
--- a/pandas/io/excel/_odswriter.py
+++ b/pandas/io/excel/_odswriter.py
@@ -25,6 +25,7 @@ def __init__(
engine: str | None = None,
date_format=None,
datetime_format=None,
+ formatters: dict[Any, str] | None = None,
mode: str = "w",
storage_options: StorageOptions = None,
if_sheet_exists: str | None = None,
@@ -37,6 +38,7 @@ def __init__(
super().__init__(
path,
+ formatters=formatters,
mode=mode,
storage_options=storage_options,
if_sheet_exists=if_sheet_exists,
diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py
index bc067e216760c..19eb00b3917de 100644
--- a/pandas/io/excel/_openpyxl.py
+++ b/pandas/io/excel/_openpyxl.py
@@ -35,6 +35,7 @@ def __init__(
engine=None,
date_format=None,
datetime_format=None,
+ formatters: dict[Any, str] | None = None,
mode: str = "w",
storage_options: StorageOptions = None,
if_sheet_exists: str | None = None,
@@ -45,6 +46,7 @@ def __init__(
super().__init__(
path,
+ formatters=formatters,
mode=mode,
storage_options=storage_options,
if_sheet_exists=if_sheet_exists,
diff --git a/pandas/io/excel/_xlsxwriter.py b/pandas/io/excel/_xlsxwriter.py
index 7500a33b1f097..3e5fdb38613a1 100644
--- a/pandas/io/excel/_xlsxwriter.py
+++ b/pandas/io/excel/_xlsxwriter.py
@@ -5,6 +5,8 @@
import pandas._libs.json as json
from pandas._typing import StorageOptions
+from pandas.core.dtypes.common import is_hashable
+
from pandas.io.excel._base import ExcelWriter
from pandas.io.excel._util import validate_freeze_panes
@@ -171,6 +173,7 @@ def __init__(
engine=None,
date_format=None,
datetime_format=None,
+ formatters: dict[Any, str] | None = None,
mode: str = "w",
storage_options: StorageOptions = None,
if_sheet_exists: str | None = None,
@@ -187,6 +190,7 @@ def __init__(
super().__init__(
path,
engine=engine,
+ formatters=formatters,
date_format=date_format,
datetime_format=datetime_format,
mode=mode,
@@ -195,6 +199,7 @@ def __init__(
engine_kwargs=engine_kwargs,
)
+ self.col_mapping = None
self.book = Workbook(self.handles.handle, **engine_kwargs)
def save(self):
@@ -204,9 +209,15 @@ def save(self):
return self.book.close()
def write_cells(
- self, cells, sheet_name=None, startrow=0, startcol=0, freeze_panes=None
+ self,
+ cells,
+ sheet_name=None,
+ startrow=0,
+ startcol=0,
+ freeze_panes=None,
):
# Write the frame cells using xlsxwriter.
+
sheet_name = self._get_sheet_name(sheet_name)
if sheet_name in self.sheets:
@@ -220,9 +231,19 @@ def write_cells(
if validate_freeze_panes(freeze_panes):
wks.freeze_panes(*(freeze_panes))
- for cell in cells:
- val, fmt = self._value_with_fmt(cell.val)
+ # Mapping the column numbers to the formats
+ self.formatters: dict[Any, str] | None
+ if self.col_mapping and self.formatters:
+ self.formatters = {
+ colno: self.formatters[colname]
+ for colno, colname in self.col_mapping.items()
+ if is_hashable(colname) and colname in self.formatters
+ }
+ else:
+ self.formatters = None
+ for cell in cells:
+ val, fmt = self._value_with_fmt(cell.val, cell.col)
stylekey = json.dumps(cell.style)
if fmt:
stylekey += fmt
diff --git a/pandas/io/excel/_xlwt.py b/pandas/io/excel/_xlwt.py
index 8a7605b80f6b4..bc3c918e616ea 100644
--- a/pandas/io/excel/_xlwt.py
+++ b/pandas/io/excel/_xlwt.py
@@ -25,6 +25,7 @@ def __init__(
engine=None,
date_format=None,
datetime_format=None,
+ formatters: dict[Any, str] | None = None,
encoding=None,
mode: str = "w",
storage_options: StorageOptions = None,
@@ -39,6 +40,7 @@ def __init__(
super().__init__(
path,
+ formatters=formatters,
mode=mode,
storage_options=storage_options,
if_sheet_exists=if_sheet_exists,
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index b285fa5f315ed..6e3401d324d4e 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -7,6 +7,7 @@
import itertools
import re
from typing import (
+ Any,
Callable,
Hashable,
Iterable,
@@ -530,6 +531,20 @@ def _format_value(self, val):
)
return val
+ def _get_col_mapping(self) -> dict[int, Any] | None:
+ """
+ Get the mapping between the column number and column name
+ """
+ if not isinstance(self.columns, MultiIndex):
+ coloffset = 0
+ if self.index:
+ coloffset = 1
+ if isinstance(self.df.index, MultiIndex):
+ coloffset = len(self.df.index[0])
+
+ return {i + coloffset: j for i, j in enumerate(self.columns)}
+ return None
+
def _format_header_mi(self) -> Iterable[ExcelCell]:
if self.columns.nlevels > 1:
if not self.index:
@@ -836,6 +851,9 @@ def write(
)
need_save = True
+ if writer.engine == "xlsxwriter":
+ writer.col_mapping = self._get_col_mapping()
+
try:
writer.write_cells(
formatted_cells,
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index 77837bea3e48a..52a1834a24186 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -1341,6 +1341,34 @@ def test_if_sheet_exists_raises(self, ext):
with pytest.raises(ValueError, match=re.escape(msg)):
ExcelWriter(f, if_sheet_exists="replace")
+ def test_formatters_xlsx(self, engine, ext):
+ # GH 30275
+ # check that an exception is raised when the engine is not xlsxwriter
+ with tm.ensure_clean(ext) as path:
+ if engine == "xlsxwriter":
+ pytest.skip("formatters is compatible with xlsxwriter")
+ with pytest.raises(NotImplementedError, match=""):
+ ExcelWriter(path, formatters={"col1": "MMM"})
+
+ def test_formatters_xlsx_warn(self, engine, ext):
+ # GH 30275
+ if engine == "xlsxwriter":
+ with tm.assert_produces_warning(FutureWarning) as m:
+ with tm.ensure_clean(ext) as path:
+ with ExcelWriter(path, datetime_format="DD.MM.YYYY HH-MM-SS") as e:
+ pass
+ assert "datetime_format is deprecated with the xlsxwriter engine" in str(
+ m[0].message
+ )
+
+ with tm.assert_produces_warning(FutureWarning) as m:
+ with tm.ensure_clean(ext) as path:
+ with ExcelWriter(path, date_format="DD.MM.YYYY") as e:
+ pass
+ assert "date_format is deprecated with the xlsxwriter engine" in str(
+ m[0].message
+ )
+
class TestExcelWriterEngineTests:
@pytest.mark.parametrize(
diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py
index 6de378f6a3d3e..0199127a87807 100644
--- a/pandas/tests/io/excel/test_xlsxwriter.py
+++ b/pandas/tests/io/excel/test_xlsxwriter.py
@@ -1,3 +1,7 @@
+from datetime import (
+ date,
+ datetime,
+)
import warnings
import pytest
@@ -61,3 +65,156 @@ def test_write_append_mode_raises(ext):
with tm.ensure_clean(ext) as f:
with pytest.raises(ValueError, match=msg):
ExcelWriter(f, engine="xlsxwriter", mode="a")
+
+
+@pytest.mark.parametrize("head", [True, False, ["col1", "col2"]])
+@pytest.mark.parametrize(
+ "data,fmt_set,out_fmt",
+ [
+ (
+ datetime(2013, 1, 13, 18, 20, 52),
+ "DD/MM/YYYY",
+ "DD/MM/YYYY",
+ ),
+ (date(2014, 1, 31), "MMM", "MMM"),
+ ],
+)
+def test_formatters(ext, head, data, fmt_set, out_fmt):
+ # GH 30275
+ df = tm.makeCustomDataframe(
+ 6,
+ 2,
+ c_idx_names=False,
+ r_idx_names=False,
+ data_gen_f=lambda r, c: data,
+ )
+ out_fmt_list = [out_fmt] * len(df.columns)
+ dict_for_formatters = dict(zip(df.columns, [fmt_set] * len(df.columns)))
+ cells_to_check = ["B4", "C4"]
+
+ with tm.ensure_clean(ext) as path:
+ with ExcelWriter(path, formatters=dict_for_formatters) as writer:
+ df.to_excel(writer, columns=None, header=head, index=True)
+
+ openpyxl = pytest.importorskip("openpyxl")
+ read_workbook = openpyxl.load_workbook(path)
+ read_worksheet = read_workbook["Sheet1"]
+
+ formats = []
+ for cl in cells_to_check:
+ cell = read_worksheet[cl]
+ read_num_format = cell.number_format
+ formats.append(read_num_format)
+
+ assert formats == out_fmt_list
+
+
+@pytest.mark.parametrize("head", [True, False, ["col1", "col2"]])
+@pytest.mark.parametrize(
+ "data,fmt_set,out_fmt",
+ [
+ (
+ datetime(2013, 1, 13, 18, 20, 52),
+ "DD/MM/YYYY",
+ "YYYY-MM-DD HH:MM:SS",
+ ),
+ (date(2014, 1, 31), "MMM", "YYYY-MM-DD"),
+ ],
+)
+def test_formatters_multiindex_cols(ext, head, data, fmt_set, out_fmt):
+ # GH 30275
+ df = tm.makeCustomDataframe(
+ 6,
+ 2,
+ c_idx_names=False,
+ r_idx_names=False,
+ c_idx_nlevels=2,
+ data_gen_f=lambda r, c: data,
+ )
+ out_fmt_list = [out_fmt] * len(df.columns)
+ dict_for_formatters = dict(zip(df.columns, [fmt_set] * len(df.columns)))
+ cells_to_check = ["B4", "C4"]
+
+ with tm.ensure_clean(ext) as path:
+ with ExcelWriter(path, formatters=dict_for_formatters) as writer:
+ df.to_excel(writer, columns=None, header=head, index=True)
+
+ openpyxl = pytest.importorskip("openpyxl")
+ read_workbook = openpyxl.load_workbook(path)
+ read_worksheet = read_workbook["Sheet1"]
+
+ formats = []
+ for cl in cells_to_check:
+ cell = read_worksheet[cl]
+ read_num_format = cell.number_format
+ formats.append(read_num_format)
+
+ assert formats == out_fmt_list
+
+
+@pytest.mark.parametrize(
+ "df,dict_for_formatters,cols,out_fmt_list",
+ [
+ # Timeseries data
+ (
+ tm.makeTimeDataFrame()[:6],
+ {"B": "0%", "C": "#,##0"},
+ None,
+ ["YYYY-MM-DD HH:MM:SS", "General", "General", "General", "General"],
+ ),
+ # Duplicated columns
+ (
+ DataFrame(
+ {
+ "A": [1, 1, 1, 1],
+ "B": [2.34, 2.34, 2.34, 2.34],
+ "C": [
+ datetime(2014, 1, 31),
+ datetime(1999, 9, 24),
+ datetime(2014, 1, 31),
+ datetime(1999, 9, 24),
+ ],
+ "D": ["abc", "abc", "def", "def"],
+ }
+ ),
+ {
+ "B": "0%",
+ "C": "YYYY",
+ },
+ ["B", "C", "C", "A"],
+ ["General", "General", "YYYY", "YYYY", "General"],
+ ),
+ ],
+)
+def test_formatters_others(ext, df, dict_for_formatters, cols, out_fmt_list):
+ # GH 30275
+ cells_to_check = ["A3", "B3", "C3", "D3", "E3"]
+
+ with tm.ensure_clean(ext) as path:
+ with ExcelWriter(path, formatters=dict_for_formatters) as writer:
+ df.to_excel(writer, columns=cols, header=True, index=True)
+
+ openpyxl = pytest.importorskip("openpyxl")
+ read_workbook = openpyxl.load_workbook(path)
+ read_worksheet = read_workbook["Sheet1"]
+
+ formats = []
+ for cl in cells_to_check:
+ cell = read_worksheet[cl]
+ read_num_format = cell.number_format
+ formats.append(read_num_format)
+ assert formats == out_fmt_list
+
+
+def test_check_exceptions(ext):
+ # GH 30275
+ with tm.ensure_clean(ext) as path:
+ with tm.ensure_clean(ext) as path:
+ with pytest.raises(
+ TypeError,
+ match="Invalid type list, formatters must be dict.",
+ ):
+ ExcelWriter(path, formatters=[1, 2, 3])
+
+ with pytest.raises(TypeError, match="Format for 'B' is not a string."):
+ ExcelWriter(path, formatters={"A": "0%", "B": 234})
| - [X] closes #30275
- [X] tests added / passed
- [X] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
Currently pandas doesn't support different formats for columns of the type `date`/`datetime`. Giving the provision to do so using the `formatters` parameter as shown below:
**Master**
```
from datetime import datetime
df = pd.DataFrame(
{
"Col1": [1010.34, 2020.67, 3030.65,3210.65],
"Col2": [
datetime(2014, 1, 31),
datetime(2014, 1, 31),
datetime(2014, 1, 31),
datetime(2014, 1, 31)
],
"Col3": [
datetime(2014, 1, 31),
datetime(2014, 1, 31),
datetime(2014, 1, 31),
datetime(2014, 1, 31)
],
"Col4": [
datetime(2014, 1, 31),
datetime(2014, 1, 31),
datetime(2014, 1, 31),
datetime(2014, 1, 31)]
},
)
writer = pd.ExcelWriter("pd_datetime.xlsx",
engine='xlsxwriter',
datetime_format='MM/DD/YYYY HH:MM:SS',
date_format='MM/DD/YYYY')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
```
**Output of the file**

**Proposed change**
```
writer = pd.ExcelWriter(
"pd_datetime.xlsx",
engine="xlsxwriter",
datetime_format="MM/DD/YYYY HH:MM:SS",
date_format="MM/DD/YYYY",
formatters={"Col2": "mmmm", "Col3": "YYYY"},
)
df.to_excel(writer, sheet_name="Sheet1")
writer.save()
```
**Output of the file**

The `date`/`datetime` columns that do not have a format specified in the `formatters` dict will take the format from the `date_format`/`datetime_format` parameters.
PS- The proposed change is currently applicable **only** for the `date`/`datetime` types but can easily be extended for `int` and `float` as well. | https://api.github.com/repos/pandas-dev/pandas/pulls/41232 | 2021-04-30T06:25:46Z | 2021-10-16T20:49:26Z | null | 2021-10-16T20:49:26Z |
REF: avoid passing empty list to concat in groupby methods | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 771ba2845db6e..ebc061a5345a2 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1754,11 +1754,16 @@ def _iterate_column_groupbys(self):
def _apply_to_column_groupbys(self, func) -> DataFrame:
from pandas.core.reshape.concat import concat
- return concat(
- (func(col_groupby) for _, col_groupby in self._iterate_column_groupbys()),
- keys=self._selected_obj.columns,
- axis=1,
- )
+ columns = self._selected_obj.columns
+ results = [
+ func(col_groupby) for _, col_groupby in self._iterate_column_groupbys()
+ ]
+
+ if not len(results):
+ # concat would raise
+ return DataFrame([], columns=columns, index=self.grouper.result_index)
+ else:
+ return concat(results, keys=columns, axis=1)
def count(self) -> DataFrame:
"""
@@ -1850,27 +1855,30 @@ def nunique(self, dropna: bool = True) -> DataFrame:
# Try to consolidate with normal wrapping functions
obj = self._obj_with_exclusions
- axis_number = obj._get_axis_number(self.axis)
- other_axis = int(not axis_number)
- if axis_number == 0:
+ if self.axis == 0:
iter_func = obj.items
else:
iter_func = obj.iterrows
- results = concat(
- [
- SeriesGroupBy(content, selection=label, grouper=self.grouper).nunique(
- dropna
- )
- for label, content in iter_func()
- ],
- axis=1,
- )
- results = cast(DataFrame, results)
+ res_list = [
+ SeriesGroupBy(content, selection=label, grouper=self.grouper).nunique(
+ dropna
+ )
+ for label, content in iter_func()
+ ]
+ if res_list:
+ results = concat(res_list, axis=1)
+ results = cast(DataFrame, results)
+ else:
+ # concat would raise
+ results = DataFrame(
+ [], index=self.grouper.result_index, columns=obj.columns[:0]
+ )
- if axis_number == 1:
+ if self.axis == 1:
results = results.T
+ other_axis = 1 - self.axis
results._get_axis(other_axis).names = obj._get_axis(other_axis).names
if not self.as_index:
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 14d065de7f77f..af9d165b94927 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -450,11 +450,6 @@ def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs):
elif "len(index) != len(labels)" in str(err):
# raised in libgroupby validation
pass
- elif "No objects to concatenate" in str(err):
- # raised in concat call
- # In tests this is reached via either
- # _apply_to_column_groupbys (ohlc) or DataFrameGroupBy.nunique
- pass
else:
raise
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 3f6485be871f1..884966ca6e85c 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -2020,6 +2020,12 @@ def test_groupby_crash_on_nunique(axis):
tm.assert_frame_equal(result, expected)
+ # same thing, but empty columns
+ gb = df[[]].groupby(axis=axis_number, level=0)
+ res = gb.nunique()
+ exp = expected[[]]
+ tm.assert_frame_equal(res, exp)
+
def test_groupby_list_level():
# GH 9790
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41231 | 2021-04-30T03:07:37Z | 2021-04-30T15:15:37Z | 2021-04-30T15:15:37Z | 2021-04-30T15:34:58Z |
COMPAT: float() exception type for py310 | diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 92618605e47cc..19fd48a772493 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -1598,7 +1598,7 @@ def _ensure_numeric(x):
elif not (is_float(x) or is_integer(x) or is_complex(x)):
try:
x = float(x)
- except ValueError:
+ except (TypeError, ValueError):
# e.g. "1+1j" or "foo"
try:
x = complex(x)
| `float()` raises TypeError in py310
```
________________ TestEnsureNumeric.test_non_convertable_values _________________
self = <pandas.tests.test_nanops.TestEnsureNumeric object at 0x7f7da1e029e0>
def test_non_convertable_values(self):
msg = "Could not convert foo to numeric"
with pytest.raises(TypeError, match=msg):
nanops._ensure_numeric("foo")
# with the wrong type, python raises TypeError for us
msg = "argument must be a string or a number"
with pytest.raises(TypeError, match=msg):
> nanops._ensure_numeric({})
pandas/tests/test_nanops.py:771:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
x = {}
def _ensure_numeric(x):
if isinstance(x, np.ndarray):
if is_integer_dtype(x) or is_bool_dtype(x):
x = x.astype(np.float64)
elif is_object_dtype(x):
try:
x = x.astype(np.complex128)
except (TypeError, ValueError):
try:
x = x.astype(np.float64)
except (TypeError, ValueError) as err:
# GH#29941 we get here with object arrays containing strs
raise TypeError(f"Could not convert {x} to numeric") from err
else:
if not np.any(np.imag(x)):
x = x.real
elif not (is_float(x) or is_integer(x) or is_complex(x)):
try:
> x = float(x)
E TypeError: float() argument must be a string or a real number, not 'dict'
pandas/core/nanops.py:1600: TypeError
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/41230 | 2021-04-30T02:58:55Z | 2021-04-30T14:54:54Z | 2021-04-30T14:54:54Z | 2021-06-18T02:29:52Z |
COMPAT: error massage for py310 | diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py
index 62d368264752b..771d60b000a7d 100644
--- a/pandas/tests/arrays/test_datetimelike.py
+++ b/pandas/tests/arrays/test_datetimelike.py
@@ -1150,7 +1150,7 @@ def test_array_interface(self, arr1d):
tm.assert_numpy_array_equal(result, arr.asi8)
# to other dtypes
- msg = r"float\(\) argument must be a string or a number, not 'Period'"
+ msg = r"float\(\) argument must be a string or a( real)? number, not 'Period'"
with pytest.raises(TypeError, match=msg):
np.asarray(arr, dtype="float64")
| https://api.github.com/repos/pandas-dev/pandas/pulls/41228 | 2021-04-30T02:35:26Z | 2021-04-30T15:16:20Z | 2021-04-30T15:16:20Z | 2021-06-18T02:29:45Z | |
BUG: read_excel trailing blank rows and columns | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 74710ca48308c..1bad9401ba312 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -795,6 +795,7 @@ I/O
- Bug in :func:`read_hdf` returning unexpected records when filtering on categorical string columns using ``where`` parameter (:issue:`39189`)
- Bug in :func:`read_sas` raising ``ValueError`` when ``datetimes`` were null (:issue:`39725`)
- Bug in :func:`read_excel` dropping empty values from single-column spreadsheets (:issue:`39808`)
+- Bug in :func:`read_excel` loading trailing empty rows/columns for some filetypes (:issue:`41167`)
- Bug in :func:`read_excel` raising ``AttributeError`` with ``MultiIndex`` header followed by two empty rows and no index, and bug affecting :func:`read_excel`, :func:`read_csv`, :func:`read_table`, :func:`read_fwf`, and :func:`read_clipboard` where one blank row after a ``MultiIndex`` header with no index would be dropped (:issue:`40442`)
- Bug in :meth:`DataFrame.to_string` misplacing the truncation column when ``index=False`` (:issue:`40907`)
- Bug in :func:`read_orc` always raising ``AttributeError`` (:issue:`40918`)
diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py
index a99f8e2625602..2071076d04a24 100644
--- a/pandas/io/excel/_openpyxl.py
+++ b/pandas/io/excel/_openpyxl.py
@@ -571,15 +571,18 @@ def get_sheet_data(self, sheet, convert_float: bool) -> list[list[Scalar]]:
last_row_with_data = -1
for row_number, row in enumerate(sheet.rows):
converted_row = [self._convert_cell(cell, convert_float) for cell in row]
- if not all(cell == "" for cell in converted_row):
+ while converted_row and converted_row[-1] == "":
+ # trim trailing empty elements
+ converted_row.pop()
+ if converted_row:
last_row_with_data = row_number
data.append(converted_row)
# Trim trailing empty rows
data = data[: last_row_with_data + 1]
- if self.book.read_only and len(data) > 0:
- # With dimension reset, openpyxl no longer pads rows
+ if len(data) > 0:
+ # extend rows to max width
max_width = max(len(data_row) for data_row in data)
if min(len(data_row) for data_row in data) < max_width:
empty_cell: list[Scalar] = [""]
diff --git a/pandas/io/excel/_pyxlsb.py b/pandas/io/excel/_pyxlsb.py
index 71ec189854f6d..02b8090adcfdf 100644
--- a/pandas/io/excel/_pyxlsb.py
+++ b/pandas/io/excel/_pyxlsb.py
@@ -75,7 +75,27 @@ def _convert_cell(self, cell, convert_float: bool) -> Scalar:
return cell.v
def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
- return [
- [self._convert_cell(c, convert_float) for c in r]
- for r in sheet.rows(sparse=False)
- ]
+ data: list[list[Scalar]] = []
+ prevous_row_number = -1
+ # When sparse=True the rows can have different lengths and empty rows are
+ # not returned. The cells are namedtuples of row, col, value (r, c, v).
+ for row in sheet.rows(sparse=True):
+ row_number = row[0].r
+ converted_row = [self._convert_cell(cell, convert_float) for cell in row]
+ while converted_row and converted_row[-1] == "":
+ # trim trailing empty elements
+ converted_row.pop()
+ if converted_row:
+ data.extend([[]] * (row_number - prevous_row_number - 1))
+ data.append(converted_row)
+ prevous_row_number = row_number
+ if data:
+ # extend rows to max_width
+ max_width = max(len(data_row) for data_row in data)
+ if min(len(data_row) for data_row in data) < max_width:
+ empty_cell: list[Scalar] = [""]
+ data = [
+ data_row + (max_width - len(data_row)) * empty_cell
+ for data_row in data
+ ]
+ return data
diff --git a/pandas/tests/io/data/excel/trailing_blanks.ods b/pandas/tests/io/data/excel/trailing_blanks.ods
new file mode 100644
index 0000000000000..a56fbfe452387
Binary files /dev/null and b/pandas/tests/io/data/excel/trailing_blanks.ods differ
diff --git a/pandas/tests/io/data/excel/trailing_blanks.xls b/pandas/tests/io/data/excel/trailing_blanks.xls
new file mode 100644
index 0000000000000..32aeb3fe36b05
Binary files /dev/null and b/pandas/tests/io/data/excel/trailing_blanks.xls differ
diff --git a/pandas/tests/io/data/excel/trailing_blanks.xlsb b/pandas/tests/io/data/excel/trailing_blanks.xlsb
new file mode 100644
index 0000000000000..b40b390a48f38
Binary files /dev/null and b/pandas/tests/io/data/excel/trailing_blanks.xlsb differ
diff --git a/pandas/tests/io/data/excel/trailing_blanks.xlsm b/pandas/tests/io/data/excel/trailing_blanks.xlsm
new file mode 100644
index 0000000000000..9f8ca5370ef81
Binary files /dev/null and b/pandas/tests/io/data/excel/trailing_blanks.xlsm differ
diff --git a/pandas/tests/io/data/excel/trailing_blanks.xlsx b/pandas/tests/io/data/excel/trailing_blanks.xlsx
new file mode 100644
index 0000000000000..8f1a739be9078
Binary files /dev/null and b/pandas/tests/io/data/excel/trailing_blanks.xlsx differ
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index c4b3221e1d3a7..401e913d9d7a7 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -1204,6 +1204,15 @@ def test_multiheader_two_blank_lines(self, read_ext):
)
tm.assert_frame_equal(result, expected)
+ def test_trailing_blanks(self, read_ext):
+ """
+ Sheets can contain blank cells with no data. Some of our readers
+ were including those cells, creating many empty rows and columns
+ """
+ file_name = "trailing_blanks" + read_ext
+ result = pd.read_excel(file_name)
+ assert result.shape == (3, 3)
+
class TestExcelFileRead:
@pytest.fixture(autouse=True)
| - [x] closes #41167
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41227 | 2021-04-29T23:13:08Z | 2021-05-06T01:41:26Z | 2021-05-06T01:41:26Z | 2021-05-06T04:00:43Z |
DOC: Add hint for "Product space too large" | diff --git a/pandas/_testing/contexts.py b/pandas/_testing/contexts.py
index e20d2d58e499f..f5fcc855f1fba 100644
--- a/pandas/_testing/contexts.py
+++ b/pandas/_testing/contexts.py
@@ -5,12 +5,14 @@
from pathlib import Path
import random
from shutil import rmtree
+import signal
import string
import tempfile
from typing import (
IO,
Any,
)
+import warnings
import numpy as np
@@ -236,3 +238,28 @@ def __enter__(self):
def __exit__(self, exc_type, exc_value, traceback):
np.random.set_state(self.start_state)
+
+
+@contextmanager
+def timeout(seconds):
+ def timeout_handler(signum, frame):
+ raise RuntimeError
+
+ has_alarm = True
+ try:
+ orig_handler = signal.signal(signal.SIGALRM, timeout_handler)
+ except AttributeError:
+ if not hasattr(signal, "SIGALRM") or not hasattr(signal, "alarm"):
+ warnings.warn(
+ "SIGALRM not available on this platform, timeout will not be enforced"
+ )
+ has_alarm = False
+
+ if has_alarm:
+ signal.alarm(seconds)
+ try:
+ yield
+ finally:
+ if has_alarm:
+ signal.alarm(0)
+ signal.signal(signal.SIGALRM, orig_handler)
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 52bf44a0bb4ec..63dcfab80a83e 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -3413,7 +3413,24 @@ def _reindex_output(
if qs is not None:
levels_list.append(qs)
names = names + [None]
- index, _ = MultiIndex.from_product(levels_list, names=names).sortlevel()
+ try:
+ index, _ = MultiIndex.from_product(
+ levels_list, names=self.grouper.names
+ ).sortlevel()
+ except (ValueError, MemoryError) as err:
+ err_str = str(err)
+ if "Product space too large" in err_str or "array is too big" in err_str:
+ raise ValueError(
+ "Group by product space too large to allocate arrays! "
+ "Consider setting `observed=True` to reduce size."
+ ) from err
+ elif isinstance(err, MemoryError) and not self.observed:
+ raise MemoryError(
+ err_str + ". Consider setting `observed=True` to reduce size of "
+ "group by product space if appropriate."
+ ) from err
+ else:
+ raise
if self.as_index:
d = {
diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py
index a3fa24c7ee1e0..9f56a6e1c0e98 100644
--- a/pandas/core/shared_docs.py
+++ b/pandas/core/shared_docs.py
@@ -144,6 +144,12 @@
-----
See the `user guide
<https://pandas.pydata.org/pandas-docs/stable/groupby.html>`__ for more.
+
+If you encounter an error regarding memory allocation or space (e.g.
+``ValueError("Product space too large to allocate arrays!")``),
+you are trying to group over too complex a column cross-product to fit in memory.
+If any of those columns are categorical, you may be able to circumvent this issue
+by passing ``observed=True``.
"""
_shared_docs[
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 3de6af8eef694..ea2e25dd9ced4 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -1,6 +1,7 @@
from datetime import datetime
from decimal import Decimal
from io import StringIO
+import sys
import numpy as np
import pytest
@@ -24,6 +25,7 @@
to_datetime,
)
import pandas._testing as tm
+from pandas._testing.contexts import timeout
from pandas.core.base import SpecificationError
import pandas.core.common as com
@@ -2502,6 +2504,62 @@ def test_datetime_categorical_multikey_groupby_indices():
assert result == expected
+def test_groupby_categorical_crossproduct():
+ def _make_df(n, k):
+ df = DataFrame(
+ {
+ "A": Categorical(np.arange(n), np.arange(n)),
+ }
+ )
+ for i in range(1, k):
+ v = np.tile(np.arange(25), n // 25)
+ df[i] = v
+ return df
+
+ def is_32bit():
+ return not (sys.maxsize > 2 ** 32)
+
+ # This combination will trigger the signed integer overflow for a 64 bit
+ # integer, thus triggering the ValueError code path. If somehow this doesn't
+ # throw a ValueError, it will throw a MemoryError, trying to allocate > 4 exibytes
+ # of memory.
+ n = 1000
+ k = 16
+ df = _make_df(n, k)
+
+ message = r"Group by product space too large to allocate arrays.*"
+ with pytest.raises(ValueError, match=message):
+ g = df.groupby(list(df.columns))
+ with timeout(1):
+ g[1].sum()
+ g = df.groupby(list(df.columns), observed=True)
+ with timeout(1):
+ assert g[1].sum().max() == 24
+
+ # This combination will just throw a MemoryError as it tries to allocate
+ # more than 4 exibytes. Test for the patched error message.
+ k = 12
+ df = _make_df(n, k)
+
+ message = r"Unable to allocate.+(Consider setting `observed=True`).*"
+ with pytest.raises(MemoryError, match=message):
+ g = df.groupby(list(df.columns))
+ with timeout(1):
+ g[1].sum()
+
+ # This cross-product is still too large for a 32-bit architecture.
+ if not is_32bit():
+ g = df.groupby(list(df.columns), observed=True)
+ with timeout(1):
+ assert g[1].sum().max() == 24
+ else:
+ message = r"Unable to allocate.+"
+ with pytest.raises(MemoryError, match=message):
+ g = df.groupby(list(df.columns), observed=True)
+ with timeout(1):
+ g[1].sum()
+
+
def test_rolling_wrong_param_min_period():
# GH34037
name_l = ["Alice"] * 5 + ["Bob"] * 5
| Adds a note to the documentation for `DataFrame.groupby` suggesting that the cause of a `Product space too large to allocate arrays!` error may be from unexpected behavior when grouping on a combination of sparse categorical columns.
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41226 | 2021-04-29T21:41:44Z | 2022-01-16T17:55:49Z | null | 2022-01-16T17:55:49Z |
REF: maybe_apply_* in core.apply | diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 9a75857c2586d..1aa08356982d2 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -156,7 +156,7 @@ def agg(self) -> FrameOrSeriesUnion | None:
kwargs = self.kwargs
if isinstance(arg, str):
- return self.maybe_apply_str()
+ return self.apply_str()
if is_dict_like(arg):
return self.agg_dict_like()
@@ -456,7 +456,7 @@ def agg_dict_like(self) -> FrameOrSeriesUnion:
return result
- def maybe_apply_str(self) -> FrameOrSeriesUnion:
+ def apply_str(self) -> FrameOrSeriesUnion:
"""
Compute apply in case of a string.
@@ -465,8 +465,7 @@ def maybe_apply_str(self) -> FrameOrSeriesUnion:
result: Series or DataFrame
"""
# Caller is responsible for checking isinstance(self.f, str)
- f = self.f
- f = cast(str, f)
+ f = cast(str, self.f)
obj = self.obj
@@ -482,7 +481,7 @@ def maybe_apply_str(self) -> FrameOrSeriesUnion:
raise ValueError(f"Operation {f} does not support axis=1")
return self._try_aggregate_string_function(obj, f, *self.args, **self.kwargs)
- def maybe_apply_multiple(self) -> FrameOrSeriesUnion | None:
+ def apply_multiple(self) -> FrameOrSeriesUnion:
"""
Compute apply in case of a list-like or dict-like.
@@ -491,9 +490,6 @@ def maybe_apply_multiple(self) -> FrameOrSeriesUnion | None:
result: Series, DataFrame, or None
Result when self.f is a list-like or dict-like, None otherwise.
"""
- # Note: dict-likes are list-like
- if not is_list_like(self.f):
- return None
return self.obj.aggregate(self.f, self.axis, *self.args, **self.kwargs)
def normalize_dictlike_arg(
@@ -634,9 +630,8 @@ def dtypes(self) -> Series:
def apply(self) -> FrameOrSeriesUnion:
""" compute the results """
# dispatch to agg
- result = self.maybe_apply_multiple()
- if result is not None:
- return result
+ if is_list_like(self.f):
+ return self.apply_multiple()
# all empty
if len(self.columns) == 0 and len(self.index) == 0:
@@ -644,7 +639,7 @@ def apply(self) -> FrameOrSeriesUnion:
# string dispatch
if isinstance(self.f, str):
- return self.maybe_apply_str()
+ return self.apply_str()
# ufunc
elif isinstance(self.f, np.ufunc):
@@ -829,7 +824,7 @@ def wrap_results(self, results: ResType, res_index: Index) -> FrameOrSeriesUnion
return result
- def maybe_apply_str(self) -> FrameOrSeriesUnion:
+ def apply_str(self) -> FrameOrSeriesUnion:
# Caller is responsible for checking isinstance(self.f, str)
# TODO: GH#39993 - Avoid special-casing by replacing with lambda
if self.f == "size":
@@ -837,7 +832,7 @@ def maybe_apply_str(self) -> FrameOrSeriesUnion:
obj = self.obj
value = obj.shape[self.axis]
return obj._constructor_sliced(value, index=self.agg_axis, name="size")
- return super().maybe_apply_str()
+ return super().apply_str()
class FrameRowApply(FrameApply):
@@ -1005,13 +1000,12 @@ def apply(self) -> FrameOrSeriesUnion:
return self.apply_empty_result()
# dispatch to agg
- result = self.maybe_apply_multiple()
- if result is not None:
- return result
+ if is_list_like(self.f):
+ return self.apply_multiple()
if isinstance(self.f, str):
# if we are a string, try to dispatch
- return self.maybe_apply_str()
+ return self.apply_str()
return self.apply_standard()
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
Followup to #41067. cc @jbrockmendel | https://api.github.com/repos/pandas-dev/pandas/pulls/41224 | 2021-04-29T20:33:57Z | 2021-04-30T17:18:46Z | 2021-04-30T17:18:46Z | 2021-04-30T19:04:23Z |
BUG: to_string truncation row with index=False | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 74710ca48308c..6099ab4a9c365 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -796,7 +796,8 @@ I/O
- Bug in :func:`read_sas` raising ``ValueError`` when ``datetimes`` were null (:issue:`39725`)
- Bug in :func:`read_excel` dropping empty values from single-column spreadsheets (:issue:`39808`)
- Bug in :func:`read_excel` raising ``AttributeError`` with ``MultiIndex`` header followed by two empty rows and no index, and bug affecting :func:`read_excel`, :func:`read_csv`, :func:`read_table`, :func:`read_fwf`, and :func:`read_clipboard` where one blank row after a ``MultiIndex`` header with no index would be dropped (:issue:`40442`)
-- Bug in :meth:`DataFrame.to_string` misplacing the truncation column when ``index=False`` (:issue:`40907`)
+- Bug in :meth:`DataFrame.to_string` misplacing the truncation column when ``index=False`` (:issue:`40904`)
+- Bug in :meth:`DataFrame.to_string` adding an extra dot and misaligning the truncation row when ``index=False`` (:issue:`40904`)
- Bug in :func:`read_orc` always raising ``AttributeError`` (:issue:`40918`)
- Bug in the conversion from pyarrow to pandas (e.g. for reading Parquet) with nullable dtypes and a pyarrow array whose data buffer size is not a multiple of dtype size (:issue:`40896`)
diff --git a/pandas/io/formats/string.py b/pandas/io/formats/string.py
index de53646b5f95f..20fc84a4df303 100644
--- a/pandas/io/formats/string.py
+++ b/pandas/io/formats/string.py
@@ -74,11 +74,14 @@ def _insert_dot_separators(self, strcols: List[List[str]]) -> List[List[str]]:
return strcols
+ @property
+ def _adjusted_tr_col_num(self) -> int:
+ return self.fmt.tr_col_num + 1 if self.fmt.index else self.fmt.tr_col_num
+
def _insert_dot_separator_horizontal(
self, strcols: List[List[str]], index_length: int
) -> List[List[str]]:
- tr_col_num = self.fmt.tr_col_num + 1 if self.fmt.index else self.fmt.tr_col_num
- strcols.insert(tr_col_num, [" ..."] * index_length)
+ strcols.insert(self._adjusted_tr_col_num, [" ..."] * index_length)
return strcols
def _insert_dot_separator_vertical(
@@ -90,7 +93,7 @@ def _insert_dot_separator_vertical(
cwidth = self.adj.len(col[row_num])
if self.fmt.is_truncated_horizontally:
- is_dot_col = ix == self.fmt.tr_col_num + 1
+ is_dot_col = ix == self._adjusted_tr_col_num
else:
is_dot_col = False
@@ -99,7 +102,7 @@ def _insert_dot_separator_vertical(
else:
dots = ".."
- if ix == 0:
+ if ix == 0 and self.fmt.index:
dot_mode = "left"
elif is_dot_col:
cwidth = 4
diff --git a/pandas/tests/io/formats/test_to_string.py b/pandas/tests/io/formats/test_to_string.py
index f9b3cac3527ef..65a438ad6108b 100644
--- a/pandas/tests/io/formats/test_to_string.py
+++ b/pandas/tests/io/formats/test_to_string.py
@@ -107,37 +107,51 @@ def test_format_remove_leading_space_dataframe(input_array, expected):
@pytest.mark.parametrize(
- "max_cols, expected",
+ "max_cols, max_rows, expected",
[
(
10,
- [
- " 0 1 2 3 4 ... 6 7 8 9 10",
- " 0 0 0 0 0 ... 0 0 0 0 0",
- " 0 0 0 0 0 ... 0 0 0 0 0",
- ],
+ None,
+ " 0 1 2 3 4 ... 6 7 8 9 10\n"
+ " 0 0 0 0 0 ... 0 0 0 0 0\n"
+ " 0 0 0 0 0 ... 0 0 0 0 0\n"
+ " 0 0 0 0 0 ... 0 0 0 0 0\n"
+ " 0 0 0 0 0 ... 0 0 0 0 0",
+ ),
+ (
+ None,
+ 2,
+ " 0 1 2 3 4 5 6 7 8 9 10\n"
+ " 0 0 0 0 0 0 0 0 0 0 0\n"
+ " .. .. .. .. .. .. .. .. .. .. ..\n"
+ " 0 0 0 0 0 0 0 0 0 0 0",
+ ),
+ (
+ 10,
+ 2,
+ " 0 1 2 3 4 ... 6 7 8 9 10\n"
+ " 0 0 0 0 0 ... 0 0 0 0 0\n"
+ " .. .. .. .. .. ... .. .. .. .. ..\n"
+ " 0 0 0 0 0 ... 0 0 0 0 0",
),
(
9,
- [
- " 0 1 2 3 ... 7 8 9 10",
- " 0 0 0 0 ... 0 0 0 0",
- " 0 0 0 0 ... 0 0 0 0",
- ],
+ 2,
+ " 0 1 2 3 ... 7 8 9 10\n"
+ " 0 0 0 0 ... 0 0 0 0\n"
+ " .. .. .. .. ... .. .. .. ..\n"
+ " 0 0 0 0 ... 0 0 0 0",
),
(
1,
- [
- " 0 ...",
- " 0 ...",
- " 0 ...",
- ],
+ 1,
+ " 0 ...\n 0 ...\n.. ...",
),
],
)
-def test_truncation_col_placement_no_index(max_cols, expected):
- df = DataFrame([[0] * 11] * 2)
- assert df.to_string(index=False, max_cols=max_cols).split("\n") == expected
+def test_truncation_no_index(max_cols, max_rows, expected):
+ df = DataFrame([[0] * 11] * 4)
+ assert df.to_string(index=False, max_cols=max_cols, max_rows=max_rows) == expected
def test_to_string_unicode_columns(float_frame):
| - [x] closes #40904
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
- Already have one for the same bug, not sure if I need one for this.
| https://api.github.com/repos/pandas-dev/pandas/pulls/41223 | 2021-04-29T20:09:15Z | 2021-05-21T15:57:21Z | 2021-05-21T15:57:21Z | 2021-05-21T15:57:25Z |
[ArrowStringArray] startswith/endswith using native pyarrow method | diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 180ed51e7fd2b..4118a172c9dac 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from distutils.version import LooseVersion
+import re
from typing import (
TYPE_CHECKING,
Any,
@@ -763,6 +764,26 @@ def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex=True):
else:
return super()._str_contains(pat, case, flags, na, regex)
+ def _str_startswith(self, pat, na=None):
+ if hasattr(pc, "match_substring_regex"):
+ result = pc.match_substring_regex(self._data, "^" + re.escape(pat))
+ result = BooleanDtype().__from_arrow__(result)
+ if not isna(na):
+ result[isna(result)] = bool(na)
+ return result
+ else:
+ return super()._str_startswith(pat, na)
+
+ def _str_endswith(self, pat, na=None):
+ if hasattr(pc, "match_substring_regex"):
+ result = pc.match_substring_regex(self._data, re.escape(pat) + "$")
+ result = BooleanDtype().__from_arrow__(result)
+ if not isna(na):
+ result[isna(result)] = bool(na)
+ return result
+ else:
+ return super()._str_endswith(pat, na)
+
def _str_isalnum(self):
if hasattr(pc, "utf8_is_alnum"):
result = pc.utf8_is_alnum(self._data)
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index d801d3457027f..0c54042d983ad 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -200,6 +200,25 @@ def test_startswith(dtype, null_value, na):
tm.assert_series_equal(rs, xp)
+@pytest.mark.parametrize("na", [None, True, False])
+def test_startswith_nullable_string_dtype(nullable_string_dtype, na):
+ values = Series(
+ ["om", None, "foo_nom", "nom", "bar_foo", None, "foo", "regex", "rege."],
+ dtype=nullable_string_dtype,
+ )
+ result = values.str.startswith("foo", na=na)
+ exp = Series(
+ [False, na, True, False, False, na, True, False, False], dtype="boolean"
+ )
+ tm.assert_series_equal(result, exp)
+
+ result = values.str.startswith("rege.", na=na)
+ exp = Series(
+ [False, na, False, False, False, na, False, False, True], dtype="boolean"
+ )
+ tm.assert_series_equal(result, exp)
+
+
@pytest.mark.parametrize("dtype", [None, "category"])
@pytest.mark.parametrize("null_value", [None, np.nan, pd.NA])
@pytest.mark.parametrize("na", [True, False])
@@ -228,6 +247,25 @@ def test_endswith(dtype, null_value, na):
tm.assert_series_equal(rs, xp)
+@pytest.mark.parametrize("na", [None, True, False])
+def test_endswith_nullable_string_dtype(nullable_string_dtype, na):
+ values = Series(
+ ["om", None, "foo_nom", "nom", "bar_foo", None, "foo", "regex", "rege."],
+ dtype=nullable_string_dtype,
+ )
+ result = values.str.endswith("foo", na=na)
+ exp = Series(
+ [False, na, False, False, True, na, True, False, False], dtype="boolean"
+ )
+ tm.assert_series_equal(result, exp)
+
+ result = values.str.endswith("rege.", na=na)
+ exp = Series(
+ [False, na, False, False, False, na, False, False, True], dtype="boolean"
+ )
+ tm.assert_series_equal(result, exp)
+
+
def test_replace():
values = Series(["fooBAD__barBAD", np.nan])
| ```
[ 50.00%] ··· strings.Methods.time_startswith ok
[ 50.00%] ··· ============== ==========
dtype
-------------- ----------
str 19.2±0ms
string 16.0±0ms
arrow_string 2.42±0ms
============== ==========
[ 50.00%] ··· strings.Methods.time_endswith ok
[ 50.00%] ··· ============== ==========
dtype
-------------- ----------
str 19.3±0ms
string 15.0±0ms
arrow_string 6.68±0ms
============== ==========
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/41222 | 2021-04-29T19:36:34Z | 2021-04-29T22:08:09Z | 2021-04-29T22:08:08Z | 2021-05-01T08:38:44Z |
[ArrowStringArray] use pyarrow string trimming functions if available | diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 180ed51e7fd2b..5d505691b13d2 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -831,3 +831,30 @@ def _str_lower(self):
def _str_upper(self):
return type(self)(pc.utf8_upper(self._data))
+
+ def _str_strip(self, to_strip=None):
+ if to_strip is None:
+ if hasattr(pc, "utf8_trim_whitespace"):
+ return type(self)(pc.utf8_trim_whitespace(self._data))
+ else:
+ if hasattr(pc, "utf8_trim"):
+ return type(self)(pc.utf8_trim(self._data, characters=to_strip))
+ return super()._str_strip(to_strip)
+
+ def _str_lstrip(self, to_strip=None):
+ if to_strip is None:
+ if hasattr(pc, "utf8_ltrim_whitespace"):
+ return type(self)(pc.utf8_ltrim_whitespace(self._data))
+ else:
+ if hasattr(pc, "utf8_ltrim"):
+ return type(self)(pc.utf8_ltrim(self._data, characters=to_strip))
+ return super()._str_lstrip(to_strip)
+
+ def _str_rstrip(self, to_strip=None):
+ if to_strip is None:
+ if hasattr(pc, "utf8_rtrim_whitespace"):
+ return type(self)(pc.utf8_rtrim_whitespace(self._data))
+ else:
+ if hasattr(pc, "utf8_rtrim"):
+ return type(self)(pc.utf8_rtrim(self._data, characters=to_strip))
+ return super()._str_rstrip(to_strip)
diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py
index 2a52b3ba3f9e1..f218d5333b415 100644
--- a/pandas/tests/strings/test_strings.py
+++ b/pandas/tests/strings/test_strings.py
@@ -570,19 +570,19 @@ def test_slice_replace():
tm.assert_series_equal(result, exp)
-def test_strip_lstrip_rstrip():
- values = Series([" aa ", " bb \n", np.nan, "cc "])
+def test_strip_lstrip_rstrip(any_string_dtype):
+ values = Series([" aa ", " bb \n", np.nan, "cc "], dtype=any_string_dtype)
result = values.str.strip()
- exp = Series(["aa", "bb", np.nan, "cc"])
+ exp = Series(["aa", "bb", np.nan, "cc"], dtype=any_string_dtype)
tm.assert_series_equal(result, exp)
result = values.str.lstrip()
- exp = Series(["aa ", "bb \n", np.nan, "cc "])
+ exp = Series(["aa ", "bb \n", np.nan, "cc "], dtype=any_string_dtype)
tm.assert_series_equal(result, exp)
result = values.str.rstrip()
- exp = Series([" aa", " bb", np.nan, "cc"])
+ exp = Series([" aa", " bb", np.nan, "cc"], dtype=any_string_dtype)
tm.assert_series_equal(result, exp)
@@ -609,19 +609,19 @@ def test_strip_lstrip_rstrip_mixed():
tm.assert_almost_equal(rs, xp)
-def test_strip_lstrip_rstrip_args():
- values = Series(["xxABCxx", "xx BNSD", "LDFJH xx"])
+def test_strip_lstrip_rstrip_args(any_string_dtype):
+ values = Series(["xxABCxx", "xx BNSD", "LDFJH xx"], dtype=any_string_dtype)
rs = values.str.strip("x")
- xp = Series(["ABC", " BNSD", "LDFJH "])
+ xp = Series(["ABC", " BNSD", "LDFJH "], dtype=any_string_dtype)
tm.assert_series_equal(rs, xp)
rs = values.str.lstrip("x")
- xp = Series(["ABCxx", " BNSD", "LDFJH xx"])
+ xp = Series(["ABCxx", " BNSD", "LDFJH xx"], dtype=any_string_dtype)
tm.assert_series_equal(rs, xp)
rs = values.str.rstrip("x")
- xp = Series(["xxABC", "xx BNSD", "LDFJH "])
+ xp = Series(["xxABC", "xx BNSD", "LDFJH "], dtype=any_string_dtype)
tm.assert_series_equal(rs, xp)
| ```
[ 27.78%] ··· strings.Methods.time_lstrip ok
[ 27.78%] ··· ============== ==========
dtype
-------------- ----------
str 22.7±0ms
string 16.4±0ms
arrow_string 1.71±0ms
============== ==========
[ 38.89%] ··· strings.Methods.time_rstrip ok
[ 38.89%] ··· ============== ==========
dtype
-------------- ----------
str 19.7±0ms
string 13.9±0ms
arrow_string 1.71±0ms
============== ==========
[ 43.06%] ··· strings.Methods.time_strip ok
[ 43.06%] ··· ============== ==========
dtype
-------------- ----------
str 18.9±0ms
string 14.6±0ms
arrow_string 1.64±0ms
============== ==========
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/41219 | 2021-04-29T18:10:46Z | 2021-04-29T22:10:13Z | 2021-04-29T22:10:13Z | 2021-04-30T09:20:49Z |
Optimising Series.nunique for Nan values #40865 | diff --git a/pandas/core/base.py b/pandas/core/base.py
index 5945d8a4b432d..4469da430da36 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -1305,10 +1305,10 @@ def nunique(self, dropna: bool = True) -> int:
4
"""
uniqs = self.unique()
- n = len(uniqs)
- if dropna and isna(uniqs).any():
- n -= 1
- return n
+ if dropna:
+ return (~isna(uniqs)).sum()
+ else:
+ return len(uniqs)
@property
def is_unique(self) -> bool:
| - [ ] closes #40865
| https://api.github.com/repos/pandas-dev/pandas/pulls/41218 | 2021-04-29T15:40:51Z | 2021-04-29T16:00:58Z | null | 2021-04-29T16:01:12Z |
[ArrowStringArray] use pyarrow.compute.match_substring_regex if available | diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index fabb3974728de..72a2ab8a1b80a 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -8,6 +8,7 @@
Sequence,
cast,
)
+import warnings
import numpy as np
@@ -766,16 +767,34 @@ def _str_map(self, f, na_value=None, dtype: Dtype | None = None):
return lib.map_infer_mask(arr, f, mask.view("uint8"))
def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex=True):
- if not regex and case:
- result = pc.match_substring(self._data, pat)
- result = BooleanDtype().__from_arrow__(result)
- if not isna(na):
- result[isna(result)] = bool(na)
- return result
- else:
+ if flags:
return super()._str_contains(pat, case, flags, na, regex)
+ if regex:
+ # match_substring_regex added in pyarrow 4.0.0
+ if hasattr(pc, "match_substring_regex") and case:
+ if re.compile(pat).groups:
+ warnings.warn(
+ "This pattern has match groups. To actually get the "
+ "groups, use str.extract.",
+ UserWarning,
+ stacklevel=3,
+ )
+ result = pc.match_substring_regex(self._data, pat)
+ else:
+ return super()._str_contains(pat, case, flags, na, regex)
+ else:
+ if case:
+ result = pc.match_substring(self._data, pat)
+ else:
+ result = pc.match_substring(pc.utf8_upper(self._data), pat.upper())
+ result = BooleanDtype().__from_arrow__(result)
+ if not isna(na):
+ result[isna(result)] = bool(na)
+ return result
+
def _str_startswith(self, pat, na=None):
+ # match_substring_regex added in pyarrow 4.0.0
if hasattr(pc, "match_substring_regex"):
result = pc.match_substring_regex(self._data, "^" + re.escape(pat))
result = BooleanDtype().__from_arrow__(result)
@@ -786,6 +805,7 @@ def _str_startswith(self, pat, na=None):
return super()._str_startswith(pat, na)
def _str_endswith(self, pat, na=None):
+ # match_substring_regex added in pyarrow 4.0.0
if hasattr(pc, "match_substring_regex"):
result = pc.match_substring_regex(self._data, re.escape(pat) + "$")
result = BooleanDtype().__from_arrow__(result)
| follow-up to #41025
```
[ 50.00%] ··· strings.Contains.time_contains ok
[ 50.00%] ··· ============== ========== ==========
-- regex
-------------- ---------------------
dtype True False
============== ========== ==========
str 22.0±0ms 15.0±0ms
string 17.2±0ms 10.9±0ms
arrow_string 6.84±0ms 2.37±0ms
============== ========== ==========
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/41217 | 2021-04-29T11:41:24Z | 2021-05-02T23:53:32Z | 2021-05-02T23:53:32Z | 2021-05-03T07:04:51Z |
REF: dont catch ValueError in aggregate_item_by_item | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 1a8329d77f61e..c8b55f90b6b2c 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1207,26 +1207,13 @@ def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame:
obj = self._obj_with_exclusions
result: dict[int | str, NDFrame] = {}
- cannot_agg = []
for item in obj:
data = obj[item]
colg = SeriesGroupBy(data, selection=item, grouper=self.grouper)
- try:
- result[item] = colg.aggregate(func, *args, **kwargs)
-
- except ValueError as err:
- if "Must produce aggregated value" in str(err):
- # raised in _aggregate_named, handle at higher level
- # see test_apply_with_mutated_index
- raise
- # otherwise we get here from an AttributeError in _make_wrapper
- cannot_agg.append(item)
- continue
+ result[item] = colg.aggregate(func, *args, **kwargs)
result_columns = obj.columns
- if cannot_agg:
- result_columns = result_columns.drop(cannot_agg)
return self.obj._constructor(result, columns=result_columns)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41211 | 2021-04-29T05:06:16Z | 2021-04-29T23:33:43Z | 2021-04-29T23:33:43Z | 2021-04-30T00:53:54Z |
REF: De-duplicate agg_series | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 1a8329d77f61e..4f618940cf9b2 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1686,7 +1686,7 @@ def _insert_inaxis_grouper_inplace(self, result: DataFrame) -> None:
def _wrap_aggregated_output(
self,
- output: Mapping[base.OutputKey, Series | np.ndarray],
+ output: Mapping[base.OutputKey, Series | ArrayLike],
) -> DataFrame:
"""
Wraps the output of DataFrameGroupBy aggregations into the expected result.
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index ce7f0de616e18..2436391580dcb 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1056,7 +1056,7 @@ def _set_result_index_ordered(
return result
- def _wrap_aggregated_output(self, output: Mapping[base.OutputKey, np.ndarray]):
+ def _wrap_aggregated_output(self, output: Mapping[base.OutputKey, ArrayLike]):
raise AbstractMethodError(self)
def _wrap_transformed_output(self, output: Mapping[base.OutputKey, ArrayLike]):
@@ -1222,7 +1222,7 @@ def _python_agg_general(self, func, *args, **kwargs):
f = lambda x: func(x, *args, **kwargs)
# iterate through "columns" ex exclusions to populate output dict
- output: dict[base.OutputKey, np.ndarray] = {}
+ output: dict[base.OutputKey, ArrayLike] = {}
for idx, obj in enumerate(self._iterate_slices()):
name = obj.name
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 1dcb2b97476a3..96f5b2cfb9d81 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -923,7 +923,8 @@ def _cython_operation(
**kwargs,
)
- def agg_series(self, obj: Series, func: F):
+ @final
+ def agg_series(self, obj: Series, func: F) -> tuple[ArrayLike, np.ndarray]:
# Caller is responsible for checking ngroups != 0
assert self.ngroups != 0
@@ -952,8 +953,9 @@ def agg_series(self, obj: Series, func: F):
raise
return self._aggregate_series_pure_python(obj, func)
- @final
- def _aggregate_series_fast(self, obj: Series, func: F):
+ def _aggregate_series_fast(
+ self, obj: Series, func: F
+ ) -> tuple[ArrayLike, np.ndarray]:
# At this point we have already checked that
# - obj.index is not a MultiIndex
# - obj is backed by an ndarray, not ExtensionArray
@@ -1157,18 +1159,14 @@ def groupings(self) -> list[grouper.Grouping]:
for lvl, name in zip(self.levels, self.names)
]
- def agg_series(self, obj: Series, func: F):
- # Caller is responsible for checking ngroups != 0
- assert self.ngroups != 0
- assert len(self.bins) > 0 # otherwise we'd get IndexError in get_result
-
- if is_extension_array_dtype(obj.dtype):
- # preempt SeriesBinGrouper from raising TypeError
- return self._aggregate_series_pure_python(obj, func)
-
- elif obj.index._has_complex_internals:
- return self._aggregate_series_pure_python(obj, func)
-
+ def _aggregate_series_fast(
+ self, obj: Series, func: F
+ ) -> tuple[ArrayLike, np.ndarray]:
+ # At this point we have already checked that
+ # - obj.index is not a MultiIndex
+ # - obj is backed by an ndarray, not ExtensionArray
+ # - ngroups != 0
+ # - len(self.bins) > 0
grouper = libreduction.SeriesBinGrouper(obj, func, self.bins)
return grouper.get_result()
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41210 | 2021-04-29T05:03:29Z | 2021-04-29T23:32:18Z | 2021-04-29T23:32:18Z | 2021-04-30T03:01:17Z |
DOC: Fix link and typo | diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst
index b9afbe387799e..f4a09e0daa750 100644
--- a/doc/source/development/contributing.rst
+++ b/doc/source/development/contributing.rst
@@ -110,8 +110,8 @@ version control to allow many people to work together on the project.
Some great resources for learning Git:
* the `GitHub help pages <https://help.github.com/>`_.
-* the `NumPy's documentation <https://numpy.org/doc/stable/dev/index.html>`_.
-* Matthew Brett's `Pydagogue <https://matthew-brett.github.com/pydagogue/>`_.
+* the `NumPy documentation <https://numpy.org/doc/stable/dev/index.html>`_.
+* Matthew Brett's `Pydagogue <https://matthew-brett.github.io/pydagogue/>`_.
Getting started with Git
------------------------
| https://api.github.com/repos/pandas-dev/pandas/pulls/41209 | 2021-04-28T22:29:55Z | 2021-04-30T00:40:21Z | 2021-04-30T00:40:20Z | 2021-04-30T07:00:28Z | |
DEPS/CLN: remove distutils usage | diff --git a/LICENSES/PACKAGING_LICENSE b/LICENSES/PACKAGING_LICENSE
new file mode 100644
index 0000000000000..4216ea1ce2379
--- /dev/null
+++ b/LICENSES/PACKAGING_LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+
+Copyright (c) Donald Stufft and individual contributors.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx
index bd749d6eca18e..cbe79d11fbfc9 100644
--- a/pandas/_libs/missing.pyx
+++ b/pandas/_libs/missing.pyx
@@ -1,5 +1,6 @@
from decimal import Decimal
import numbers
+from sys import maxsize
import cython
from cython import Py_ssize_t
@@ -27,7 +28,6 @@ from pandas._libs.tslibs.np_datetime cimport (
)
from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op
-from pandas.compat import IS64
cdef:
float64_t INF = <float64_t>np.inf
@@ -35,7 +35,7 @@ cdef:
int64_t NPY_NAT = util.get_nat()
- bint is_32bit = not IS64
+ bint is_32bit = maxsize <= 2 ** 32
type cDecimal = Decimal # for faster isinstance checks
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index cf00618a7b2b9..0ef6da53191c5 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -1,11 +1,12 @@
from __future__ import annotations
-import distutils.version
import importlib
import sys
import types
import warnings
+from pandas.util.version import Version
+
# Update install.rst when updating versions!
VERSIONS = {
@@ -128,7 +129,7 @@ def import_optional_dependency(
minimum_version = min_version if min_version is not None else VERSIONS.get(parent)
if minimum_version:
version = get_version(module_to_get)
- if distutils.version.LooseVersion(version) < minimum_version:
+ if Version(version) < Version(minimum_version):
msg = (
f"Pandas requires version '{minimum_version}' or newer of '{parent}' "
f"(version '{version}' currently installed)."
diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py
index 4812a0ecba919..619713f28ee2d 100644
--- a/pandas/compat/numpy/__init__.py
+++ b/pandas/compat/numpy/__init__.py
@@ -1,21 +1,22 @@
""" support numpy compatibility across versions """
-from distutils.version import LooseVersion
import re
import numpy as np
+from pandas.util.version import Version
+
# numpy versioning
_np_version = np.__version__
-_nlv = LooseVersion(_np_version)
-np_version_under1p18 = _nlv < LooseVersion("1.18")
-np_version_under1p19 = _nlv < LooseVersion("1.19")
-np_version_under1p20 = _nlv < LooseVersion("1.20")
-is_numpy_dev = ".dev" in str(_nlv)
+_nlv = Version(_np_version)
+np_version_under1p18 = _nlv < Version("1.18")
+np_version_under1p19 = _nlv < Version("1.19")
+np_version_under1p20 = _nlv < Version("1.20")
+is_numpy_dev = _nlv.dev is not None
_min_numpy_ver = "1.17.3"
-if _nlv < _min_numpy_ver:
+if _nlv < Version(_min_numpy_ver):
raise ImportError(
f"this version of pandas is incompatible with numpy < {_min_numpy_ver}\n"
f"your numpy version is {_np_version}.\n"
diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py
index 3f56ecd640774..63ea5554e32d7 100644
--- a/pandas/compat/numpy/function.py
+++ b/pandas/compat/numpy/function.py
@@ -15,7 +15,6 @@
methods that are spread throughout the codebase. This module will make it
easier to adjust to future upstream changes in the analogous numpy signatures.
"""
-from distutils.version import LooseVersion
from typing import (
Any,
Dict,
@@ -39,6 +38,8 @@
validate_kwargs,
)
+from pandas.util.version import Version
+
class CompatValidator:
def __init__(
@@ -128,7 +129,7 @@ def validate_argmax_with_skipna(skipna, args, kwargs):
ARGSORT_DEFAULTS["kind"] = "quicksort"
ARGSORT_DEFAULTS["order"] = None
-if LooseVersion(__version__) >= LooseVersion("1.17.0"):
+if Version(__version__) >= Version("1.17.0"):
# GH-26361. NumPy added radix sort and changed default to None.
ARGSORT_DEFAULTS["kind"] = None
diff --git a/pandas/compat/pyarrow.py b/pandas/compat/pyarrow.py
index e9ca9b99d4380..cc5c7a2e51976 100644
--- a/pandas/compat/pyarrow.py
+++ b/pandas/compat/pyarrow.py
@@ -1,16 +1,16 @@
""" support pyarrow compatibility across versions """
-from distutils.version import LooseVersion
+from pandas.util.version import Version
try:
import pyarrow as pa
_pa_version = pa.__version__
- _palv = LooseVersion(_pa_version)
- pa_version_under1p0 = _palv < LooseVersion("1.0.0")
- pa_version_under2p0 = _palv < LooseVersion("2.0.0")
- pa_version_under3p0 = _palv < LooseVersion("3.0.0")
- pa_version_under4p0 = _palv < LooseVersion("4.0.0")
+ _palv = Version(_pa_version)
+ pa_version_under1p0 = _palv < Version("1.0.0")
+ pa_version_under2p0 = _palv < Version("2.0.0")
+ pa_version_under3p0 = _palv < Version("3.0.0")
+ pa_version_under4p0 = _palv < Version("4.0.0")
except ImportError:
pa_version_under1p0 = True
pa_version_under2p0 = True
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index a1278a129c40f..87625015d83a2 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-from distutils.version import LooseVersion
import re
from typing import (
TYPE_CHECKING,
@@ -53,6 +52,7 @@
validate_indices,
)
from pandas.core.strings.object_array import ObjectStringArrayMixin
+from pandas.util.version import Version
try:
import pyarrow as pa
@@ -62,7 +62,7 @@
# PyArrow backed StringArrays are available starting at 1.0.0, but this
# file is imported from even if pyarrow is < 1.0.0, before pyarrow.compute
# and its compute functions existed. GH38801
- if LooseVersion(pa.__version__) >= "1.0.0":
+ if Version(pa.__version__) >= Version("1.0.0"):
import pyarrow.compute as pc
ARROW_CMP_FUNCS = {
@@ -232,7 +232,7 @@ def __init__(self, values):
def _chk_pyarrow_available(cls) -> None:
# TODO: maybe update import_optional_dependency to allow a minimum
# version to be specified rather than use the global minimum
- if pa is None or LooseVersion(pa.__version__) < "1.0.0":
+ if pa is None or Version(pa.__version__) < Version("1.0.0"):
msg = "pyarrow>=1.0.0 is required for PyArrow backed StringArray."
raise ImportError(msg)
diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py
index 223c4139f2b7c..231beb40e9630 100644
--- a/pandas/core/computation/ops.py
+++ b/pandas/core/computation/ops.py
@@ -5,7 +5,6 @@
from __future__ import annotations
from datetime import datetime
-from distutils.version import LooseVersion
from functools import partial
import operator
from typing import (
@@ -28,6 +27,7 @@
result_type_many,
)
from pandas.core.computation.scope import DEFAULT_GLOBALS
+from pandas.util.version import Version
from pandas.io.formats.printing import (
pprint_thing,
@@ -623,7 +623,7 @@ def __init__(self, name: str):
if name not in MATHOPS or (
NUMEXPR_INSTALLED
- and NUMEXPR_VERSION < LooseVersion("2.6.9")
+ and Version(NUMEXPR_VERSION) < Version("2.6.9")
and name in ("floor", "ceil")
):
raise ValueError(f'"{name}" is not a supported function')
diff --git a/pandas/core/util/numba_.py b/pandas/core/util/numba_.py
index 3da6a5cbf7326..8a2e24b25268c 100644
--- a/pandas/core/util/numba_.py
+++ b/pandas/core/util/numba_.py
@@ -1,5 +1,4 @@
"""Common utilities for Numba operations"""
-from distutils.version import LooseVersion
import types
from typing import (
Callable,
@@ -13,6 +12,8 @@
from pandas.compat._optional import import_optional_dependency
from pandas.errors import NumbaUtilError
+from pandas.util.version import Version
+
GLOBAL_USE_NUMBA: bool = False
NUMBA_FUNC_CACHE: Dict[Tuple[Callable, str], Callable] = {}
@@ -89,7 +90,7 @@ def jit_user_function(
"""
numba = import_optional_dependency("numba")
- if LooseVersion(numba.__version__) >= LooseVersion("0.49.0"):
+ if Version(numba.__version__) >= Version("0.49.0"):
is_jitted = numba.extending.is_jitted(func)
else:
is_jitted = isinstance(func, numba.targets.registry.CPUDispatcher)
diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py
index e9c20ff42f51b..c1c9865e6721d 100644
--- a/pandas/io/clipboard/__init__.py
+++ b/pandas/io/clipboard/__init__.py
@@ -51,9 +51,9 @@
get_errno,
sizeof,
)
-import distutils.spawn
import os
import platform
+from shutil import which
import subprocess
import time
import warnings
@@ -528,7 +528,7 @@ def determine_clipboard():
return init_windows_clipboard()
if platform.system() == "Linux":
- if distutils.spawn.find_executable("wslconfig.exe"):
+ if which("wslconfig.exe"):
return init_wsl_clipboard()
# Setup for the MAC OS X platform:
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index d26a991ba2820..4b81b69976c62 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -2,7 +2,6 @@
import abc
import datetime
-from distutils.version import LooseVersion
import inspect
from io import BytesIO
import os
@@ -44,6 +43,7 @@
from pandas.core.frame import DataFrame
from pandas.core.shared_docs import _shared_docs
+from pandas.util.version import Version
from pandas.io.common import (
IOHandles,
@@ -1163,7 +1163,7 @@ def __init__(
else:
import xlrd
- xlrd_version = LooseVersion(get_version(xlrd))
+ xlrd_version = Version(get_version(xlrd))
ext = None
if engine is None:
@@ -1190,7 +1190,7 @@ def __init__(
path_or_buffer, storage_options=storage_options
)
- if ext != "xls" and xlrd_version >= "2":
+ if ext != "xls" and xlrd_version >= Version("2"):
raise ValueError(
f"Your version of xlrd is {xlrd_version}. In xlrd >= 2.0, "
f"only the xls format is supported. Install openpyxl instead."
diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py
index 3801a29fec39e..5ad014a334c27 100644
--- a/pandas/io/parquet.py
+++ b/pandas/io/parquet.py
@@ -1,7 +1,6 @@
""" parquet compat """
from __future__ import annotations
-from distutils.version import LooseVersion
import io
import os
from typing import (
@@ -24,6 +23,7 @@
get_option,
)
from pandas.core import generic
+from pandas.util.version import Version
from pandas.io.common import (
IOHandles,
@@ -210,7 +210,7 @@ def read(
to_pandas_kwargs = {}
if use_nullable_dtypes:
- if LooseVersion(self.api.__version__) >= "0.16":
+ if Version(self.api.__version__) >= Version("0.16"):
import pandas as pd
mapping = {
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 04a7ccb538a67..a347e7a99be8b 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -11,7 +11,6 @@
datetime,
time,
)
-from distutils.version import LooseVersion
from functools import partial
import re
from typing import (
@@ -45,6 +44,7 @@
)
from pandas.core.base import PandasObject
from pandas.core.tools.datetimes import to_datetime
+from pandas.util.version import Version
class SQLAlchemyRequired(ImportError):
@@ -86,7 +86,7 @@ def _gt14() -> bool:
"""
import sqlalchemy
- return LooseVersion(sqlalchemy.__version__) >= LooseVersion("1.4.0")
+ return Version(sqlalchemy.__version__) >= Version("1.4.0")
def _convert_params(sql, params):
diff --git a/pandas/plotting/_matplotlib/compat.py b/pandas/plotting/_matplotlib/compat.py
index 729d2bf1f019a..70ddd1ca09c7e 100644
--- a/pandas/plotting/_matplotlib/compat.py
+++ b/pandas/plotting/_matplotlib/compat.py
@@ -1,7 +1,8 @@
# being a bit too dynamic
-from distutils.version import LooseVersion
import operator
+from pandas.util.version import Version
+
def _mpl_version(version, op):
def inner():
@@ -10,7 +11,7 @@ def inner():
except ImportError:
return False
return (
- op(LooseVersion(mpl.__version__), LooseVersion(version))
+ op(Version(mpl.__version__), Version(version))
and str(mpl.__version__)[0] != "0"
)
diff --git a/pandas/tests/arrays/interval/test_interval.py b/pandas/tests/arrays/interval/test_interval.py
index fde45a1e39bb2..6ae3f75069899 100644
--- a/pandas/tests/arrays/interval/test_interval.py
+++ b/pandas/tests/arrays/interval/test_interval.py
@@ -165,7 +165,7 @@ def test_repr():
# Arrow interaction
-pyarrow_skip = td.skip_if_no("pyarrow", min_version="0.15.1.dev")
+pyarrow_skip = td.skip_if_no("pyarrow", min_version="0.16.0")
@pyarrow_skip
diff --git a/pandas/tests/arrays/masked/test_arrow_compat.py b/pandas/tests/arrays/masked/test_arrow_compat.py
index d64dd6fa24d2c..e06b8749fbf11 100644
--- a/pandas/tests/arrays/masked/test_arrow_compat.py
+++ b/pandas/tests/arrays/masked/test_arrow_compat.py
@@ -43,7 +43,7 @@ def test_arrow_roundtrip(data):
tm.assert_frame_equal(result, df)
-@td.skip_if_no("pyarrow", min_version="0.15.1.dev")
+@td.skip_if_no("pyarrow", min_version="0.16.0")
def test_arrow_load_from_zero_chunks(data):
# GH-41040
diff --git a/pandas/tests/arrays/period/test_arrow_compat.py b/pandas/tests/arrays/period/test_arrow_compat.py
index 398972a682504..d7b0704cdfb05 100644
--- a/pandas/tests/arrays/period/test_arrow_compat.py
+++ b/pandas/tests/arrays/period/test_arrow_compat.py
@@ -11,7 +11,7 @@
period_array,
)
-pyarrow_skip = pyarrow_skip = td.skip_if_no("pyarrow", min_version="0.15.1.dev")
+pyarrow_skip = pyarrow_skip = td.skip_if_no("pyarrow", min_version="0.16.0")
@pyarrow_skip
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index 43ba5667d4d93..17d05ebeb0fc5 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -460,7 +460,7 @@ def test_arrow_array(dtype):
assert arr.equals(expected)
-@td.skip_if_no("pyarrow", min_version="0.15.1.dev")
+@td.skip_if_no("pyarrow", min_version="0.16.0")
def test_arrow_roundtrip(dtype, dtype_object):
# roundtrip possible from arrow 1.0.0
import pyarrow as pa
@@ -476,7 +476,7 @@ def test_arrow_roundtrip(dtype, dtype_object):
assert result.loc[2, "a"] is pd.NA
-@td.skip_if_no("pyarrow", min_version="0.15.1.dev")
+@td.skip_if_no("pyarrow", min_version="0.16.0")
def test_arrow_load_from_zero_chunks(dtype, dtype_object):
# GH-41040
import pyarrow as pa
diff --git a/pandas/tests/computation/test_compat.py b/pandas/tests/computation/test_compat.py
index 8fa11ab75dd67..6d6aa08204c3f 100644
--- a/pandas/tests/computation/test_compat.py
+++ b/pandas/tests/computation/test_compat.py
@@ -1,5 +1,3 @@
-from distutils.version import LooseVersion
-
import pytest
from pandas.compat._optional import VERSIONS
@@ -7,6 +5,7 @@
import pandas as pd
from pandas.core.computation.engines import ENGINES
import pandas.core.computation.expr as expr
+from pandas.util.version import Version
def test_compat():
@@ -18,7 +17,7 @@ def test_compat():
import numexpr as ne
ver = ne.__version__
- if LooseVersion(ver) < LooseVersion(VERSIONS["numexpr"]):
+ if Version(ver) < Version(VERSIONS["numexpr"]):
assert not NUMEXPR_INSTALLED
else:
assert NUMEXPR_INSTALLED
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py
index eb2ed2c25d27c..9ee53a9d7c54d 100644
--- a/pandas/tests/computation/test_eval.py
+++ b/pandas/tests/computation/test_eval.py
@@ -1,4 +1,3 @@
-from distutils.version import LooseVersion
from functools import reduce
from itertools import product
import operator
@@ -52,6 +51,7 @@
_binary_ops_dict,
_unary_math_ops,
)
+from pandas.util.version import Version
@pytest.fixture(
@@ -78,14 +78,14 @@ def parser(request):
@pytest.fixture
def ne_lt_2_6_9():
- if NUMEXPR_INSTALLED and NUMEXPR_VERSION >= LooseVersion("2.6.9"):
+ if NUMEXPR_INSTALLED and Version(NUMEXPR_VERSION) >= Version("2.6.9"):
pytest.skip("numexpr is >= 2.6.9")
return "numexpr"
def _get_unary_fns_for_ne():
if NUMEXPR_INSTALLED:
- if NUMEXPR_VERSION >= LooseVersion("2.6.9"):
+ if Version(NUMEXPR_VERSION) >= Version("2.6.9"):
return list(_unary_math_ops)
else:
return [x for x in _unary_math_ops if x not in ["floor", "ceil"]]
diff --git a/pandas/tests/generic/test_to_xarray.py b/pandas/tests/generic/test_to_xarray.py
index 8e33465efcbf7..556ae8baafd11 100644
--- a/pandas/tests/generic/test_to_xarray.py
+++ b/pandas/tests/generic/test_to_xarray.py
@@ -13,6 +13,7 @@
import pandas._testing as tm
+@td.skip_if_no("xarray")
class TestDataFrameToXArray:
@pytest.fixture
def df(self):
@@ -29,7 +30,6 @@ def df(self):
}
)
- @td.skip_if_no("xarray", "0.10.0")
def test_to_xarray_index_types(self, index, df):
if isinstance(index, MultiIndex):
pytest.skip("MultiIndex is tested separately")
@@ -56,7 +56,6 @@ def test_to_xarray_index_types(self, index, df):
expected.columns.name = None
tm.assert_frame_equal(result.to_dataframe(), expected)
- @td.skip_if_no("xarray", min_version="0.7.0")
def test_to_xarray_empty(self, df):
from xarray import Dataset
@@ -65,11 +64,9 @@ def test_to_xarray_empty(self, df):
assert result.dims["foo"] == 0
assert isinstance(result, Dataset)
- @td.skip_if_no("xarray", min_version="0.7.0")
def test_to_xarray_with_multiindex(self, df):
from xarray import Dataset
- # available in 0.7.1
# MultiIndex
df.index = MultiIndex.from_product([["a"], range(3)], names=["one", "two"])
result = df.to_xarray()
@@ -87,8 +84,8 @@ def test_to_xarray_with_multiindex(self, df):
tm.assert_frame_equal(result, expected)
+@td.skip_if_no("xarray")
class TestSeriesToXArray:
- @td.skip_if_no("xarray", "0.10.0")
def test_to_xarray_index_types(self, index):
if isinstance(index, MultiIndex):
pytest.skip("MultiIndex is tested separately")
@@ -107,7 +104,6 @@ def test_to_xarray_index_types(self, index):
# idempotency
tm.assert_series_equal(result.to_series(), ser)
- @td.skip_if_no("xarray", min_version="0.7.0")
def test_to_xarray_empty(self):
from xarray import DataArray
@@ -119,7 +115,6 @@ def test_to_xarray_empty(self):
tm.assert_almost_equal(list(result.coords.keys()), ["foo"])
assert isinstance(result, DataArray)
- @td.skip_if_no("xarray", min_version="0.7.0")
def test_to_xarray_with_multiindex(self):
from xarray import DataArray
diff --git a/pandas/tests/io/excel/__init__.py b/pandas/tests/io/excel/__init__.py
index e1de03e1f306c..c4343497ded48 100644
--- a/pandas/tests/io/excel/__init__.py
+++ b/pandas/tests/io/excel/__init__.py
@@ -1,5 +1,3 @@
-from distutils.version import LooseVersion
-
import pytest
from pandas.compat._optional import (
@@ -7,6 +5,8 @@
import_optional_dependency,
)
+from pandas.util.version import Version
+
pytestmark = [
pytest.mark.filterwarnings(
# Looks like tree.getiterator is deprecated in favor of tree.iter
@@ -32,4 +32,4 @@
else:
import xlrd
- xlrd_version = LooseVersion(get_version(xlrd))
+ xlrd_version = Version(get_version(xlrd))
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index c4b3221e1d3a7..8114ac049bdb9 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -21,6 +21,7 @@
)
import pandas._testing as tm
from pandas.tests.io.excel import xlrd_version
+from pandas.util.version import Version
read_ext_params = [".xls", ".xlsx", ".xlsm", ".xlsb", ".ods"]
engine_params = [
@@ -70,7 +71,7 @@ def _is_valid_engine_ext_pair(engine, read_ext: str) -> bool:
if (
engine == "xlrd"
and xlrd_version is not None
- and xlrd_version >= "2"
+ and xlrd_version >= Version("2")
and read_ext != ".xls"
):
return False
@@ -1404,7 +1405,7 @@ def test_excel_read_binary_via_read_excel(self, read_ext, engine):
tm.assert_frame_equal(result, expected)
@pytest.mark.skipif(
- xlrd_version is not None and xlrd_version >= "2",
+ xlrd_version is not None and xlrd_version >= Version("2"),
reason="xlrd no longer supports xlsx",
)
def test_excel_high_surrogate(self, engine):
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
index c0d8acf8ab562..bf0a0de442ae1 100644
--- a/pandas/tests/io/excel/test_xlrd.py
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -5,6 +5,7 @@
import pandas as pd
import pandas._testing as tm
from pandas.tests.io.excel import xlrd_version
+from pandas.util.version import Version
from pandas.io.excel import ExcelFile
@@ -18,7 +19,7 @@ def skip_ods_and_xlsb_files(read_ext):
pytest.skip("Not valid for xlrd")
if read_ext == ".xlsb":
pytest.skip("Not valid for xlrd")
- if read_ext in (".xlsx", ".xlsm") and xlrd_version >= "2":
+ if read_ext in (".xlsx", ".xlsm") and xlrd_version >= Version("2"):
pytest.skip("Not valid for xlrd >= 2.0")
@@ -61,7 +62,7 @@ def test_read_excel_warning_with_xlsx_file(datapath):
path = datapath("io", "data", "excel", "test1.xlsx")
has_openpyxl = import_optional_dependency("openpyxl", errors="ignore") is not None
if not has_openpyxl:
- if xlrd_version >= "2":
+ if xlrd_version >= Version("2"):
with pytest.raises(
ValueError,
match="Your version of xlrd is ",
diff --git a/pandas/tests/io/generate_legacy_storage_files.py b/pandas/tests/io/generate_legacy_storage_files.py
index f33299a1b14de..601b50fb469cb 100644
--- a/pandas/tests/io/generate_legacy_storage_files.py
+++ b/pandas/tests/io/generate_legacy_storage_files.py
@@ -33,7 +33,6 @@
"""
from datetime import timedelta
-from distutils.version import LooseVersion
import os
import pickle
import platform as pl
@@ -54,9 +53,11 @@
Timestamp,
bdate_range,
date_range,
+ interval_range,
period_range,
timedelta_range,
)
+from pandas.arrays import SparseArray
from pandas.tseries.offsets import (
FY5253,
@@ -81,15 +82,6 @@
YearEnd,
)
-try:
- # TODO: remove try/except when 0.24.0 is the legacy version.
- from pandas.arrays import SparseArray
-except ImportError:
- from pandas.core.sparse.api import SparseArray
-
-
-_loose_version = LooseVersion(pandas.__version__)
-
def _create_sp_series():
nan = np.nan
@@ -155,10 +147,7 @@ def create_data():
index["range"] = RangeIndex(10)
- if _loose_version >= LooseVersion("0.21"):
- from pandas import interval_range
-
- index["interval"] = interval_range(0, periods=10)
+ index["interval"] = interval_range(0, periods=10)
mi = {
"reg2": MultiIndex.from_tuples(
diff --git a/pandas/tests/io/pytables/test_select.py b/pandas/tests/io/pytables/test_select.py
index 3ee81a176ab9d..fc19a3bd63c74 100644
--- a/pandas/tests/io/pytables/test_select.py
+++ b/pandas/tests/io/pytables/test_select.py
@@ -1,4 +1,3 @@
-from distutils.version import LooseVersion
from warnings import catch_warnings
import numpy as np
@@ -25,7 +24,6 @@
_maybe_remove,
ensure_clean_path,
ensure_clean_store,
- tables,
)
from pandas.io.pytables import Term
@@ -861,10 +859,6 @@ def test_select_as_multiple(setup_path):
)
-@pytest.mark.skipif(
- LooseVersion(tables.__version__) < LooseVersion("3.1.0"),
- reason=("tables version does not support fix for nan selection bug: GH 4858"),
-)
def test_nan_selection_bug_4858(setup_path):
with ensure_clean_store(setup_path) as store:
diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py
index 81af799640135..a5254f5ff7988 100644
--- a/pandas/tests/io/test_feather.py
+++ b/pandas/tests/io/test_feather.py
@@ -1,6 +1,4 @@
""" test feather-format compat """
-from distutils.version import LooseVersion
-
import numpy as np
import pytest
@@ -8,13 +6,14 @@
import pandas as pd
import pandas._testing as tm
+from pandas.util.version import Version
from pandas.io.feather_format import read_feather, to_feather # isort:skip
pyarrow = pytest.importorskip("pyarrow")
-pyarrow_version = LooseVersion(pyarrow.__version__)
+pyarrow_version = Version(pyarrow.__version__)
filter_sparse = pytest.mark.filterwarnings("ignore:The Sparse")
@@ -90,7 +89,7 @@ def test_basic(self):
),
}
)
- if pyarrow_version >= LooseVersion("0.16.1.dev"):
+ if pyarrow_version >= Version("0.17.0"):
df["periods"] = pd.period_range("2013", freq="M", periods=3)
df["timedeltas"] = pd.timedelta_range("1 day", periods=3)
# TODO temporary disable due to regression in pyarrow 0.17.1
@@ -186,7 +185,7 @@ def test_path_localpath(self):
result = tm.round_trip_localpath(df.to_feather, read_feather)
tm.assert_frame_equal(df, result)
- @td.skip_if_no("pyarrow", min_version="0.16.1.dev")
+ @td.skip_if_no("pyarrow", min_version="0.17.0")
def test_passthrough_keywords(self):
df = tm.makeDataFrame().reset_index()
self.check_round_trip(df, write_kwargs={"version": 1})
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index 7cc7acd9007fa..30666a716859a 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -1,6 +1,5 @@
""" test parquet compat """
import datetime
-from distutils.version import LooseVersion
from io import BytesIO
import os
import pathlib
@@ -19,6 +18,7 @@
import pandas as pd
import pandas._testing as tm
+from pandas.util.version import Version
from pandas.io.parquet import (
FastParquetImpl,
@@ -273,12 +273,12 @@ def test_get_engine_auto_error_message():
have_pa_bad_version = (
False
if not _HAVE_PYARROW
- else LooseVersion(pyarrow.__version__) < LooseVersion(pa_min_ver)
+ else Version(pyarrow.__version__) < Version(pa_min_ver)
)
have_fp_bad_version = (
False
if not _HAVE_FASTPARQUET
- else LooseVersion(fastparquet.__version__) < LooseVersion(fp_min_ver)
+ else Version(fastparquet.__version__) < Version(fp_min_ver)
)
# Do we have usable engines installed?
have_usable_pa = _HAVE_PYARROW and not have_pa_bad_version
@@ -321,18 +321,6 @@ def test_cross_engine_pa_fp(df_cross_compat, pa, fp):
def test_cross_engine_fp_pa(request, df_cross_compat, pa, fp):
# cross-compat with differing reading/writing engines
-
- if (
- LooseVersion(pyarrow.__version__) < "0.15"
- and LooseVersion(pyarrow.__version__) >= "0.13"
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- "Reading fastparquet with pyarrow in 0.14 fails: "
- "https://issues.apache.org/jira/browse/ARROW-6492"
- )
- )
-
df = df_cross_compat
with tm.ensure_clean() as path:
df.to_parquet(path, engine=fp, compression=None)
@@ -623,13 +611,6 @@ def test_duplicate_columns(self, pa):
self.check_error_on_write(df, pa, ValueError, "Duplicate column names found")
def test_unsupported(self, pa):
- if LooseVersion(pyarrow.__version__) < LooseVersion("0.15.1.dev"):
- # period - will be supported using an extension type with pyarrow 1.0
- df = pd.DataFrame({"a": pd.period_range("2013", freq="M", periods=3)})
- # pyarrow 0.11 raises ArrowTypeError
- # older pyarrows raise ArrowInvalid
- self.check_external_error_on_write(df, pa, pyarrow.ArrowException)
-
# timedelta
df = pd.DataFrame({"a": pd.timedelta_range("1 day", periods=3)})
self.check_external_error_on_write(df, pa, NotImplementedError)
@@ -657,12 +638,7 @@ def test_categorical(self, pa):
["a", "b", "c", "a", "c", "b"], categories=["b", "c", "d"], ordered=True
)
- if LooseVersion(pyarrow.__version__) >= LooseVersion("0.15.0"):
- check_round_trip(df, pa)
- else:
- # de-serialized as object for pyarrow < 0.15
- expected = df.astype(object)
- check_round_trip(df, pa, expected=expected)
+ check_round_trip(df, pa)
@pytest.mark.xfail(
is_platform_windows() and PY38,
@@ -671,7 +647,7 @@ def test_categorical(self, pa):
)
def test_s3_roundtrip_explicit_fs(self, df_compat, s3_resource, pa, s3so):
s3fs = pytest.importorskip("s3fs")
- if LooseVersion(pyarrow.__version__) <= LooseVersion("0.17.0"):
+ if Version(pyarrow.__version__) <= Version("0.17.0"):
pytest.skip()
s3 = s3fs.S3FileSystem(**s3so)
kw = {"filesystem": s3}
@@ -684,7 +660,7 @@ def test_s3_roundtrip_explicit_fs(self, df_compat, s3_resource, pa, s3so):
)
def test_s3_roundtrip(self, df_compat, s3_resource, pa, s3so):
- if LooseVersion(pyarrow.__version__) <= LooseVersion("0.17.0"):
+ if Version(pyarrow.__version__) <= Version("0.17.0"):
pytest.skip()
# GH #19134
s3so = {"storage_options": s3so}
@@ -716,8 +692,8 @@ def test_s3_roundtrip_for_dir(
# These are added to back of dataframe on read. In new API category dtype is
# only used if partition field is string, but this changed again to use
# category dtype for all types (not only strings) in pyarrow 2.0.0
- pa10 = (LooseVersion(pyarrow.__version__) >= LooseVersion("1.0.0")) and (
- LooseVersion(pyarrow.__version__) < LooseVersion("2.0.0")
+ pa10 = (Version(pyarrow.__version__) >= Version("1.0.0")) and (
+ Version(pyarrow.__version__) < Version("2.0.0")
)
if partition_col:
if pa10:
@@ -824,7 +800,7 @@ def test_additional_extension_arrays(self, pa):
"c": pd.Series(["a", None, "c"], dtype="string"),
}
)
- if LooseVersion(pyarrow.__version__) >= LooseVersion("0.16.0"):
+ if Version(pyarrow.__version__) >= Version("0.16.0"):
expected = df
else:
# de-serialized as plain int / object
@@ -834,7 +810,7 @@ def test_additional_extension_arrays(self, pa):
check_round_trip(df, pa, expected=expected)
df = pd.DataFrame({"a": pd.Series([1, 2, 3, None], dtype="Int64")})
- if LooseVersion(pyarrow.__version__) >= LooseVersion("0.16.0"):
+ if Version(pyarrow.__version__) >= Version("0.16.0"):
expected = df
else:
# if missing values in integer, currently de-serialized as float
@@ -862,7 +838,7 @@ def test_additional_extension_types(self, pa):
)
check_round_trip(df, pa)
- @td.skip_if_no("pyarrow", min_version="0.16")
+ @td.skip_if_no("pyarrow", min_version="0.16.0")
def test_use_nullable_dtypes(self, pa):
import pyarrow.parquet as pq
@@ -891,7 +867,6 @@ def test_use_nullable_dtypes(self, pa):
)
tm.assert_frame_equal(result2, expected)
- @td.skip_if_no("pyarrow", min_version="0.14")
def test_timestamp_nanoseconds(self, pa):
# with version 2.0, pyarrow defaults to writing the nanoseconds, so
# this should work without error
@@ -899,7 +874,7 @@ def test_timestamp_nanoseconds(self, pa):
check_round_trip(df, pa, write_kwargs={"version": "2.0"})
def test_timezone_aware_index(self, pa, timezone_aware_date_list):
- if LooseVersion(pyarrow.__version__) >= LooseVersion("2.0.0"):
+ if Version(pyarrow.__version__) >= Version("2.0.0"):
# temporary skip this test until it is properly resolved
# https://github.com/pandas-dev/pandas/issues/37286
pytest.skip()
diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py
index 229399476773f..0b2a4cfb94d18 100644
--- a/pandas/tests/test_common.py
+++ b/pandas/tests/test_common.py
@@ -1,5 +1,4 @@
import collections
-from distutils.version import LooseVersion
from functools import partial
import string
@@ -13,6 +12,7 @@
import pandas._testing as tm
from pandas.core import ops
import pandas.core.common as com
+from pandas.util.version import Version
def test_get_callable_name():
@@ -142,9 +142,9 @@ def test_git_version():
def test_version_tag():
- version = pd.__version__
+ version = Version(pd.__version__)
try:
- version > LooseVersion("0.0.1")
+ version > Version("0.0.1")
except TypeError:
raise ValueError(
"No git tags exist, please sync tags between upstream and your repo"
diff --git a/pandas/tests/util/test_show_versions.py b/pandas/tests/util/test_show_versions.py
index 57cd2e1a144b6..7a1363099e7a0 100644
--- a/pandas/tests/util/test_show_versions.py
+++ b/pandas/tests/util/test_show_versions.py
@@ -32,7 +32,6 @@
# https://github.com/pandas-dev/pandas/issues/35252
"ignore:Distutils:UserWarning"
)
-@pytest.mark.filterwarnings("ignore:Setuptools is replacing distutils:UserWarning")
def test_show_versions(tmpdir):
# GH39701
as_json = os.path.join(tmpdir, "test_output.json")
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index dd22b5ef5e4ac..62e31c0e46715 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -26,7 +26,6 @@ def test_foo():
from __future__ import annotations
from contextlib import contextmanager
-from distutils.version import LooseVersion
import locale
from typing import Callable
import warnings
@@ -46,6 +45,7 @@ def test_foo():
NUMEXPR_INSTALLED,
USE_NUMEXPR,
)
+from pandas.util.version import Version
def safe_import(mod_name: str, min_version: str | None = None):
@@ -87,11 +87,8 @@ def safe_import(mod_name: str, min_version: str | None = None):
except AttributeError:
# xlrd uses a capitalized attribute name
version = getattr(sys.modules[mod_name], "__VERSION__")
- if version:
- from distutils.version import LooseVersion
-
- if LooseVersion(version) >= LooseVersion(min_version):
- return mod
+ if version and Version(version) >= Version(min_version):
+ return mod
return False
@@ -211,7 +208,7 @@ def skip_if_np_lt(ver_str: str, *args, reason: str | None = None):
if reason is None:
reason = f"NumPy {ver_str} or greater required"
return pytest.mark.skipif(
- np.__version__ < LooseVersion(ver_str),
+ Version(np.__version__) < Version(ver_str),
*args,
reason=reason,
)
diff --git a/pandas/util/version/__init__.py b/pandas/util/version/__init__.py
new file mode 100644
index 0000000000000..5ca3abb916ce0
--- /dev/null
+++ b/pandas/util/version/__init__.py
@@ -0,0 +1,580 @@
+# Vendored from https://github.com/pypa/packaging/blob/main/packaging/_structures.py
+# and https://github.com/pypa/packaging/blob/main/packaging/_structures.py
+# changeset ae891fd74d6dd4c6063bb04f2faeadaac6fc6313
+# 04/30/2021
+
+# This file is dual licensed under the terms of the Apache License, Version
+# 2.0, and the BSD License. See the LICENSE file in the root of this repository
+# for complete details.
+
+import collections
+import itertools
+import re
+from typing import (
+ Callable,
+ Iterator,
+ List,
+ Optional,
+ SupportsInt,
+ Tuple,
+ Union,
+)
+import warnings
+
+__all__ = ["parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN"]
+
+
+class InfinityType:
+ def __repr__(self) -> str:
+ return "Infinity"
+
+ def __hash__(self) -> int:
+ return hash(repr(self))
+
+ def __lt__(self, other: object) -> bool:
+ return False
+
+ def __le__(self, other: object) -> bool:
+ return False
+
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, type(self))
+
+ def __ne__(self, other: object) -> bool:
+ return not isinstance(other, type(self))
+
+ def __gt__(self, other: object) -> bool:
+ return True
+
+ def __ge__(self, other: object) -> bool:
+ return True
+
+ def __neg__(self: object) -> "NegativeInfinityType":
+ return NegativeInfinity
+
+
+Infinity = InfinityType()
+
+
+class NegativeInfinityType:
+ def __repr__(self) -> str:
+ return "-Infinity"
+
+ def __hash__(self) -> int:
+ return hash(repr(self))
+
+ def __lt__(self, other: object) -> bool:
+ return True
+
+ def __le__(self, other: object) -> bool:
+ return True
+
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, type(self))
+
+ def __ne__(self, other: object) -> bool:
+ return not isinstance(other, type(self))
+
+ def __gt__(self, other: object) -> bool:
+ return False
+
+ def __ge__(self, other: object) -> bool:
+ return False
+
+ def __neg__(self: object) -> InfinityType:
+ return Infinity
+
+
+NegativeInfinity = NegativeInfinityType()
+
+
+InfiniteTypes = Union[InfinityType, NegativeInfinityType]
+PrePostDevType = Union[InfiniteTypes, Tuple[str, int]]
+SubLocalType = Union[InfiniteTypes, int, str]
+LocalType = Union[
+ NegativeInfinityType,
+ Tuple[
+ Union[
+ SubLocalType,
+ Tuple[SubLocalType, str],
+ Tuple[NegativeInfinityType, SubLocalType],
+ ],
+ ...,
+ ],
+]
+CmpKey = Tuple[
+ int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType
+]
+LegacyCmpKey = Tuple[int, Tuple[str, ...]]
+VersionComparisonMethod = Callable[
+ [Union[CmpKey, LegacyCmpKey], Union[CmpKey, LegacyCmpKey]], bool
+]
+
+_Version = collections.namedtuple(
+ "_Version", ["epoch", "release", "dev", "pre", "post", "local"]
+)
+
+
+def parse(version: str) -> Union["LegacyVersion", "Version"]:
+ """
+ Parse the given version string and return either a :class:`Version` object
+ or a :class:`LegacyVersion` object depending on if the given version is
+ a valid PEP 440 version or a legacy version.
+ """
+ try:
+ return Version(version)
+ except InvalidVersion:
+ return LegacyVersion(version)
+
+
+class InvalidVersion(ValueError):
+ """
+ An invalid version was found, users should refer to PEP 440.
+ """
+
+
+class _BaseVersion:
+ _key: Union[CmpKey, LegacyCmpKey]
+
+ def __hash__(self) -> int:
+ return hash(self._key)
+
+ # Please keep the duplicated `isinstance` check
+ # in the six comparisons hereunder
+ # unless you find a way to avoid adding overhead function calls.
+ def __lt__(self, other: "_BaseVersion") -> bool:
+ if not isinstance(other, _BaseVersion):
+ return NotImplemented
+
+ return self._key < other._key
+
+ def __le__(self, other: "_BaseVersion") -> bool:
+ if not isinstance(other, _BaseVersion):
+ return NotImplemented
+
+ return self._key <= other._key
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, _BaseVersion):
+ return NotImplemented
+
+ return self._key == other._key
+
+ def __ge__(self, other: "_BaseVersion") -> bool:
+ if not isinstance(other, _BaseVersion):
+ return NotImplemented
+
+ return self._key >= other._key
+
+ def __gt__(self, other: "_BaseVersion") -> bool:
+ if not isinstance(other, _BaseVersion):
+ return NotImplemented
+
+ return self._key > other._key
+
+ def __ne__(self, other: object) -> bool:
+ if not isinstance(other, _BaseVersion):
+ return NotImplemented
+
+ return self._key != other._key
+
+
+class LegacyVersion(_BaseVersion):
+ def __init__(self, version: str) -> None:
+ self._version = str(version)
+ self._key = _legacy_cmpkey(self._version)
+
+ warnings.warn(
+ "Creating a LegacyVersion has been deprecated and will be "
+ "removed in the next major release",
+ DeprecationWarning,
+ )
+
+ def __str__(self) -> str:
+ return self._version
+
+ def __repr__(self) -> str:
+ return f"<LegacyVersion('{self}')>"
+
+ @property
+ def public(self) -> str:
+ return self._version
+
+ @property
+ def base_version(self) -> str:
+ return self._version
+
+ @property
+ def epoch(self) -> int:
+ return -1
+
+ @property
+ def release(self) -> None:
+ return None
+
+ @property
+ def pre(self) -> None:
+ return None
+
+ @property
+ def post(self) -> None:
+ return None
+
+ @property
+ def dev(self) -> None:
+ return None
+
+ @property
+ def local(self) -> None:
+ return None
+
+ @property
+ def is_prerelease(self) -> bool:
+ return False
+
+ @property
+ def is_postrelease(self) -> bool:
+ return False
+
+ @property
+ def is_devrelease(self) -> bool:
+ return False
+
+
+_legacy_version_component_re = re.compile(r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE)
+
+_legacy_version_replacement_map = {
+ "pre": "c",
+ "preview": "c",
+ "-": "final-",
+ "rc": "c",
+ "dev": "@",
+}
+
+
+def _parse_version_parts(s: str) -> Iterator[str]:
+ for part in _legacy_version_component_re.split(s):
+ part = _legacy_version_replacement_map.get(part, part)
+
+ if not part or part == ".":
+ continue
+
+ if part[:1] in "0123456789":
+ # pad for numeric comparison
+ yield part.zfill(8)
+ else:
+ yield "*" + part
+
+ # ensure that alpha/beta/candidate are before final
+ yield "*final"
+
+
+def _legacy_cmpkey(version: str) -> LegacyCmpKey:
+
+ # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch
+ # greater than or equal to 0. This will effectively put the LegacyVersion,
+ # which uses the defacto standard originally implemented by setuptools,
+ # as before all PEP 440 versions.
+ epoch = -1
+
+ # This scheme is taken from pkg_resources.parse_version setuptools prior to
+ # it's adoption of the packaging library.
+ parts: List[str] = []
+ for part in _parse_version_parts(version.lower()):
+ if part.startswith("*"):
+ # remove "-" before a prerelease tag
+ if part < "*final":
+ while parts and parts[-1] == "*final-":
+ parts.pop()
+
+ # remove trailing zeros from each series of numeric parts
+ while parts and parts[-1] == "00000000":
+ parts.pop()
+
+ parts.append(part)
+
+ return epoch, tuple(parts)
+
+
+# Deliberately not anchored to the start and end of the string, to make it
+# easier for 3rd party code to reuse
+VERSION_PATTERN = r"""
+ v?
+ (?:
+ (?:(?P<epoch>[0-9]+)!)? # epoch
+ (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
+ (?P<pre> # pre-release
+ [-_\.]?
+ (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
+ [-_\.]?
+ (?P<pre_n>[0-9]+)?
+ )?
+ (?P<post> # post release
+ (?:-(?P<post_n1>[0-9]+))
+ |
+ (?:
+ [-_\.]?
+ (?P<post_l>post|rev|r)
+ [-_\.]?
+ (?P<post_n2>[0-9]+)?
+ )
+ )?
+ (?P<dev> # dev release
+ [-_\.]?
+ (?P<dev_l>dev)
+ [-_\.]?
+ (?P<dev_n>[0-9]+)?
+ )?
+ )
+ (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
+"""
+
+
+class Version(_BaseVersion):
+
+ _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+
+ def __init__(self, version: str) -> None:
+
+ # Validate the version and parse it into pieces
+ match = self._regex.search(version)
+ if not match:
+ raise InvalidVersion(f"Invalid version: '{version}'")
+
+ # Store the parsed out pieces of the version
+ self._version = _Version(
+ epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+ release=tuple(int(i) for i in match.group("release").split(".")),
+ pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
+ post=_parse_letter_version(
+ match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+ ),
+ dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
+ local=_parse_local_version(match.group("local")),
+ )
+
+ # Generate a key which will be used for sorting
+ self._key = _cmpkey(
+ self._version.epoch,
+ self._version.release,
+ self._version.pre,
+ self._version.post,
+ self._version.dev,
+ self._version.local,
+ )
+
+ def __repr__(self) -> str:
+ return f"<Version('{self}')>"
+
+ def __str__(self) -> str:
+ parts = []
+
+ # Epoch
+ if self.epoch != 0:
+ parts.append(f"{self.epoch}!")
+
+ # Release segment
+ parts.append(".".join(str(x) for x in self.release))
+
+ # Pre-release
+ if self.pre is not None:
+ parts.append("".join(str(x) for x in self.pre))
+
+ # Post-release
+ if self.post is not None:
+ parts.append(f".post{self.post}")
+
+ # Development release
+ if self.dev is not None:
+ parts.append(f".dev{self.dev}")
+
+ # Local version segment
+ if self.local is not None:
+ parts.append(f"+{self.local}")
+
+ return "".join(parts)
+
+ @property
+ def epoch(self) -> int:
+ _epoch: int = self._version.epoch
+ return _epoch
+
+ @property
+ def release(self) -> Tuple[int, ...]:
+ _release: Tuple[int, ...] = self._version.release
+ return _release
+
+ @property
+ def pre(self) -> Optional[Tuple[str, int]]:
+ _pre: Optional[Tuple[str, int]] = self._version.pre
+ return _pre
+
+ @property
+ def post(self) -> Optional[int]:
+ return self._version.post[1] if self._version.post else None
+
+ @property
+ def dev(self) -> Optional[int]:
+ return self._version.dev[1] if self._version.dev else None
+
+ @property
+ def local(self) -> Optional[str]:
+ if self._version.local:
+ return ".".join(str(x) for x in self._version.local)
+ else:
+ return None
+
+ @property
+ def public(self) -> str:
+ return str(self).split("+", 1)[0]
+
+ @property
+ def base_version(self) -> str:
+ parts = []
+
+ # Epoch
+ if self.epoch != 0:
+ parts.append(f"{self.epoch}!")
+
+ # Release segment
+ parts.append(".".join(str(x) for x in self.release))
+
+ return "".join(parts)
+
+ @property
+ def is_prerelease(self) -> bool:
+ return self.dev is not None or self.pre is not None
+
+ @property
+ def is_postrelease(self) -> bool:
+ return self.post is not None
+
+ @property
+ def is_devrelease(self) -> bool:
+ return self.dev is not None
+
+ @property
+ def major(self) -> int:
+ return self.release[0] if len(self.release) >= 1 else 0
+
+ @property
+ def minor(self) -> int:
+ return self.release[1] if len(self.release) >= 2 else 0
+
+ @property
+ def micro(self) -> int:
+ return self.release[2] if len(self.release) >= 3 else 0
+
+
+def _parse_letter_version(
+ letter: str, number: Union[str, bytes, SupportsInt]
+) -> Optional[Tuple[str, int]]:
+
+ if letter:
+ # We consider there to be an implicit 0 in a pre-release if there is
+ # not a numeral associated with it.
+ if number is None:
+ number = 0
+
+ # We normalize any letters to their lower case form
+ letter = letter.lower()
+
+ # We consider some words to be alternate spellings of other words and
+ # in those cases we want to normalize the spellings to our preferred
+ # spelling.
+ if letter == "alpha":
+ letter = "a"
+ elif letter == "beta":
+ letter = "b"
+ elif letter in ["c", "pre", "preview"]:
+ letter = "rc"
+ elif letter in ["rev", "r"]:
+ letter = "post"
+
+ return letter, int(number)
+ if not letter and number:
+ # We assume if we are given a number, but we are not given a letter
+ # then this is using the implicit post release syntax (e.g. 1.0-1)
+ letter = "post"
+
+ return letter, int(number)
+
+ return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: str) -> Optional[LocalType]:
+ """
+ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+ """
+ if local is not None:
+ return tuple(
+ part.lower() if not part.isdigit() else int(part)
+ for part in _local_version_separators.split(local)
+ )
+ return None
+
+
+def _cmpkey(
+ epoch: int,
+ release: Tuple[int, ...],
+ pre: Optional[Tuple[str, int]],
+ post: Optional[Tuple[str, int]],
+ dev: Optional[Tuple[str, int]],
+ local: Optional[Tuple[SubLocalType]],
+) -> CmpKey:
+
+ # When we compare a release version, we want to compare it with all of the
+ # trailing zeros removed. So we'll use a reverse the list, drop all the now
+ # leading zeros until we come to something non zero, then take the rest
+ # re-reverse it back into the correct order and make it a tuple and use
+ # that for our sorting key.
+ _release = tuple(
+ reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
+ )
+
+ # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+ # We'll do this by abusing the pre segment, but we _only_ want to do this
+ # if there is not a pre or a post segment. If we have one of those then
+ # the normal sorting rules will handle this case correctly.
+ if pre is None and post is None and dev is not None:
+ _pre: PrePostDevType = NegativeInfinity
+ # Versions without a pre-release (except as noted above) should sort after
+ # those with one.
+ elif pre is None:
+ _pre = Infinity
+ else:
+ _pre = pre
+
+ # Versions without a post segment should sort before those with one.
+ if post is None:
+ _post: PrePostDevType = NegativeInfinity
+
+ else:
+ _post = post
+
+ # Versions without a development segment should sort after those with one.
+ if dev is None:
+ _dev: PrePostDevType = Infinity
+
+ else:
+ _dev = dev
+
+ if local is None:
+ # Versions without a local segment should sort before those with one.
+ _local: LocalType = NegativeInfinity
+ else:
+ # Versions with a local segment need that segment parsed to implement
+ # the sorting rules in PEP440.
+ # - Alpha numeric segments sort before numeric segments
+ # - Alpha numeric segments sort lexicographically
+ # - Numeric segments sort numerically
+ # - Shorter versions sort before longer versions when the prefixes
+ # match exactly
+ _local = tuple(
+ (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
+ )
+
+ return epoch, _release, _pre, _post, _dev, _local
diff --git a/setup.py b/setup.py
index b410c5c154648..386074519ca4f 100755
--- a/setup.py
+++ b/setup.py
@@ -7,17 +7,16 @@
"""
import argparse
-from distutils.command.build import build
-from distutils.sysconfig import get_config_vars
-from distutils.version import LooseVersion
import multiprocessing
import os
from os.path import join as pjoin
import platform
import shutil
import sys
+from sysconfig import get_config_vars
import numpy
+from pkg_resources import parse_version
from setuptools import (
Command,
Extension,
@@ -47,7 +46,7 @@ def is_platform_mac():
)
from Cython.Build import cythonize
- _CYTHON_INSTALLED = _CYTHON_VERSION >= LooseVersion(min_cython_ver)
+ _CYTHON_INSTALLED = parse_version(_CYTHON_VERSION) >= parse_version(min_cython_ver)
except ImportError:
_CYTHON_VERSION = None
_CYTHON_INSTALLED = False
@@ -106,7 +105,7 @@ def build_extensions(self):
class CleanCommand(Command):
- """Custom distutils command to clean the .so and .pyc files."""
+ """Custom command to clean the .so and .pyc files."""
user_options = [("all", "a", "")]
@@ -278,7 +277,7 @@ def build_extensions(self):
class CythonCommand(build_ext):
"""
- Custom distutils command subclassed from Cython.Distutils.build_ext
+ Custom command subclassed from Cython.Distutils.build_ext
to compile pyx->c, and stop there. All this does is override the
C-compile method build_extension() with a no-op.
"""
@@ -302,7 +301,7 @@ def run(self):
pass
-cmdclass.update({"clean": CleanCommand, "build": build})
+cmdclass["clean"] = CleanCommand
cmdclass["build_ext"] = CheckingBuildExt
if _CYTHON_INSTALLED:
@@ -351,11 +350,13 @@ def run(self):
python_target = get_config_vars().get(
"MACOSX_DEPLOYMENT_TARGET", current_system
)
+ target_macos_version = "10.9"
+ parsed_macos_version = parse_version(target_macos_version)
if (
- LooseVersion(str(python_target)) < "10.9"
- and LooseVersion(current_system) >= "10.9"
+ parse_version(str(python_target)) < parsed_macos_version
+ and parse_version(current_system) >= parsed_macos_version
):
- os.environ["MACOSX_DEPLOYMENT_TARGET"] = "10.9"
+ os.environ["MACOSX_DEPLOYMENT_TARGET"] = target_macos_version
if sys.version_info[:2] == (3, 8): # GH 33239
extra_compile_args.append("-Wno-error=deprecated-declarations")
| - [x] close #41199
| https://api.github.com/repos/pandas-dev/pandas/pulls/41207 | 2021-04-28T21:12:45Z | 2021-05-05T20:14:09Z | 2021-05-05T20:14:09Z | 2021-06-18T02:25:50Z |
DOC: Add Lux to Pandas Ecosystem page | diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index 56aa734deddd6..d53d0556dca04 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -164,6 +164,21 @@ A good implementation for Python users is `has2k1/plotnine <https://github.com/h
`Plotly’s <https://plot.ly/>`__ `Python API <https://plot.ly/python/>`__ enables interactive figures and web shareability. Maps, 2D, 3D, and live-streaming graphs are rendered with WebGL and `D3.js <https://d3js.org/>`__. The library supports plotting directly from a pandas DataFrame and cloud-based collaboration. Users of `matplotlib, ggplot for Python, and Seaborn <https://plot.ly/python/matplotlib-to-plotly-tutorial/>`__ can convert figures into interactive web-based plots. Plots can be drawn in `IPython Notebooks <https://plot.ly/ipython-notebooks/>`__ , edited with R or MATLAB, modified in a GUI, or embedded in apps and dashboards. Plotly is free for unlimited sharing, and has `cloud <https://plot.ly/product/plans/>`__, `offline <https://plot.ly/python/offline/>`__, or `on-premise <https://plot.ly/product/enterprise/>`__ accounts for private use.
+`Lux <https://github.com/lux-org/lux>`__
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+`Lux <https://github.com/lux-org/lux>`__ is a Python library that facilitates fast and easy experimentation with data by automating the visual data exploration process. To use Lux, simply add an extra import alongside pandas:
+
+.. code:: python
+
+ import lux
+ import pandas as pd
+
+ df = pd.read_csv("data.csv")
+ df # discover interesting insights!
+
+By printing out a dataframe, Lux automatically `recommends a set of visualizations <https://github.com/lux-org/lux-resources/blob/master/readme_img/demohighlight.gif?raw=true>`__ that highlights interesting trends and patterns in the dataframe. Users can leverage any existing pandas commands without modifying their code, while being able to visualize their pandas data structures (e.g., DataFrame, Series, Index) at the same time. Lux also offers a `powerful, intuitive language <https://lux-api.readthedocs.io/en/latest/source/guide/vis.html>`__ that allow users to create `Altair <https://altair-viz.github.io/>`__, `matplotlib <https://matplotlib.org>`__, or `Vega-Lite <https://vega.github.io/vega-lite/>`__ visualizations without having to think at the level of code.
+
`Qtpandas <https://github.com/draperjames/qtpandas>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| #### Location of the documentation
List of systems under [pandas ecosystem](https://pandas.pydata.org/docs/ecosystem.html#pandas-ecosystem)
#### Documentation problem
Add [Lux](https://github.com/lux-org/lux) to the ["pandas ecosystem" documentation](https://pandas.pydata.org/docs/ecosystem.html#pandas-ecosystem)
| https://api.github.com/repos/pandas-dev/pandas/pulls/41205 | 2021-04-28T19:12:38Z | 2021-05-01T18:10:48Z | 2021-05-01T18:10:48Z | 2021-05-01T18:11:00Z |
CLN: groupby.ops follow-up cleanup | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 2436391580dcb..7fe9d7cb49eb5 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -809,6 +809,7 @@ class GroupBy(BaseGroupBy[FrameOrSeries]):
grouper: ops.BaseGrouper
as_index: bool
+ @final
def __init__(
self,
obj: FrameOrSeries,
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 96f5b2cfb9d81..ed3b6d68b71cd 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -14,6 +14,7 @@
Hashable,
Iterator,
Sequence,
+ overload,
)
import numpy as np
@@ -47,23 +48,35 @@
is_categorical_dtype,
is_complex_dtype,
is_datetime64_any_dtype,
- is_datetime64tz_dtype,
is_extension_array_dtype,
- is_float_dtype,
is_integer_dtype,
is_numeric_dtype,
- is_period_dtype,
is_sparse,
is_timedelta64_dtype,
needs_i8_conversion,
)
+from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.generic import ABCCategoricalIndex
from pandas.core.dtypes.missing import (
isna,
maybe_fill,
)
-from pandas.core.arrays import ExtensionArray
+from pandas.core.arrays import (
+ DatetimeArray,
+ ExtensionArray,
+ PeriodArray,
+ TimedeltaArray,
+)
+from pandas.core.arrays.boolean import BooleanDtype
+from pandas.core.arrays.floating import (
+ Float64Dtype,
+ FloatingDtype,
+)
+from pandas.core.arrays.integer import (
+ Int64Dtype,
+ _IntegerDtype,
+)
from pandas.core.arrays.masked import (
BaseMaskedArray,
BaseMaskedDtype,
@@ -194,7 +207,7 @@ def get_cython_func_and_vals(self, values: np.ndarray, is_numeric: bool):
return func, values
- def disallow_invalid_ops(self, dtype: DtypeObj, is_numeric: bool = False):
+ def _disallow_invalid_ops(self, dtype: DtypeObj, is_numeric: bool = False):
"""
Check if we can do this operation with our cython functions.
@@ -230,7 +243,7 @@ def disallow_invalid_ops(self, dtype: DtypeObj, is_numeric: bool = False):
if how in ["prod", "cumprod"]:
raise TypeError(f"timedelta64 type does not support {how} operations")
- def get_output_shape(self, ngroups: int, values: np.ndarray) -> Shape:
+ def _get_output_shape(self, ngroups: int, values: np.ndarray) -> Shape:
how = self.how
kind = self.kind
@@ -261,7 +274,15 @@ def get_out_dtype(self, dtype: np.dtype) -> np.dtype:
out_dtype = "object"
return np.dtype(out_dtype)
- def get_result_dtype(self, dtype: DtypeObj) -> DtypeObj:
+ @overload
+ def _get_result_dtype(self, dtype: np.dtype) -> np.dtype:
+ ...
+
+ @overload
+ def _get_result_dtype(self, dtype: ExtensionDtype) -> ExtensionDtype:
+ ...
+
+ def _get_result_dtype(self, dtype: DtypeObj) -> DtypeObj:
"""
Get the desired dtype of a result based on the
input dtype and how it was computed.
@@ -276,13 +297,6 @@ def get_result_dtype(self, dtype: DtypeObj) -> DtypeObj:
np.dtype or ExtensionDtype
The desired dtype of the result.
"""
- from pandas.core.arrays.boolean import BooleanDtype
- from pandas.core.arrays.floating import Float64Dtype
- from pandas.core.arrays.integer import (
- Int64Dtype,
- _IntegerDtype,
- )
-
how = self.how
if how in ["add", "cumsum", "sum", "prod"]:
@@ -315,15 +329,12 @@ def _ea_wrap_cython_operation(
# TODO: general case implementation overridable by EAs.
orig_values = values
- if is_datetime64tz_dtype(values.dtype) or is_period_dtype(values.dtype):
+ if isinstance(orig_values, (DatetimeArray, PeriodArray)):
# All of the functions implemented here are ordinal, so we can
# operate on the tz-naive equivalents
- npvalues = values.view("M8[ns]")
+ npvalues = orig_values._ndarray.view("M8[ns]")
res_values = self._cython_op_ndim_compat(
- # error: Argument 1 to "_cython_op_ndim_compat" of
- # "WrappedCythonOp" has incompatible type
- # "Union[ExtensionArray, ndarray]"; expected "ndarray"
- npvalues, # type: ignore[arg-type]
+ npvalues,
min_count=min_count,
ngroups=ngroups,
comp_ids=comp_ids,
@@ -336,14 +347,31 @@ def _ea_wrap_cython_operation(
# preserve float64 dtype
return res_values
- res_values = res_values.astype("i8", copy=False)
- # error: Too many arguments for "ExtensionArray"
- result = type(orig_values)( # type: ignore[call-arg]
- res_values, dtype=orig_values.dtype
+ res_values = res_values.view("i8")
+ result = type(orig_values)(res_values, dtype=orig_values.dtype)
+ return result
+
+ elif isinstance(orig_values, TimedeltaArray):
+ # We have an ExtensionArray but not ExtensionDtype
+ res_values = self._cython_op_ndim_compat(
+ orig_values._ndarray,
+ min_count=min_count,
+ ngroups=ngroups,
+ comp_ids=comp_ids,
+ mask=None,
+ **kwargs,
)
+ if self.how in ["rank"]:
+ # i.e. how in WrappedCythonOp.cast_blocklist, since
+ # other cast_blocklist methods dont go through cython_operation
+ # preserve float64 dtype
+ return res_values
+
+ # otherwise res_values has the same dtype as original values
+ result = type(orig_values)(res_values)
return result
- elif is_integer_dtype(values.dtype) or is_bool_dtype(values.dtype):
+ elif isinstance(values.dtype, (BooleanDtype, _IntegerDtype)):
# IntegerArray or BooleanArray
npvalues = values.to_numpy("float64", na_value=np.nan)
res_values = self._cython_op_ndim_compat(
@@ -359,17 +387,14 @@ def _ea_wrap_cython_operation(
# other cast_blocklist methods dont go through cython_operation
return res_values
- dtype = self.get_result_dtype(orig_values.dtype)
- # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]"
- # has no attribute "construct_array_type"
- cls = dtype.construct_array_type() # type: ignore[union-attr]
+ dtype = self._get_result_dtype(orig_values.dtype)
+ cls = dtype.construct_array_type()
return cls._from_sequence(res_values, dtype=dtype)
- elif is_float_dtype(values.dtype):
+ elif isinstance(values.dtype, FloatingDtype):
# FloatingArray
- # error: "ExtensionDtype" has no attribute "numpy_dtype"
npvalues = values.to_numpy(
- values.dtype.numpy_dtype, # type: ignore[attr-defined]
+ values.dtype.numpy_dtype,
na_value=np.nan,
)
res_values = self._cython_op_ndim_compat(
@@ -385,10 +410,8 @@ def _ea_wrap_cython_operation(
# other cast_blocklist methods dont go through cython_operation
return res_values
- dtype = self.get_result_dtype(orig_values.dtype)
- # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]"
- # has no attribute "construct_array_type"
- cls = dtype.construct_array_type() # type: ignore[union-attr]
+ dtype = self._get_result_dtype(orig_values.dtype)
+ cls = dtype.construct_array_type()
return cls._from_sequence(res_values, dtype=dtype)
raise NotImplementedError(
@@ -422,12 +445,13 @@ def _masked_ea_wrap_cython_operation(
mask=mask,
**kwargs,
)
- dtype = self.get_result_dtype(orig_values.dtype)
+ dtype = self._get_result_dtype(orig_values.dtype)
assert isinstance(dtype, BaseMaskedDtype)
cls = dtype.construct_array_type()
return cls(res_values.astype(dtype.type, copy=False), mask)
+ @final
def _cython_op_ndim_compat(
self,
values: np.ndarray,
@@ -500,7 +524,7 @@ def _call_cython_op(
if mask is not None:
mask = mask.reshape(values.shape, order="C")
- out_shape = self.get_output_shape(ngroups, values)
+ out_shape = self._get_output_shape(ngroups, values)
func, values = self.get_cython_func_and_vals(values, is_numeric)
out_dtype = self.get_out_dtype(values.dtype)
@@ -550,12 +574,8 @@ def _call_cython_op(
if self.how not in self.cast_blocklist:
# e.g. if we are int64 and need to restore to datetime64/timedelta64
# "rank" is the only member of cast_blocklist we get here
- res_dtype = self.get_result_dtype(orig_values.dtype)
- # error: Argument 2 to "maybe_downcast_to_dtype" has incompatible type
- # "Union[dtype[Any], ExtensionDtype]"; expected "Union[str, dtype[Any]]"
- op_result = maybe_downcast_to_dtype(
- result, res_dtype # type: ignore[arg-type]
- )
+ res_dtype = self._get_result_dtype(orig_values.dtype)
+ op_result = maybe_downcast_to_dtype(result, res_dtype)
else:
op_result = result
@@ -563,6 +583,62 @@ def _call_cython_op(
# expected "ndarray")
return op_result # type: ignore[return-value]
+ @final
+ def cython_operation(
+ self,
+ *,
+ values: ArrayLike,
+ axis: int,
+ min_count: int = -1,
+ comp_ids: np.ndarray,
+ ngroups: int,
+ **kwargs,
+ ) -> ArrayLike:
+ """
+ Call our cython function, with appropriate pre- and post- processing.
+ """
+ if values.ndim > 2:
+ raise NotImplementedError("number of dimensions is currently limited to 2")
+ elif values.ndim == 2:
+ # Note: it is *not* the case that axis is always 0 for 1-dim values,
+ # as we can have 1D ExtensionArrays that we need to treat as 2D
+ assert axis == 1, axis
+
+ dtype = values.dtype
+ is_numeric = is_numeric_dtype(dtype)
+
+ # can we do this operation with our cython functions
+ # if not raise NotImplementedError
+ self._disallow_invalid_ops(dtype, is_numeric)
+
+ if not isinstance(values, np.ndarray):
+ # i.e. ExtensionArray
+ if isinstance(values, BaseMaskedArray) and self.uses_mask():
+ return self._masked_ea_wrap_cython_operation(
+ values,
+ min_count=min_count,
+ ngroups=ngroups,
+ comp_ids=comp_ids,
+ **kwargs,
+ )
+ else:
+ return self._ea_wrap_cython_operation(
+ values,
+ min_count=min_count,
+ ngroups=ngroups,
+ comp_ids=comp_ids,
+ **kwargs,
+ )
+
+ return self._cython_op_ndim_compat(
+ values,
+ min_count=min_count,
+ ngroups=ngroups,
+ comp_ids=comp_ids,
+ mask=None,
+ **kwargs,
+ )
+
class BaseGrouper:
"""
@@ -799,6 +875,7 @@ def group_info(self):
ngroups = len(obs_group_ids)
comp_ids = ensure_platform_int(comp_ids)
+
return comp_ids, obs_group_ids, ngroups
@final
@@ -868,7 +945,6 @@ def _cython_operation(
how: str,
axis: int,
min_count: int = -1,
- mask: np.ndarray | None = None,
**kwargs,
) -> ArrayLike:
"""
@@ -876,50 +952,16 @@ def _cython_operation(
"""
assert kind in ["transform", "aggregate"]
- if values.ndim > 2:
- raise NotImplementedError("number of dimensions is currently limited to 2")
- elif values.ndim == 2:
- # Note: it is *not* the case that axis is always 0 for 1-dim values,
- # as we can have 1D ExtensionArrays that we need to treat as 2D
- assert axis == 1, axis
-
- dtype = values.dtype
- is_numeric = is_numeric_dtype(dtype)
-
cy_op = WrappedCythonOp(kind=kind, how=how)
- # can we do this operation with our cython functions
- # if not raise NotImplementedError
- cy_op.disallow_invalid_ops(dtype, is_numeric)
-
comp_ids, _, _ = self.group_info
ngroups = self.ngroups
-
- func_uses_mask = cy_op.uses_mask()
- if is_extension_array_dtype(dtype):
- if isinstance(values, BaseMaskedArray) and func_uses_mask:
- return cy_op._masked_ea_wrap_cython_operation(
- values,
- min_count=min_count,
- ngroups=ngroups,
- comp_ids=comp_ids,
- **kwargs,
- )
- else:
- return cy_op._ea_wrap_cython_operation(
- values,
- min_count=min_count,
- ngroups=ngroups,
- comp_ids=comp_ids,
- **kwargs,
- )
-
- return cy_op._cython_op_ndim_compat(
- values,
+ return cy_op.cython_operation(
+ values=values,
+ axis=axis,
min_count=min_count,
- ngroups=self.ngroups,
comp_ids=comp_ids,
- mask=mask,
+ ngroups=ngroups,
**kwargs,
)
@@ -969,8 +1011,8 @@ def _aggregate_series_fast(
indexer = get_group_index_sorter(group_index, ngroups)
obj = obj.take(indexer)
group_index = group_index.take(indexer)
- grouper = libreduction.SeriesGrouper(obj, func, group_index, ngroups)
- result, counts = grouper.get_result()
+ sgrouper = libreduction.SeriesGrouper(obj, func, group_index, ngroups)
+ result, counts = sgrouper.get_result()
return result, counts
@final
@@ -1167,8 +1209,8 @@ def _aggregate_series_fast(
# - obj is backed by an ndarray, not ExtensionArray
# - ngroups != 0
# - len(self.bins) > 0
- grouper = libreduction.SeriesBinGrouper(obj, func, self.bins)
- return grouper.get_result()
+ sbg = libreduction.SeriesBinGrouper(obj, func, self.bins)
+ return sbg.get_result()
def _is_indexed_like(obj, axes, axis: int) -> bool:
| get the namespaces/privateness "right"
avoid runtime imports
fix "type: ignore"s | https://api.github.com/repos/pandas-dev/pandas/pulls/41204 | 2021-04-28T19:10:16Z | 2021-04-30T14:53:48Z | 2021-04-30T14:53:48Z | 2021-04-30T15:22:00Z |
TYP: Fix typing in ExtensionDtype registry | diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index 5b7dadac5d914..7dad8c61f4fc7 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -8,6 +8,8 @@
TYPE_CHECKING,
Any,
TypeVar,
+ cast,
+ overload,
)
import numpy as np
@@ -15,6 +17,7 @@
from pandas._libs.hashtable import object_hash
from pandas._typing import (
DtypeObj,
+ npt,
type_t,
)
from pandas.errors import AbstractMethodError
@@ -29,7 +32,7 @@
from pandas.core.arrays import ExtensionArray
# To parameterize on same ExtensionDtype
- E = TypeVar("E", bound="ExtensionDtype")
+ ExtensionDtypeT = TypeVar("ExtensionDtypeT", bound="ExtensionDtype")
class ExtensionDtype:
@@ -206,7 +209,9 @@ def construct_array_type(cls) -> type_t[ExtensionArray]:
raise AbstractMethodError(cls)
@classmethod
- def construct_from_string(cls, string: str):
+ def construct_from_string(
+ cls: type_t[ExtensionDtypeT], string: str
+ ) -> ExtensionDtypeT:
r"""
Construct this type from a string.
@@ -368,7 +373,7 @@ def _can_hold_na(self) -> bool:
return True
-def register_extension_dtype(cls: type[E]) -> type[E]:
+def register_extension_dtype(cls: type_t[ExtensionDtypeT]) -> type_t[ExtensionDtypeT]:
"""
Register an ExtensionType with pandas as class decorator.
@@ -409,9 +414,9 @@ class Registry:
"""
def __init__(self):
- self.dtypes: list[type[ExtensionDtype]] = []
+ self.dtypes: list[type_t[ExtensionDtype]] = []
- def register(self, dtype: type[ExtensionDtype]) -> None:
+ def register(self, dtype: type_t[ExtensionDtype]) -> None:
"""
Parameters
----------
@@ -422,22 +427,46 @@ def register(self, dtype: type[ExtensionDtype]) -> None:
self.dtypes.append(dtype)
- def find(self, dtype: type[ExtensionDtype] | str) -> type[ExtensionDtype] | None:
+ @overload
+ def find(self, dtype: type_t[ExtensionDtypeT]) -> type_t[ExtensionDtypeT]:
+ ...
+
+ @overload
+ def find(self, dtype: ExtensionDtypeT) -> ExtensionDtypeT:
+ ...
+
+ @overload
+ def find(self, dtype: str) -> ExtensionDtype | None:
+ ...
+
+ @overload
+ def find(
+ self, dtype: npt.DTypeLike
+ ) -> type_t[ExtensionDtype] | ExtensionDtype | None:
+ ...
+
+ def find(
+ self, dtype: type_t[ExtensionDtype] | ExtensionDtype | npt.DTypeLike
+ ) -> type_t[ExtensionDtype] | ExtensionDtype | None:
"""
Parameters
----------
- dtype : Type[ExtensionDtype] or str
+ dtype : ExtensionDtype class or instance or str or numpy dtype or python type
Returns
-------
return the first matching dtype, otherwise return None
"""
if not isinstance(dtype, str):
- dtype_type = dtype
+ dtype_type: type_t
if not isinstance(dtype, type):
dtype_type = type(dtype)
+ else:
+ dtype_type = dtype
if issubclass(dtype_type, ExtensionDtype):
- return dtype
+ # cast needed here as mypy doesn't know we have figured
+ # out it is an ExtensionDtype or type_t[ExtensionDtype]
+ return cast("ExtensionDtype | type_t[ExtensionDtype]", dtype)
return None
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 08287cc296006..3a870c2287584 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -1765,9 +1765,7 @@ def pandas_dtype(dtype) -> DtypeObj:
# registered extension types
result = registry.find(dtype)
if result is not None:
- # error: Incompatible return value type (got "Type[ExtensionDtype]",
- # expected "Union[dtype, ExtensionDtype]")
- return result # type: ignore[return-value]
+ return result
# try a numpy dtype
# raise a consistent TypeError if failed
| Simplifying #40421 to just fix up typing in the registry for Extension Dtypes, and return type for `construct_from_string` in `pandas/core/dtypes/base.py`
| https://api.github.com/repos/pandas-dev/pandas/pulls/41203 | 2021-04-28T18:51:18Z | 2021-08-03T15:59:52Z | 2021-08-03T15:59:51Z | 2023-02-13T20:51:11Z |
BUG: make_block with dt64tz-1d #41168 | diff --git a/pandas/core/internals/api.py b/pandas/core/internals/api.py
index 2f8686fd38929..37e07af71213e 100644
--- a/pandas/core/internals/api.py
+++ b/pandas/core/internals/api.py
@@ -19,6 +19,7 @@
)
from pandas.core.arrays import DatetimeArray
+from pandas.core.construction import extract_array
from pandas.core.internals.blocks import (
Block,
DatetimeTZBlock,
@@ -49,7 +50,6 @@ def make_block(
values, dtype = extract_pandas_array(values, dtype, ndim)
- needs_reshape = False
if klass is None:
dtype = dtype or values.dtype
klass = get_block_type(values, dtype)
@@ -57,13 +57,14 @@ def make_block(
elif klass is DatetimeTZBlock and not is_datetime64tz_dtype(values.dtype):
# pyarrow calls get here
values = DatetimeArray._simple_new(values, dtype=dtype)
- needs_reshape = True
if not isinstance(placement, BlockPlacement):
placement = BlockPlacement(placement)
ndim = maybe_infer_ndim(values, placement, ndim)
- if needs_reshape:
+ if is_datetime64tz_dtype(values.dtype):
+ # GH#41168 ensure we can pass 1D dt64tz values
+ values = extract_array(values, extract_numpy=True)
values = ensure_block_shape(values, ndim)
check_ndim(values, placement, ndim)
diff --git a/pandas/tests/internals/test_api.py b/pandas/tests/internals/test_api.py
index 0062d5aa34319..21299d76eaf5a 100644
--- a/pandas/tests/internals/test_api.py
+++ b/pandas/tests/internals/test_api.py
@@ -3,6 +3,7 @@
in core.internals
"""
+import pandas as pd
from pandas.core import internals
from pandas.core.internals import api
@@ -44,3 +45,12 @@ def test_namespace():
result = [x for x in dir(internals) if not x.startswith("__")]
assert set(result) == set(expected + modules)
+
+
+def test_make_block_2d_with_dti():
+ # GH#41168
+ dti = pd.date_range("2012", periods=3, tz="UTC")
+ blk = api.make_block(dti, placement=[0])
+
+ assert blk.shape == (1, 3)
+ assert blk.values.shape == (1, 3)
| - [x] closes #41168
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41202 | 2021-04-28T18:40:14Z | 2021-04-30T20:36:56Z | 2021-04-30T20:36:56Z | 2021-04-30T21:32:35Z |
TYP: io.parsers | diff --git a/pandas/_libs/parsers.pyi b/pandas/_libs/parsers.pyi
index 18ae23e7fb90d..92b970d47467e 100644
--- a/pandas/_libs/parsers.pyi
+++ b/pandas/_libs/parsers.pyi
@@ -31,8 +31,8 @@ class TextReader:
source,
delimiter: bytes | str = ..., # single-character only
header=...,
- header_start=...,
- header_end=...,
+ header_start: int = ..., # int64_t
+ header_end: int = ..., # uint64_t
index_col=...,
names=...,
tokenize_chunksize: int = ..., # int64_t
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index 2abb7e0ea3ac2..8d9f1773590b0 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -101,13 +101,13 @@ from pandas.errors import (
from pandas.core.dtypes.common import (
is_bool_dtype,
- is_categorical_dtype,
is_datetime64_dtype,
is_extension_array_dtype,
is_float_dtype,
is_integer_dtype,
is_object_dtype,
)
+from pandas.core.dtypes.dtypes import CategoricalDtype
cdef:
float64_t INF = <float64_t>np.inf
@@ -305,35 +305,36 @@ cdef class TextReader:
object na_fvalues
object true_values, false_values
object handle
+ object orig_header
bint na_filter, keep_default_na, verbose, has_usecols, has_mi_columns
- uint64_t parser_start
+ bint mangle_dupe_cols, allow_leading_cols
+ uint64_t parser_start # this is modified after __init__
list clocks
const char *encoding_errors
kh_str_starts_t *false_set
kh_str_starts_t *true_set
+ int64_t buffer_lines, skipfooter
+ list dtype_cast_order # list[np.dtype]
+ list names # can be None
+ set noconvert # set[int]
cdef public:
- int64_t leading_cols, table_width, skipfooter, buffer_lines
- bint allow_leading_cols, mangle_dupe_cols
- bint delim_whitespace
+ int64_t leading_cols, table_width
object delimiter # bytes or str
object converters
object na_values
- object orig_header, names, header_start, header_end
list header # list[list[non-negative integers]]
object index_col
object skiprows
object dtype
object usecols
- list dtype_cast_order # list[np.dtype]
set unnamed_cols # set[str]
- set noconvert # set[int]
def __cinit__(self, source,
delimiter=b',', # bytes | str
header=0,
- header_start=0,
- header_end=0,
+ int64_t header_start=0,
+ uint64_t header_end=0,
index_col=None,
names=None,
tokenize_chunksize=DEFAULT_CHUNKSIZE,
@@ -457,7 +458,6 @@ cdef class TextReader:
self.parser.warn_bad_lines = 0
self.delimiter = delimiter
- self.delim_whitespace = delim_whitespace
self.na_values = na_values
if na_fvalues is None:
@@ -502,7 +502,7 @@ cdef class TextReader:
# header stuff
self.allow_leading_cols = allow_leading_cols
- self.leading_cols = 0
+ self.leading_cols = 0 # updated in _get_header
# TODO: no header vs. header is not the first row
self.has_mi_columns = 0
@@ -535,10 +535,11 @@ cdef class TextReader:
self.parser.header_end = header
self.parser_start = header + 1
self.parser.header = header
- prelim_header = [ header ]
+ prelim_header = [header]
self.names = names
header, table_width, unnamed_cols = self._get_header(prelim_header)
+ # header, table_width, and unnamed_cols are set here, never changed
self.header = header
self.table_width = table_width
self.unnamed_cols = unnamed_cols
@@ -618,6 +619,11 @@ cdef class TextReader:
cdef _get_header(self, list prelim_header):
# header is now a list of lists, so field_count should use header[0]
+ #
+ # modifies:
+ # self.parser attributes
+ # self.parser_start
+ # self.leading_cols
cdef:
Py_ssize_t i, start, field_count, passed_count, unnamed_count, level
@@ -710,7 +716,7 @@ cdef class TextReader:
header.append(this_header)
if self.names is not None:
- header = [ self.names ]
+ header = [self.names]
elif self.names is not None:
# Enforce this unless usecols
@@ -721,7 +727,7 @@ cdef class TextReader:
if self.parser.lines < 1:
self._tokenize_rows(1)
- header = [ self.names ]
+ header = [self.names]
if self.parser.lines < 1:
field_count = len(header[0])
@@ -778,7 +784,7 @@ cdef class TextReader:
"""
# Conserve intermediate space
# Caller is responsible for concatenating chunks,
- # see c_parser_wrapper._concatenatve_chunks
+ # see c_parser_wrapper._concatenate_chunks
cdef:
size_t rows_read = 0
list chunks = []
@@ -885,7 +891,7 @@ cdef class TextReader:
cdef _start_clock(self):
self.clocks.append(time.time())
- cdef _end_clock(self, what):
+ cdef _end_clock(self, str what):
if self.verbose:
elapsed = time.time() - self.clocks.pop(-1)
print(f'{what} took: {elapsed * 1000:.2f} ms')
@@ -1090,7 +1096,7 @@ cdef class TextReader:
bint user_dtype,
kh_str_starts_t *na_hashset,
object na_flist):
- if is_categorical_dtype(dtype):
+ if isinstance(dtype, CategoricalDtype):
# TODO: I suspect that _categorical_convert could be
# optimized when dtype is an instance of CategoricalDtype
codes, cats, na_count = _categorical_convert(
@@ -1205,6 +1211,7 @@ cdef class TextReader:
return self.converters.get(i)
cdef _get_na_list(self, Py_ssize_t i, name):
+ # Note: updates self.na_values, self.na_fvalues
if self.na_values is None:
return None, set()
diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py
index a011a789bf17c..8ab845868285c 100644
--- a/pandas/io/parsers/base_parser.py
+++ b/pandas/io/parsers/base_parser.py
@@ -4,6 +4,7 @@
import itertools
from typing import (
Any,
+ Callable,
DefaultDict,
Dict,
Iterable,
@@ -27,6 +28,7 @@
from pandas._typing import (
DtypeArg,
FilePathOrBuffer,
+ final,
)
from pandas.errors import (
ParserError,
@@ -114,6 +116,9 @@
class ParserBase:
+ _implicit_index: bool = False
+ _first_chunk: bool
+
def __init__(self, kwds):
self.names = kwds.get("names")
@@ -268,15 +273,17 @@ def close(self):
if self.handles is not None:
self.handles.close()
+ @final
@property
- def _has_complex_date_col(self):
+ def _has_complex_date_col(self) -> bool:
return isinstance(self.parse_dates, dict) or (
isinstance(self.parse_dates, list)
and len(self.parse_dates) > 0
and isinstance(self.parse_dates[0], list)
)
- def _should_parse_dates(self, i):
+ @final
+ def _should_parse_dates(self, i: int) -> bool:
if isinstance(self.parse_dates, bool):
return self.parse_dates
else:
@@ -295,8 +302,9 @@ def _should_parse_dates(self, i):
name is not None and name in self.parse_dates
)
+ @final
def _extract_multi_indexer_columns(
- self, header, index_names, col_names, passed_names=False
+ self, header, index_names, col_names, passed_names: bool = False
):
"""
extract and return the names, index_names, col_names
@@ -354,6 +362,7 @@ def extract(r):
return names, index_names, col_names, passed_names
+ @final
def _maybe_dedup_names(self, names):
# see gh-7160 and gh-9424: this helps to provide
# immediate alleviation of the duplicate names
@@ -382,12 +391,14 @@ def _maybe_dedup_names(self, names):
return names
+ @final
def _maybe_make_multi_index_columns(self, columns, col_names=None):
# possibly create a column mi here
if _is_potential_multi_index(columns):
columns = MultiIndex.from_tuples(columns, names=col_names)
return columns
+ @final
def _make_index(self, data, alldata, columns, indexnamerow=False):
if not is_index_col(self.index_col) or not self.index_col:
index = None
@@ -415,8 +426,7 @@ def _make_index(self, data, alldata, columns, indexnamerow=False):
return index, columns
- _implicit_index = False
-
+ @final
def _get_simple_index(self, data, columns):
def ix(col):
if not isinstance(col, str):
@@ -439,6 +449,7 @@ def ix(col):
return index
+ @final
def _get_complex_date_index(self, data, col_names):
def _get_name(icol):
if isinstance(icol, str):
@@ -466,7 +477,8 @@ def _get_name(icol):
return index
- def _agg_index(self, index, try_parse_dates=True) -> Index:
+ @final
+ def _agg_index(self, index, try_parse_dates: bool = True) -> Index:
arrays = []
for i, arr in enumerate(index):
@@ -497,8 +509,15 @@ def _agg_index(self, index, try_parse_dates=True) -> Index:
return index
+ @final
def _convert_to_ndarrays(
- self, dct, na_values, na_fvalues, verbose=False, converters=None, dtypes=None
+ self,
+ dct: dict,
+ na_values,
+ na_fvalues,
+ verbose: bool = False,
+ converters=None,
+ dtypes=None,
):
result = {}
for c, values in dct.items():
@@ -575,6 +594,7 @@ def _convert_to_ndarrays(
print(f"Filled {na_count} NA values in column {c!s}")
return result
+ @final
def _set_noconvert_dtype_columns(
self, col_indices: List[int], names: List[Union[int, str, Tuple]]
) -> Set[int]:
@@ -1010,12 +1030,12 @@ def converter(*date_cols):
def _process_date_conversion(
data_dict,
- converter,
+ converter: Callable,
parse_spec,
index_col,
index_names,
columns,
- keep_date_col=False,
+ keep_date_col: bool = False,
):
def _isindex(colspec):
return (isinstance(index_col, list) and colspec in index_col) or (
@@ -1077,7 +1097,7 @@ def _isindex(colspec):
return data_dict, new_cols
-def _try_convert_dates(parser, colspec, data_dict, columns):
+def _try_convert_dates(parser: Callable, colspec, data_dict, columns):
colset = set(columns)
colnames = []
@@ -1131,21 +1151,9 @@ def _get_na_values(col, na_values, na_fvalues, keep_default_na):
return na_values, na_fvalues
-# Seems to be unused
-def _get_col_names(colspec, columns):
- colset = set(columns)
- colnames = []
- for c in colspec:
- if c in colset:
- colnames.append(c)
- elif isinstance(c, int):
- colnames.append(columns[c])
- return colnames
-
-
def _is_potential_multi_index(
columns, index_col: Optional[Union[bool, Sequence[int]]] = None
-):
+) -> bool:
"""
Check whether or not the `columns` parameter
could be converted into a MultiIndex.
@@ -1159,12 +1167,12 @@ def _is_potential_multi_index(
Returns
-------
- boolean : Whether or not columns could become a MultiIndex
+ bool : Whether or not columns could become a MultiIndex
"""
if index_col is None or isinstance(index_col, bool):
index_col = []
- return (
+ return bool(
len(columns)
and not isinstance(columns, MultiIndex)
and all(isinstance(c, tuple) for c in columns if c not in list(index_col))
@@ -1193,5 +1201,5 @@ def _validate_parse_dates_arg(parse_dates):
return parse_dates
-def is_index_col(col):
+def is_index_col(col) -> bool:
return col is not None and col is not False
diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py
index fbf2a53207f75..7a0e704d2fbc4 100644
--- a/pandas/io/parsers/c_parser_wrapper.py
+++ b/pandas/io/parsers/c_parser_wrapper.py
@@ -28,6 +28,7 @@
class CParserWrapper(ParserBase):
low_memory: bool
+ _reader: parsers.TextReader
def __init__(self, src: FilePathOrBuffer, **kwds):
self.kwds = kwds
@@ -58,6 +59,7 @@ def __init__(self, src: FilePathOrBuffer, **kwds):
except Exception:
self.handles.close()
raise
+
self.unnamed_cols = self._reader.unnamed_cols
# error: Cannot determine type of 'names'
@@ -217,8 +219,7 @@ def read(self, nrows=None):
else:
data = self._reader.read(nrows)
except StopIteration:
- # error: Cannot determine type of '_first_chunk'
- if self._first_chunk: # type: ignore[has-type]
+ if self._first_chunk:
self._first_chunk = False
names = self._maybe_dedup_names(self.orig_names)
index, columns, col_dict = self._get_empty_meta(
@@ -322,7 +323,7 @@ def _get_index_names(self):
return names, idx_names
- def _maybe_parse_dates(self, values, index: int, try_parse_dates=True):
+ def _maybe_parse_dates(self, values, index: int, try_parse_dates: bool = True):
if try_parse_dates and self._should_parse_dates(index):
values = self._date_conv(values)
return values
diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index a6d38eab99977..0055f3123f3c0 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -250,8 +250,7 @@ def read(self, rows=None):
try:
content = self._get_lines(rows)
except StopIteration:
- # error: Cannot determine type of '_first_chunk'
- if self._first_chunk: # type: ignore[has-type]
+ if self._first_chunk:
content = []
else:
self.close()
@@ -1195,7 +1194,7 @@ def count_empty_vals(vals) -> int:
return sum(1 for v in vals if v == "" or v is None)
-def _validate_skipfooter_arg(skipfooter):
+def _validate_skipfooter_arg(skipfooter: int) -> int:
"""
Validate the 'skipfooter' parameter.
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41201 | 2021-04-28T17:23:42Z | 2021-05-05T13:00:22Z | 2021-05-05T13:00:22Z | 2021-05-05T14:54:58Z |
REF: move DataFrame-specific methods from NDFrame | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 8ac94111cca56..4469869a5a929 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -10454,6 +10454,107 @@ def _AXIS_NAMES(self) -> dict[int, str]:
boxplot = pandas.plotting.boxplot_frame
sparse = CachedAccessor("sparse", SparseFrameAccessor)
+ # ----------------------------------------------------------------------
+ # Internal Interface Methods
+
+ def _to_dict_of_blocks(self, copy: bool = True):
+ """
+ Return a dict of dtype -> Constructor Types that
+ each is a homogeneous dtype.
+
+ Internal ONLY - only works for BlockManager
+ """
+ mgr = self._mgr
+ # convert to BlockManager if needed -> this way support ArrayManager as well
+ mgr = mgr_to_mgr(mgr, "block")
+ mgr = cast(BlockManager, mgr)
+ return {
+ k: self._constructor(v).__finalize__(self)
+ for k, v, in mgr.to_dict(copy=copy).items()
+ }
+
+ @property
+ def values(self) -> np.ndarray:
+ """
+ Return a Numpy representation of the DataFrame.
+
+ .. warning::
+
+ We recommend using :meth:`DataFrame.to_numpy` instead.
+
+ Only the values in the DataFrame will be returned, the axes labels
+ will be removed.
+
+ Returns
+ -------
+ numpy.ndarray
+ The values of the DataFrame.
+
+ See Also
+ --------
+ DataFrame.to_numpy : Recommended alternative to this method.
+ DataFrame.index : Retrieve the index labels.
+ DataFrame.columns : Retrieving the column names.
+
+ Notes
+ -----
+ The dtype will be a lower-common-denominator dtype (implicit
+ upcasting); that is to say if the dtypes (even of numeric types)
+ are mixed, the one that accommodates all will be chosen. Use this
+ with care if you are not dealing with the blocks.
+
+ e.g. If the dtypes are float16 and float32, dtype will be upcast to
+ float32. If dtypes are int32 and uint8, dtype will be upcast to
+ int32. By :func:`numpy.find_common_type` convention, mixing int64
+ and uint64 will result in a float64 dtype.
+
+ Examples
+ --------
+ A DataFrame where all columns are the same type (e.g., int64) results
+ in an array of the same type.
+
+ >>> df = pd.DataFrame({'age': [ 3, 29],
+ ... 'height': [94, 170],
+ ... 'weight': [31, 115]})
+ >>> df
+ age height weight
+ 0 3 94 31
+ 1 29 170 115
+ >>> df.dtypes
+ age int64
+ height int64
+ weight int64
+ dtype: object
+ >>> df.values
+ array([[ 3, 94, 31],
+ [ 29, 170, 115]])
+
+ A DataFrame with mixed type columns(e.g., str/object, int64, float32)
+ results in an ndarray of the broadest type that accommodates these
+ mixed types (e.g., object).
+
+ >>> df2 = pd.DataFrame([('parrot', 24.0, 'second'),
+ ... ('lion', 80.5, 1),
+ ... ('monkey', np.nan, None)],
+ ... columns=('name', 'max_speed', 'rank'))
+ >>> df2.dtypes
+ name object
+ max_speed float64
+ rank object
+ dtype: object
+ >>> df2.values
+ array([['parrot', 24.0, 'second'],
+ ['lion', 80.5, 1],
+ ['monkey', nan, None]], dtype=object)
+ """
+ self._consolidate_inplace()
+ return self._mgr.as_array(transpose=True)
+
+ @property
+ def _values(self) -> np.ndarray:
+ """internal implementation"""
+ return self.values
+
DataFrame._add_numeric_operations()
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index eba4a36315ba4..35f29bdedf639 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5614,85 +5614,12 @@ def _get_bool_data(self):
@property
def values(self) -> np.ndarray:
- """
- Return a Numpy representation of the DataFrame.
-
- .. warning::
-
- We recommend using :meth:`DataFrame.to_numpy` instead.
-
- Only the values in the DataFrame will be returned, the axes labels
- will be removed.
-
- Returns
- -------
- numpy.ndarray
- The values of the DataFrame.
-
- See Also
- --------
- DataFrame.to_numpy : Recommended alternative to this method.
- DataFrame.index : Retrieve the index labels.
- DataFrame.columns : Retrieving the column names.
-
- Notes
- -----
- The dtype will be a lower-common-denominator dtype (implicit
- upcasting); that is to say if the dtypes (even of numeric types)
- are mixed, the one that accommodates all will be chosen. Use this
- with care if you are not dealing with the blocks.
-
- e.g. If the dtypes are float16 and float32, dtype will be upcast to
- float32. If dtypes are int32 and uint8, dtype will be upcast to
- int32. By :func:`numpy.find_common_type` convention, mixing int64
- and uint64 will result in a float64 dtype.
-
- Examples
- --------
- A DataFrame where all columns are the same type (e.g., int64) results
- in an array of the same type.
-
- >>> df = pd.DataFrame({'age': [ 3, 29],
- ... 'height': [94, 170],
- ... 'weight': [31, 115]})
- >>> df
- age height weight
- 0 3 94 31
- 1 29 170 115
- >>> df.dtypes
- age int64
- height int64
- weight int64
- dtype: object
- >>> df.values
- array([[ 3, 94, 31],
- [ 29, 170, 115]])
-
- A DataFrame with mixed type columns(e.g., str/object, int64, float32)
- results in an ndarray of the broadest type that accommodates these
- mixed types (e.g., object).
-
- >>> df2 = pd.DataFrame([('parrot', 24.0, 'second'),
- ... ('lion', 80.5, 1),
- ... ('monkey', np.nan, None)],
- ... columns=('name', 'max_speed', 'rank'))
- >>> df2.dtypes
- name object
- max_speed float64
- rank object
- dtype: object
- >>> df2.values
- array([['parrot', 24.0, 'second'],
- ['lion', 80.5, 1],
- ['monkey', nan, None]], dtype=object)
- """
- self._consolidate_inplace()
- return self._mgr.as_array(transpose=self._AXIS_REVERSED)
+ raise AbstractMethodError(self)
@property
def _values(self) -> np.ndarray:
"""internal implementation"""
- return self.values
+ raise AbstractMethodError(self)
@property
def dtypes(self):
@@ -5725,23 +5652,6 @@ def dtypes(self):
data = self._mgr.get_dtypes()
return self._constructor_sliced(data, index=self._info_axis, dtype=np.object_)
- @final
- def _to_dict_of_blocks(self, copy: bool_t = True):
- """
- Return a dict of dtype -> Constructor Types that
- each is a homogeneous dtype.
-
- Internal ONLY - only works for BlockManager
- """
- mgr = self._mgr
- # convert to BlockManager if needed -> this way support ArrayManager as well
- mgr = mgr_to_mgr(mgr, "block")
- mgr = cast(BlockManager, mgr)
- return {
- k: self._constructor(v).__finalize__(self)
- for k, v, in mgr.to_dict(copy=copy).items()
- }
-
def astype(
self: FrameOrSeries, dtype, copy: bool_t = True, errors: str = "raise"
) -> FrameOrSeries:
diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index a25750e7e1eab..ff76228646a02 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -201,47 +201,6 @@ def __repr__(self) -> str:
output += f"\n{arr.dtype}"
return output
- def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T:
- """
- Apply grouped reduction function columnwise, returning a new ArrayManager.
-
- Parameters
- ----------
- func : grouped reduction function
- ignore_failures : bool, default False
- Whether to drop columns where func raises TypeError.
-
- Returns
- -------
- ArrayManager
- """
- result_arrays: list[np.ndarray] = []
- result_indices: list[int] = []
-
- for i, arr in enumerate(self.arrays):
- try:
- res = func(arr)
- except (TypeError, NotImplementedError):
- if not ignore_failures:
- raise
- continue
- result_arrays.append(res)
- result_indices.append(i)
-
- if len(result_arrays) == 0:
- index = Index([None]) # placeholder
- else:
- index = Index(range(result_arrays[0].shape[0]))
-
- if ignore_failures:
- columns = self.items[np.array(result_indices, dtype="int64")]
- else:
- columns = self.items
-
- # error: Argument 1 to "ArrayManager" has incompatible type "List[ndarray]";
- # expected "List[Union[ndarray, ExtensionArray]]"
- return type(self)(result_arrays, [index, columns]) # type: ignore[arg-type]
-
def apply(
self: T,
f,
@@ -322,25 +281,6 @@ def apply(
# expected "List[Union[ndarray, ExtensionArray]]"
return type(self)(result_arrays, new_axes) # type: ignore[arg-type]
- def apply_2d(self: T, f, ignore_failures: bool = False, **kwargs) -> T:
- """
- Variant of `apply`, but where the function should not be applied to
- each column independently, but to the full data as a 2D array.
- """
- values = self.as_array()
- try:
- result = f(values, **kwargs)
- except (TypeError, NotImplementedError):
- if not ignore_failures:
- raise
- result_arrays = []
- new_axes = [self._axes[0], self.axes[1].take([])]
- else:
- result_arrays = [result[:, i] for i in range(len(self._axes[1]))]
- new_axes = self._axes
-
- return type(self)(result_arrays, new_axes)
-
def apply_with_block(self: T, f, align_keys=None, swap_axis=True, **kwargs) -> T:
# switch axis to follow BlockManager logic
if swap_axis and "axis" in kwargs and self.ndim == 2:
@@ -606,67 +546,6 @@ def copy_func(ax):
new_arrays = self.arrays
return type(self)(new_arrays, new_axes)
- def as_array(
- self,
- transpose: bool = False,
- dtype=None,
- copy: bool = False,
- na_value=lib.no_default,
- ) -> np.ndarray:
- """
- Convert the blockmanager data into an numpy array.
-
- Parameters
- ----------
- transpose : bool, default False
- If True, transpose the return array.
- dtype : object, default None
- Data type of the return array.
- copy : bool, default False
- If True then guarantee that a copy is returned. A value of
- False does not guarantee that the underlying data is not
- copied.
- na_value : object, default lib.no_default
- Value to be used as the missing value sentinel.
-
- Returns
- -------
- arr : ndarray
- """
- if len(self.arrays) == 0:
- arr = np.empty(self.shape, dtype=float)
- return arr.transpose() if transpose else arr
-
- # We want to copy when na_value is provided to avoid
- # mutating the original object
- copy = copy or na_value is not lib.no_default
-
- if not dtype:
- dtype = interleaved_dtype([arr.dtype for arr in self.arrays])
-
- if isinstance(dtype, SparseDtype):
- dtype = dtype.subtype
- elif isinstance(dtype, PandasDtype):
- dtype = dtype.numpy_dtype
- elif is_extension_array_dtype(dtype):
- dtype = "object"
- elif is_dtype_equal(dtype, str):
- dtype = "object"
-
- result = np.empty(self.shape_proper, dtype=dtype)
-
- # error: Incompatible types in assignment (expression has type "Union[ndarray,
- # ExtensionArray]", variable has type "ndarray")
- for i, arr in enumerate(self.arrays): # type: ignore[assignment]
- arr = arr.astype(dtype, copy=copy)
- result[:, i] = arr
-
- if na_value is not lib.no_default:
- result[isna(result)] = na_value
-
- return result
- # return arr.transpose() if transpose else arr
-
def reindex_indexer(
self: T,
new_axis,
@@ -1035,6 +914,47 @@ def idelete(self, indexer):
# --------------------------------------------------------------------
# Array-wise Operation
+ def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T:
+ """
+ Apply grouped reduction function columnwise, returning a new ArrayManager.
+
+ Parameters
+ ----------
+ func : grouped reduction function
+ ignore_failures : bool, default False
+ Whether to drop columns where func raises TypeError.
+
+ Returns
+ -------
+ ArrayManager
+ """
+ result_arrays: list[np.ndarray] = []
+ result_indices: list[int] = []
+
+ for i, arr in enumerate(self.arrays):
+ try:
+ res = func(arr)
+ except (TypeError, NotImplementedError):
+ if not ignore_failures:
+ raise
+ continue
+ result_arrays.append(res)
+ result_indices.append(i)
+
+ if len(result_arrays) == 0:
+ index = Index([None]) # placeholder
+ else:
+ index = Index(range(result_arrays[0].shape[0]))
+
+ if ignore_failures:
+ columns = self.items[np.array(result_indices, dtype="int64")]
+ else:
+ columns = self.items
+
+ # error: Argument 1 to "ArrayManager" has incompatible type "List[ndarray]";
+ # expected "List[Union[ndarray, ExtensionArray]]"
+ return type(self)(result_arrays, [index, columns]) # type: ignore[arg-type]
+
def reduce(
self: T, func: Callable, ignore_failures: bool = False
) -> tuple[T, np.ndarray]:
@@ -1122,6 +1042,27 @@ def quantile(
axes = [qs, self._axes[1]]
return type(self)(new_arrs, axes)
+ def apply_2d(
+ self: ArrayManager, f, ignore_failures: bool = False, **kwargs
+ ) -> ArrayManager:
+ """
+ Variant of `apply`, but where the function should not be applied to
+ each column independently, but to the full data as a 2D array.
+ """
+ values = self.as_array()
+ try:
+ result = f(values, **kwargs)
+ except (TypeError, NotImplementedError):
+ if not ignore_failures:
+ raise
+ result_arrays = []
+ new_axes = [self._axes[0], self.axes[1].take([])]
+ else:
+ result_arrays = [result[:, i] for i in range(len(self._axes[1]))]
+ new_axes = self._axes
+
+ return type(self)(result_arrays, new_axes)
+
# ----------------------------------------------------------------
def unstack(self, unstacker, fill_value) -> ArrayManager:
@@ -1166,6 +1107,67 @@ def unstack(self, unstacker, fill_value) -> ArrayManager:
return type(self)(new_arrays, new_axes, verify_integrity=False)
+ def as_array(
+ self,
+ transpose: bool = False,
+ dtype=None,
+ copy: bool = False,
+ na_value=lib.no_default,
+ ) -> np.ndarray:
+ """
+ Convert the blockmanager data into an numpy array.
+
+ Parameters
+ ----------
+ transpose : bool, default False
+ If True, transpose the return array.
+ dtype : object, default None
+ Data type of the return array.
+ copy : bool, default False
+ If True then guarantee that a copy is returned. A value of
+ False does not guarantee that the underlying data is not
+ copied.
+ na_value : object, default lib.no_default
+ Value to be used as the missing value sentinel.
+
+ Returns
+ -------
+ arr : ndarray
+ """
+ if len(self.arrays) == 0:
+ arr = np.empty(self.shape, dtype=float)
+ return arr.transpose() if transpose else arr
+
+ # We want to copy when na_value is provided to avoid
+ # mutating the original object
+ copy = copy or na_value is not lib.no_default
+
+ if not dtype:
+ dtype = interleaved_dtype([arr.dtype for arr in self.arrays])
+
+ if isinstance(dtype, SparseDtype):
+ dtype = dtype.subtype
+ elif isinstance(dtype, PandasDtype):
+ dtype = dtype.numpy_dtype
+ elif is_extension_array_dtype(dtype):
+ dtype = "object"
+ elif is_dtype_equal(dtype, str):
+ dtype = "object"
+
+ result = np.empty(self.shape_proper, dtype=dtype)
+
+ # error: Incompatible types in assignment (expression has type "Union[ndarray,
+ # ExtensionArray]", variable has type "ndarray")
+ for i, arr in enumerate(self.arrays): # type: ignore[assignment]
+ arr = arr.astype(dtype, copy=copy)
+ result[:, i] = arr
+
+ if na_value is not lib.no_default:
+ result[isna(result)] = na_value
+
+ return result
+ # return arr.transpose() if transpose else arr
+
class SingleArrayManager(BaseArrayManager, SingleDataManager):
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index bf81ac529d678..eac2579e7dfa5 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -284,53 +284,6 @@ def __repr__(self) -> str:
output += f"\n{block}"
return output
- def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T:
- """
- Apply grouped reduction function blockwise, returning a new BlockManager.
-
- Parameters
- ----------
- func : grouped reduction function
- ignore_failures : bool, default False
- Whether to drop blocks where func raises TypeError.
-
- Returns
- -------
- BlockManager
- """
- result_blocks: list[Block] = []
-
- for blk in self.blocks:
- if blk.is_object:
- # split on object-dtype blocks bc some columns may raise
- # while others do not.
- for sb in blk._split():
- try:
- applied = sb.apply(func)
- except (TypeError, NotImplementedError):
- if not ignore_failures:
- raise
- continue
- result_blocks = extend_blocks(applied, result_blocks)
- else:
- try:
- applied = blk.apply(func)
- except (TypeError, NotImplementedError):
- if not ignore_failures:
- raise
- continue
- result_blocks = extend_blocks(applied, result_blocks)
-
- if len(result_blocks) == 0:
- index = Index([None]) # placeholder
- else:
- index = Index(range(result_blocks[0].values.shape[-1]))
-
- if ignore_failures:
- return self._combine(result_blocks, index=index)
-
- return type(self).from_blocks(result_blocks, [self.axes[0], index])
-
def apply(
self: T,
f,
@@ -631,144 +584,6 @@ def copy_func(ax):
res.axes = new_axes
return res
- def as_array(
- self,
- transpose: bool = False,
- dtype: Dtype | None = None,
- copy: bool = False,
- na_value=lib.no_default,
- ) -> np.ndarray:
- """
- Convert the blockmanager data into an numpy array.
-
- Parameters
- ----------
- transpose : bool, default False
- If True, transpose the return array.
- dtype : object, default None
- Data type of the return array.
- copy : bool, default False
- If True then guarantee that a copy is returned. A value of
- False does not guarantee that the underlying data is not
- copied.
- na_value : object, default lib.no_default
- Value to be used as the missing value sentinel.
-
- Returns
- -------
- arr : ndarray
- """
- if len(self.blocks) == 0:
- arr = np.empty(self.shape, dtype=float)
- return arr.transpose() if transpose else arr
-
- # We want to copy when na_value is provided to avoid
- # mutating the original object
- copy = copy or na_value is not lib.no_default
-
- if self.is_single_block:
- blk = self.blocks[0]
- if blk.is_extension:
- # Avoid implicit conversion of extension blocks to object
-
- # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no
- # attribute "to_numpy"
- arr = blk.values.to_numpy( # type: ignore[union-attr]
- dtype=dtype, na_value=na_value
- ).reshape(blk.shape)
- else:
- arr = np.asarray(blk.get_values())
- if dtype:
- # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has
- # incompatible type "Union[ExtensionDtype, str, dtype[Any],
- # Type[object]]"; expected "Union[dtype[Any], None, type,
- # _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int,
- # Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]"
- arr = arr.astype(dtype, copy=False) # type: ignore[arg-type]
- else:
- arr = self._interleave(dtype=dtype, na_value=na_value)
- # The underlying data was copied within _interleave
- copy = False
-
- if copy:
- arr = arr.copy()
-
- if na_value is not lib.no_default:
- arr[isna(arr)] = na_value
-
- return arr.transpose() if transpose else arr
-
- def _interleave(
- self, dtype: Dtype | None = None, na_value=lib.no_default
- ) -> np.ndarray:
- """
- Return ndarray from blocks with specified item order
- Items must be contained in the blocks
- """
- if not dtype:
- dtype = interleaved_dtype([blk.dtype for blk in self.blocks])
-
- # TODO: https://github.com/pandas-dev/pandas/issues/22791
- # Give EAs some input on what happens here. Sparse needs this.
- if isinstance(dtype, SparseDtype):
- dtype = dtype.subtype
- elif isinstance(dtype, ExtensionDtype):
- dtype = "object"
- elif is_dtype_equal(dtype, str):
- dtype = "object"
-
- # error: Argument "dtype" to "empty" has incompatible type
- # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected
- # "Union[dtype[Any], None, type, _SupportsDType, str, Union[Tuple[Any, int],
- # Tuple[Any, Union[int, Sequence[int]]], List[Any], _DTypeDict,
- # Tuple[Any, Any]]]"
- result = np.empty(self.shape, dtype=dtype) # type: ignore[arg-type]
-
- itemmask = np.zeros(self.shape[0])
-
- for blk in self.blocks:
- rl = blk.mgr_locs
- if blk.is_extension:
- # Avoid implicit conversion of extension blocks to object
-
- # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no
- # attribute "to_numpy"
- arr = blk.values.to_numpy( # type: ignore[union-attr]
- dtype=dtype, na_value=na_value
- )
- else:
- # error: Argument 1 to "get_values" of "Block" has incompatible type
- # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected
- # "Union[dtype[Any], ExtensionDtype, None]"
- arr = blk.get_values(dtype) # type: ignore[arg-type]
- result[rl.indexer] = arr
- itemmask[rl.indexer] = 1
-
- if not itemmask.all():
- raise AssertionError("Some items were not contained in blocks")
-
- return result
-
- def to_dict(self, copy: bool = True):
- """
- Return a dict of str(dtype) -> BlockManager
-
- Parameters
- ----------
- copy : bool, default True
-
- Returns
- -------
- values : a dict of dtype -> BlockManager
- """
-
- bd: dict[str, list[Block]] = {}
- for b in self.blocks:
- bd.setdefault(str(b.dtype), []).append(b)
-
- # TODO(EA2D): the combine will be unnecessary with 2D EAs
- return {dtype: self._combine(blocks, copy=copy) for dtype, blocks in bd.items()}
-
def consolidate(self: T) -> T:
"""
Join together blocks having same dtype
@@ -1375,6 +1190,53 @@ def idelete(self, indexer) -> BlockManager:
# ----------------------------------------------------------------
# Block-wise Operation
+ def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T:
+ """
+ Apply grouped reduction function blockwise, returning a new BlockManager.
+
+ Parameters
+ ----------
+ func : grouped reduction function
+ ignore_failures : bool, default False
+ Whether to drop blocks where func raises TypeError.
+
+ Returns
+ -------
+ BlockManager
+ """
+ result_blocks: list[Block] = []
+
+ for blk in self.blocks:
+ if blk.is_object:
+ # split on object-dtype blocks bc some columns may raise
+ # while others do not.
+ for sb in blk._split():
+ try:
+ applied = sb.apply(func)
+ except (TypeError, NotImplementedError):
+ if not ignore_failures:
+ raise
+ continue
+ result_blocks = extend_blocks(applied, result_blocks)
+ else:
+ try:
+ applied = blk.apply(func)
+ except (TypeError, NotImplementedError):
+ if not ignore_failures:
+ raise
+ continue
+ result_blocks = extend_blocks(applied, result_blocks)
+
+ if len(result_blocks) == 0:
+ index = Index([None]) # placeholder
+ else:
+ index = Index(range(result_blocks[0].values.shape[-1]))
+
+ if ignore_failures:
+ return self._combine(result_blocks, index=index)
+
+ return type(self).from_blocks(result_blocks, [self.axes[0], index])
+
def reduce(
self: T, func: Callable, ignore_failures: bool = False
) -> tuple[T, np.ndarray]:
@@ -1506,6 +1368,144 @@ def unstack(self, unstacker, fill_value) -> BlockManager:
bm = BlockManager(new_blocks, [new_columns, new_index])
return bm
+ def to_dict(self, copy: bool = True):
+ """
+ Return a dict of str(dtype) -> BlockManager
+
+ Parameters
+ ----------
+ copy : bool, default True
+
+ Returns
+ -------
+ values : a dict of dtype -> BlockManager
+ """
+
+ bd: dict[str, list[Block]] = {}
+ for b in self.blocks:
+ bd.setdefault(str(b.dtype), []).append(b)
+
+ # TODO(EA2D): the combine will be unnecessary with 2D EAs
+ return {dtype: self._combine(blocks, copy=copy) for dtype, blocks in bd.items()}
+
+ def as_array(
+ self,
+ transpose: bool = False,
+ dtype: Dtype | None = None,
+ copy: bool = False,
+ na_value=lib.no_default,
+ ) -> np.ndarray:
+ """
+ Convert the blockmanager data into an numpy array.
+
+ Parameters
+ ----------
+ transpose : bool, default False
+ If True, transpose the return array.
+ dtype : object, default None
+ Data type of the return array.
+ copy : bool, default False
+ If True then guarantee that a copy is returned. A value of
+ False does not guarantee that the underlying data is not
+ copied.
+ na_value : object, default lib.no_default
+ Value to be used as the missing value sentinel.
+
+ Returns
+ -------
+ arr : ndarray
+ """
+ if len(self.blocks) == 0:
+ arr = np.empty(self.shape, dtype=float)
+ return arr.transpose() if transpose else arr
+
+ # We want to copy when na_value is provided to avoid
+ # mutating the original object
+ copy = copy or na_value is not lib.no_default
+
+ if self.is_single_block:
+ blk = self.blocks[0]
+ if blk.is_extension:
+ # Avoid implicit conversion of extension blocks to object
+
+ # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no
+ # attribute "to_numpy"
+ arr = blk.values.to_numpy( # type: ignore[union-attr]
+ dtype=dtype, na_value=na_value
+ ).reshape(blk.shape)
+ else:
+ arr = np.asarray(blk.get_values())
+ if dtype:
+ # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has
+ # incompatible type "Union[ExtensionDtype, str, dtype[Any],
+ # Type[object]]"; expected "Union[dtype[Any], None, type,
+ # _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int,
+ # Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]"
+ arr = arr.astype(dtype, copy=False) # type: ignore[arg-type]
+ else:
+ arr = self._interleave(dtype=dtype, na_value=na_value)
+ # The underlying data was copied within _interleave
+ copy = False
+
+ if copy:
+ arr = arr.copy()
+
+ if na_value is not lib.no_default:
+ arr[isna(arr)] = na_value
+
+ return arr.transpose() if transpose else arr
+
+ def _interleave(
+ self, dtype: Dtype | None = None, na_value=lib.no_default
+ ) -> np.ndarray:
+ """
+ Return ndarray from blocks with specified item order
+ Items must be contained in the blocks
+ """
+ if not dtype:
+ dtype = interleaved_dtype([blk.dtype for blk in self.blocks])
+
+ # TODO: https://github.com/pandas-dev/pandas/issues/22791
+ # Give EAs some input on what happens here. Sparse needs this.
+ if isinstance(dtype, SparseDtype):
+ dtype = dtype.subtype
+ elif isinstance(dtype, ExtensionDtype):
+ dtype = "object"
+ elif is_dtype_equal(dtype, str):
+ dtype = "object"
+
+ # error: Argument "dtype" to "empty" has incompatible type
+ # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected
+ # "Union[dtype[Any], None, type, _SupportsDType, str, Union[Tuple[Any, int],
+ # Tuple[Any, Union[int, Sequence[int]]], List[Any], _DTypeDict,
+ # Tuple[Any, Any]]]"
+ result = np.empty(self.shape, dtype=dtype) # type: ignore[arg-type]
+
+ itemmask = np.zeros(self.shape[0])
+
+ for blk in self.blocks:
+ rl = blk.mgr_locs
+ if blk.is_extension:
+ # Avoid implicit conversion of extension blocks to object
+
+ # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no
+ # attribute "to_numpy"
+ arr = blk.values.to_numpy( # type: ignore[union-attr]
+ dtype=dtype, na_value=na_value
+ )
+ else:
+ # error: Argument 1 to "get_values" of "Block" has incompatible type
+ # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected
+ # "Union[dtype[Any], ExtensionDtype, None]"
+ arr = blk.get_values(dtype) # type: ignore[arg-type]
+ result[rl.indexer] = arr
+ itemmask[rl.indexer] = 1
+
+ if not itemmask.all():
+ raise AssertionError("Some items were not contained in blocks")
+
+ return result
+
class SingleBlockManager(BaseBlockManager, SingleDataManager):
""" manage a single block with """
diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index 3299503dbc3a4..08dba5aa76a2f 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -823,7 +823,7 @@ def test_equals_block_order_different_dtypes(self, mgr_string):
def test_single_mgr_ctor(self):
mgr = create_single_mgr("f8", num_rows=5)
- assert mgr.as_array().tolist() == [0.0, 1.0, 2.0, 3.0, 4.0]
+ assert mgr.external_values().tolist() == [0.0, 1.0, 2.0, 3.0, 4.0]
@pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
def test_validate_bool_args(self, value):
@@ -837,6 +837,12 @@ def test_validate_bool_args(self, value):
bm1.replace_list([1], [2], inplace=value)
+def _as_array(mgr):
+ if mgr.ndim == 1:
+ return mgr.external_values()
+ return mgr.as_array()
+
+
class TestIndexing:
# Nosetests-style data-driven tests.
#
@@ -859,7 +865,7 @@ class TestIndexing:
@pytest.mark.parametrize("mgr", MANAGERS)
def test_get_slice(self, mgr):
def assert_slice_ok(mgr, axis, slobj):
- mat = mgr.as_array()
+ mat = _as_array(mgr)
# we maybe using an ndarray to test slicing and
# might not be the full length of the axis
@@ -881,7 +887,7 @@ def assert_slice_ok(mgr, axis, slobj):
mat_slobj = (slice(None),) * axis + (slobj,)
tm.assert_numpy_array_equal(
- mat[mat_slobj], sliced.as_array(), check_dtype=False
+ mat[mat_slobj], _as_array(sliced), check_dtype=False
)
tm.assert_index_equal(mgr.axes[axis][slobj], sliced.axes[axis])
@@ -919,10 +925,10 @@ def assert_slice_ok(mgr, axis, slobj):
@pytest.mark.parametrize("mgr", MANAGERS)
def test_take(self, mgr):
def assert_take_ok(mgr, axis, indexer):
- mat = mgr.as_array()
+ mat = _as_array(mgr)
taken = mgr.take(indexer, axis)
tm.assert_numpy_array_equal(
- np.take(mat, indexer, axis), taken.as_array(), check_dtype=False
+ np.take(mat, indexer, axis), _as_array(taken), check_dtype=False
)
tm.assert_index_equal(mgr.axes[axis].take(indexer), taken.axes[axis])
@@ -940,13 +946,13 @@ def assert_take_ok(mgr, axis, indexer):
@pytest.mark.parametrize("fill_value", [None, np.nan, 100.0])
def test_reindex_axis(self, fill_value, mgr):
def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value):
- mat = mgr.as_array()
+ mat = _as_array(mgr)
indexer = mgr.axes[axis].get_indexer_for(new_labels)
reindexed = mgr.reindex_axis(new_labels, axis, fill_value=fill_value)
tm.assert_numpy_array_equal(
algos.take_nd(mat, indexer, axis, fill_value=fill_value),
- reindexed.as_array(),
+ _as_array(reindexed),
check_dtype=False,
)
tm.assert_index_equal(reindexed.axes[axis], new_labels)
@@ -971,13 +977,13 @@ def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value):
@pytest.mark.parametrize("fill_value", [None, np.nan, 100.0])
def test_reindex_indexer(self, fill_value, mgr):
def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value):
- mat = mgr.as_array()
+ mat = _as_array(mgr)
reindexed_mat = algos.take_nd(mat, indexer, axis, fill_value=fill_value)
reindexed = mgr.reindex_indexer(
new_labels, indexer, axis, fill_value=fill_value
)
tm.assert_numpy_array_equal(
- reindexed_mat, reindexed.as_array(), check_dtype=False
+ reindexed_mat, _as_array(reindexed), check_dtype=False
)
tm.assert_index_equal(reindexed.axes[axis], new_labels)
| which in turn lets us do the same for BlockManager/ArrayManager | https://api.github.com/repos/pandas-dev/pandas/pulls/41200 | 2021-04-28T16:48:42Z | 2021-04-30T16:36:53Z | 2021-04-30T16:36:53Z | 2021-04-30T18:15:41Z |
BUG: Fix export .to_numpy() with nullable type | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index c44e667d84308..c9615a6f8f4ec 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -708,6 +708,7 @@ Conversion
- Bug in :func:`factorize` where, when given an array with a numeric numpy dtype lower than int64, uint64 and float64, the unique values did not keep their original dtype (:issue:`41132`)
- Bug in :class:`DataFrame` construction with a dictionary containing an arraylike with ``ExtensionDtype`` and ``copy=True`` failing to make a copy (:issue:`38939`)
- Bug in :meth:`qcut` raising error when taking ``Float64DType`` as input (:issue:`40730`)
+- Bug in :meth:`BaseMaskedArray.to_numpy` does not output ``numeric_dtype`` with ``numeric_dtype`` input (:issue:`40630`)
Strings
^^^^^^^
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 11f9f645920ec..30b703bb4885d 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -32,6 +32,8 @@
from pandas.core.dtypes.common import (
is_dtype_equal,
is_integer,
+ is_integer_dtype,
+ is_numeric_dtype,
is_object_dtype,
is_scalar,
is_string_dtype,
@@ -244,7 +246,12 @@ def to_numpy( # type: ignore[override]
Examples
--------
- An object-dtype is the default result
+ Other than numerical type input (int and float), object-dtype is
+ the default result
+
+ >>> a = pd.Series([1, 2, 3], dtype=pd.Int64Dtype())
+ >>> a.to_numpy()
+ array([1, 2, 3], dtype=int64)
>>> a = pd.array([True, False, pd.NA], dtype="boolean")
>>> a.to_numpy()
@@ -280,10 +287,27 @@ def to_numpy( # type: ignore[override]
if na_value is lib.no_default:
na_value = libmissing.NA
if dtype is None:
- # error: Incompatible types in assignment (expression has type
- # "Type[object]", variable has type "Union[str, dtype[Any], None]")
- dtype = object # type: ignore[assignment]
- if self._hasna:
+ if is_numeric_dtype(self):
+ dtype = self.dtype.numpy_dtype
+ else:
+ # error: Incompatible types in assignment (expression has type
+ # "Type[object]", variable has type "Union[str, dtype[Any], None]")
+ dtype = object # type: ignore[assignment]
+
+ if is_numeric_dtype(self):
+
+ # If there is NA and the data is of int type, a float
+ # is being returned as int type cannot support np.nan.
+ if is_integer_dtype(self) and self._hasna:
+ data = self._data.astype(float)
+ else:
+ data = self._data.astype(dtype)
+
+ # For numerical input, pd.na is replaced with np.nan
+ if self._hasna is True:
+ data[np.where(self._mask is True)] = np.nan
+
+ elif self._hasna:
if (
not is_object_dtype(dtype)
and not is_string_dtype(dtype)
diff --git a/pandas/tests/arrays/test_numpy.py b/pandas/tests/arrays/test_numpy.py
index 753ec99e683e6..6b6453607ca7b 100644
--- a/pandas/tests/arrays/test_numpy.py
+++ b/pandas/tests/arrays/test_numpy.py
@@ -154,6 +154,21 @@ def test_to_numpy():
tm.assert_numpy_array_equal(result, expected)
+@pytest.mark.parametrize(
+ "data_content,data_type,expected_result",
+ [
+ ([1, 2, 3], pd.Float64Dtype(), np.array([1, 2, 3], dtype=np.float64)),
+ ([1, 2, 3], "Int64", np.array([1, 2, 3], dtype=np.int64)),
+ ([1, 2, pd.NA], pd.Float64Dtype(), np.array([1, 2, np.nan], dtype=np.float64)),
+ ([1, 2, pd.NA], "Int64", np.array([1, 2, np.nan], dtype=np.float64)),
+ ],
+)
+def test_to_numpy_int_float(data_content, data_type, expected_result):
+ data = pd.Series(data_content, dtype=data_type)
+ actual_result = data.to_numpy()
+ assert np.array_equal(actual_result, expected_result, equal_nan=True)
+
+
# ----------------------------------------------------------------------------
# Setitem
| - [x] closes #40630
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41196 | 2021-04-28T14:44:14Z | 2021-05-20T17:03:22Z | null | 2021-05-20T17:03:22Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.