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 |
|---|---|---|---|---|---|---|---|
BUG: DatetimeIndex with non-nano values and freq='D' throws ValueError | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index bb21bed2dc779..816d8abec1428 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1897,7 +1897,12 @@ def _validate_frequency(cls, index, freq, **kwargs):
try:
on_freq = cls._generate_range(
- start=index[0], end=None, periods=len(index), freq=freq, **kwargs
+ start=index[0],
+ end=None,
+ periods=len(index),
+ freq=freq,
+ unit=index.unit,
+ **kwargs,
)
if not np.array_equal(index.asi8, on_freq.asi8):
raise ValueError
diff --git a/pandas/tests/frame/methods/test_asfreq.py b/pandas/tests/frame/methods/test_asfreq.py
index 5b3e1614e1ada..9fa9f27e7e312 100644
--- a/pandas/tests/frame/methods/test_asfreq.py
+++ b/pandas/tests/frame/methods/test_asfreq.py
@@ -17,6 +17,10 @@
class TestAsFreq:
+ @pytest.fixture(params=["s", "ms", "us", "ns"])
+ def unit(self, request):
+ return request.param
+
def test_asfreq2(self, frame_or_series):
ts = frame_or_series(
[0.0, 1.0, 2.0],
@@ -197,3 +201,11 @@ def test_asfreq_with_unsorted_index(self, frame_or_series):
result = result.asfreq("D")
tm.assert_equal(result, expected)
+
+ def test_asfreq_after_normalize(self, unit):
+ # https://github.com/pandas-dev/pandas/issues/50727
+ result = DatetimeIndex(
+ date_range("2000", periods=2).as_unit(unit).normalize(), freq="D"
+ )
+ expected = DatetimeIndex(["2000-01-01", "2000-01-02"], freq="D").as_unit(unit)
+ tm.assert_index_equal(result, expected)
| - [ ] closes #50727 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50773 | 2023-01-16T10:55:14Z | 2023-01-17T16:33:11Z | 2023-01-17T16:33:11Z | 2023-01-17T16:33:20Z |
DOC: fixed register_extension_dtype import statement | diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py
index 0c14fac57d9db..ccf8431660acb 100644
--- a/pandas/core/arrays/floating.py
+++ b/pandas/core/arrays/floating.py
@@ -2,8 +2,8 @@
import numpy as np
+from pandas.core.dtypes.base import register_extension_dtype
from pandas.core.dtypes.common import is_float_dtype
-from pandas.core.dtypes.dtypes import register_extension_dtype
from pandas.core.arrays.numeric import (
NumericArray,
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50770 | 2023-01-16T09:27:52Z | 2023-01-16T17:33:53Z | 2023-01-16T17:33:53Z | 2023-01-16T17:34:08Z |
DEPR: deprecate Index.is_numeric | diff --git a/doc/source/user_guide/scale.rst b/doc/source/user_guide/scale.rst
index a974af4ffe1c5..65ed82d9d2cf5 100644
--- a/doc/source/user_guide/scale.rst
+++ b/doc/source/user_guide/scale.rst
@@ -333,6 +333,7 @@ Dask implements the most used parts of the pandas API. For example, we can do
a familiar groupby aggregation.
.. ipython:: python
+ :okwarning:
%time ddf.groupby("name")[["x", "y"]].mean().compute().head()
@@ -356,6 +357,7 @@ we need to supply the divisions manually.
Now we can do things like fast random access with ``.loc``.
.. ipython:: python
+ :okwarning:
ddf.loc["2002-01-01 12:01":"2002-01-01 12:05"].compute()
@@ -369,6 +371,7 @@ results will fit in memory, so we can safely call ``compute`` without running
out of memory. At that point it's just a regular pandas object.
.. ipython:: python
+ :okwarning:
@savefig dask_resample.png
ddf[["x", "y"]].resample("1D").mean().cumsum().compute().plot()
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index e8b8d071928ea..5c02e6997586b 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -749,6 +749,7 @@ Deprecations
- :meth:`Index.is_integer` has been deprecated. Use :func:`pandas.api.types.is_integer_dtype` instead (:issue:`50042`)
- :meth:`Index.is_floating` has been deprecated. Use :func:`pandas.api.types.is_float_dtype` instead (:issue:`50042`)
- :meth:`Index.holds_integer` has been deprecated. Use :func:`pandas.api.types.infer_dtype` instead (:issue:`50243`)
+- :meth:`Index.is_numeric` has been deprecated. Use :func:`pandas.api.types.is_numeric_dtype` instead (:issue:`50042`)
- :meth:`Index.is_categorical` has been deprecated. Use :func:`pandas.api.types.is_categorical_dtype` instead (:issue:`50042`)
- :meth:`Index.is_object` has been deprecated. Use :func:`pandas.api.types.is_object_dtype` instead (:issue:`50042`)
- :meth:`Index.is_interval` has been deprecated. Use :func:`pandas.api.types.is_intterval_dtype` instead (:issue:`50042`)
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index f2e54185c11ff..648472d378fe1 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -47,6 +47,7 @@
from pandas.core.dtypes.common import (
ensure_int64,
ensure_platform_int,
+ is_any_numeric_dtype,
is_bool_dtype,
is_categorical_dtype,
is_datetime64_dtype,
@@ -595,7 +596,7 @@ def _from_inferred_categories(
if known_categories:
# Convert to a specialized type with `dtype` if specified.
- if dtype.categories.is_numeric():
+ if is_any_numeric_dtype(dtype.categories):
cats = to_numeric(inferred_categories, errors="coerce")
elif is_datetime64_dtype(dtype.categories):
cats = to_datetime(inferred_categories, errors="coerce")
@@ -1758,7 +1759,7 @@ def _values_for_rank(self):
if mask.any():
values = values.astype("float64")
values[mask] = np.nan
- elif self.categories.is_numeric():
+ elif is_any_numeric_dtype(self.categories):
values = np.array(self)
else:
# reorder the categories (so rank can use the float codes)
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index aa3cdcd65b344..fb9817de2b69b 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -1219,6 +1219,40 @@ def is_numeric_dtype(arr_or_dtype) -> bool:
)
+def is_any_numeric_dtype(arr_or_dtype) -> bool:
+ """
+ Check whether the provided array or dtype is of a real number dtype
+
+ Parameters
+ ----------
+ arr_or_dtype : array-like or dtype
+ The array or dtype to check.
+
+ Returns
+ -------
+ boolean
+ Whether or not the array or dtype is of a real number dtype
+
+ Examples
+ -------
+ >>> is_any_numeric_dtype(str)
+ False
+ >>> is_any_numeric_dtype(int)
+ True
+ >>> is_any_numeric_dtype(float)
+ True
+ >>> is_any_numeric_dtype(complex(1,2))
+ False
+ >>> is_any_numeric_dtype(bool)
+ False
+ """
+ return (
+ is_numeric_dtype(arr_or_dtype)
+ and not is_complex_dtype(arr_or_dtype)
+ and not is_bool_dtype(arr_or_dtype)
+ )
+
+
def is_float_dtype(arr_or_dtype) -> bool:
"""
Check whether the provided array or dtype is of a float dtype.
@@ -1774,6 +1808,7 @@ def is_all_strings(value: ArrayLike) -> bool:
"is_nested_list_like",
"is_number",
"is_numeric_dtype",
+ "is_any_numeric_dtype",
"is_numeric_v_string_like",
"is_object_dtype",
"is_period_dtype",
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 881e83313ced5..02b852f14abc8 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -88,6 +88,7 @@
ensure_int64,
ensure_object,
ensure_platform_int,
+ is_any_numeric_dtype,
is_bool_dtype,
is_categorical_dtype,
is_dtype_equal,
@@ -2278,7 +2279,7 @@ def is_boolean(self) -> bool:
--------
is_integer : Check if the Index only consists of integers (deprecated).
is_floating : Check if the Index is a floating type (deprecated).
- is_numeric : Check if the Index only consists of numeric data.
+ is_numeric : Check if the Index only consists of numeric data (deprecated).
is_object : Check if the Index is of the object dtype (deprecated).
is_categorical : Check if the Index holds categorical data.
is_interval : Check if the Index holds Interval objects (deprecated).
@@ -2322,7 +2323,7 @@ def is_integer(self) -> bool:
--------
is_boolean : Check if the Index only consists of booleans (deprecated).
is_floating : Check if the Index is a floating type (deprecated).
- is_numeric : Check if the Index only consists of numeric data.
+ is_numeric : Check if the Index only consists of numeric data (deprecated).
is_object : Check if the Index is of the object dtype. (deprecated).
is_categorical : Check if the Index holds categorical data (deprecated).
is_interval : Check if the Index holds Interval objects (deprecated).
@@ -2370,7 +2371,7 @@ def is_floating(self) -> bool:
--------
is_boolean : Check if the Index only consists of booleans (deprecated).
is_integer : Check if the Index only consists of integers (deprecated).
- is_numeric : Check if the Index only consists of numeric data.
+ is_numeric : Check if the Index only consists of numeric data (deprecated).
is_object : Check if the Index is of the object dtype. (deprecated).
is_categorical : Check if the Index holds categorical data (deprecated).
is_interval : Check if the Index holds Interval objects (deprecated).
@@ -2406,6 +2407,9 @@ def is_numeric(self) -> bool:
"""
Check if the Index only consists of numeric data.
+ .. deprecated:: 2.0.0
+ Use `pandas.api.types.is_numeric_dtype` instead.
+
Returns
-------
bool
@@ -2442,6 +2446,12 @@ def is_numeric(self) -> bool:
>>> idx.is_numeric()
False
"""
+ warnings.warn(
+ f"{type(self).__name__}.is_numeric is deprecated. "
+ "Use pandas.api.types.is_numeric_dtype instead",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return self.inferred_type in ["integer", "floating"]
@final
@@ -2462,7 +2472,7 @@ def is_object(self) -> bool:
is_boolean : Check if the Index only consists of booleans (deprecated).
is_integer : Check if the Index only consists of integers (deprecated).
is_floating : Check if the Index is a floating type (deprecated).
- is_numeric : Check if the Index only consists of numeric data.
+ is_numeric : Check if the Index only consists of numeric data (deprecated).
is_categorical : Check if the Index holds categorical data (deprecated).
is_interval : Check if the Index holds Interval objects (deprecated).
@@ -2512,7 +2522,7 @@ def is_categorical(self) -> bool:
is_boolean : Check if the Index only consists of booleans (deprecated).
is_integer : Check if the Index only consists of integers (deprecated).
is_floating : Check if the Index is a floating type (deprecated).
- is_numeric : Check if the Index only consists of numeric data.
+ is_numeric : Check if the Index only consists of numeric data (deprecated).
is_object : Check if the Index is of the object dtype. (deprecated).
is_interval : Check if the Index holds Interval objects (deprecated).
@@ -2565,7 +2575,7 @@ def is_interval(self) -> bool:
is_boolean : Check if the Index only consists of booleans (deprecated).
is_integer : Check if the Index only consists of integers (deprecated).
is_floating : Check if the Index is a floating type (deprecated).
- is_numeric : Check if the Index only consists of numeric data.
+ is_numeric : Check if the Index only consists of numeric data (deprecated).
is_object : Check if the Index is of the object dtype. (deprecated).
is_categorical : Check if the Index holds categorical data (deprecated).
@@ -3360,7 +3370,7 @@ def _intersection(self, other: Index, sort: bool = False):
pass
else:
# TODO: algos.unique1d should preserve DTA/TDA
- if self.is_numeric():
+ if is_numeric_dtype(self):
# This is faster, because Index.unique() checks for uniqueness
# before calculating the unique values.
res = algos.unique1d(res_indexer)
@@ -6035,8 +6045,8 @@ def _should_compare(self, other: Index) -> bool:
Check if `self == other` can ever have non-False entries.
"""
- if (is_bool_dtype(other) and self.is_numeric()) or (
- is_bool_dtype(self) and other.is_numeric()
+ if (is_bool_dtype(other) and is_any_numeric_dtype(self)) or (
+ is_bool_dtype(self) and is_any_numeric_dtype(other)
):
# GH#16877 Treat boolean labels passed to a numeric index as not
# found. Without this fix False and True would be treated as 0 and 1
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index fd17e57a16c4b..49b92e0984713 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -27,6 +27,7 @@
from pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.common import (
+ is_any_numeric_dtype,
is_categorical_dtype,
is_extension_array_dtype,
is_float,
@@ -840,7 +841,7 @@ def _get_xticks(self, convert_period: bool = False):
if convert_period and isinstance(index, ABCPeriodIndex):
self.data = self.data.reindex(index=index.sort_values())
x = self.data.index.to_timestamp()._mpl_repr()
- elif index.is_numeric():
+ elif is_any_numeric_dtype(index):
# Matplotlib supports numeric values or datetime objects as
# xaxis values. Taking LBYL approach here, by the time
# matplotlib raises exception when using non numeric/datetime
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index c203792be2694..f36118e245eb4 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -813,6 +813,15 @@ def test_holds_integer_deprecated(self, simple_index):
with tm.assert_produces_warning(FutureWarning, match=msg):
idx.holds_integer()
+ def test_is_numeric_is_deprecated(self, simple_index):
+ # GH50042
+ idx = simple_index
+ with tm.assert_produces_warning(
+ FutureWarning,
+ match=f"{type(idx).__name__}.is_numeric is deprecated. ",
+ ):
+ idx.is_numeric()
+
def test_is_categorical_is_deprecated(self, simple_index):
# GH50042
idx = simple_index
diff --git a/pandas/tests/indexes/multi/test_equivalence.py b/pandas/tests/indexes/multi/test_equivalence.py
index c51b9386d7ec6..3861d74cee092 100644
--- a/pandas/tests/indexes/multi/test_equivalence.py
+++ b/pandas/tests/indexes/multi/test_equivalence.py
@@ -1,6 +1,8 @@
import numpy as np
import pytest
+from pandas.core.dtypes.common import is_any_numeric_dtype
+
import pandas as pd
from pandas import (
Index,
@@ -253,7 +255,7 @@ def test_is_all_dates(idx):
def test_is_numeric(idx):
# MultiIndex is never numeric
- assert not idx.is_numeric()
+ assert not is_any_numeric_dtype(idx)
def test_multiindex_compare():
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index d78da49c967ab..6a736dfcf8687 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -19,6 +19,7 @@
from pandas.util._test_decorators import async_mark
from pandas.core.dtypes.common import (
+ is_any_numeric_dtype,
is_numeric_dtype,
is_object_dtype,
)
@@ -659,7 +660,7 @@ def test_append_empty_preserve_name(self, name, expected):
indirect=["index"],
)
def test_is_numeric(self, index, expected):
- assert index.is_numeric() is expected
+ assert is_any_numeric_dtype(index) is expected
@pytest.mark.parametrize(
"index, expected",
| - [ ] progress towards https://github.com/pandas-dev/pandas/issues/50042
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50769 | 2023-01-16T06:41:26Z | 2023-02-02T22:16:45Z | 2023-02-02T22:16:45Z | 2023-02-03T03:06:19Z |
TST: Test series add sub with UInt64 | diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index 93225d937697f..fea216c35129b 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -1463,3 +1463,17 @@ def test_empty_str_comparison(power, string_size):
result = right == left
expected = pd.DataFrame(np.zeros(right.shape, dtype=bool))
tm.assert_frame_equal(result, expected)
+
+
+def test_series_add_sub_with_UInt64():
+ # GH 22023
+ series1 = Series([1, 2, 3])
+ series2 = Series([2, 1, 3], dtype="UInt64")
+
+ result = series1 + series2
+ expected = Series([3, 3, 6], dtype="Float64")
+ tm.assert_series_equal(result, expected)
+
+ result = series1 - series2
+ expected = Series([-1, 1, 0], dtype="Float64")
+ tm.assert_series_equal(result, expected)
| - [x] closes #22023 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50768 | 2023-01-16T05:17:12Z | 2023-01-16T17:39:06Z | 2023-01-16T17:39:06Z | 2023-01-17T03:27:24Z |
DOC: Add docstring for DataFrame.T property | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 46f8c73027f48..f6994b6912e29 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3569,6 +3569,31 @@ def transpose(self, *args, copy: bool = False) -> DataFrame:
@property
def T(self) -> DataFrame:
+ """
+ The transpose of the DataFrame.
+
+ Returns
+ -------
+ DataFrame
+ The transposed DataFrame.
+
+ See Also
+ --------
+ DataFrame.transpose : Transpose index and columns.
+
+ Examples
+ --------
+ >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
+ >>> df
+ col1 col2
+ 0 1 3
+ 1 2 4
+
+ >>> df.T
+ 0 1
+ col1 1 2
+ col2 3 4
+ """
return self.transpose()
# ----------------------------------------------------------------------
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
**Before this change:**
The `T` property of a DataFrame is named in the docs but is not linked to any documentation:
(Screenshot below taken from https://pandas.pydata.org/docs/dev/reference/api/pandas.DataFrame.html)
<img width="1346" alt="image" src="https://user-images.githubusercontent.com/122238526/212579272-bc583d1a-bd0d-471e-972f-c6d10d81667e.png">
**After this change**
The `T` property is linked to documentation (it now appears as the top property alphabetically, I guess because it's a capital 'T').
<img width="1258" alt="image" src="https://user-images.githubusercontent.com/122238526/212579535-b4f9c4d7-2bfb-49af-bb3b-1e3f0e675df0.png">
And if you click on it you see this new page. As you can see, it links through to the existing `DataFrame.transpose` docs. I put in one simple example here.
<img width="1277" alt="image" src="https://user-images.githubusercontent.com/122238526/212579665-cdca6ebd-9a99-4d16-ace6-979ad85a7dbc.png">
| https://api.github.com/repos/pandas-dev/pandas/pulls/50766 | 2023-01-16T01:25:46Z | 2023-01-16T18:42:14Z | 2023-01-16T18:42:14Z | 2023-11-27T00:21:05Z |
ENH: Add use_nullable_dtypes to read_feather | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index 033f47f0c994d..18fd3ca829b31 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -45,6 +45,7 @@ The ``use_nullable_dtypes`` keyword argument has been expanded to the following
* :func:`read_sql_query`
* :func:`read_sql_table`
* :func:`read_orc`
+* :func:`read_feather`
* :func:`to_numeric`
Additionally a new global configuration, ``mode.dtype_backend`` can now be used in conjunction with the parameter ``use_nullable_dtypes=True`` in the following functions
@@ -57,6 +58,7 @@ to select the nullable dtypes implementation.
* :func:`read_xml`
* :func:`read_parquet`
* :func:`read_orc`
+* :func:`read_feather`
And the following methods will also utilize the ``mode.dtype_backend`` option.
diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py
index e781da74e97aa..cb2890777621a 100644
--- a/pandas/io/feather_format.py
+++ b/pandas/io/feather_format.py
@@ -15,6 +15,10 @@
from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import doc
+from pandas import (
+ arrays,
+ get_option,
+)
from pandas.core.api import (
DataFrame,
NumericIndex,
@@ -99,6 +103,7 @@ def read_feather(
columns: Sequence[Hashable] | None = None,
use_threads: bool = True,
storage_options: StorageOptions = None,
+ use_nullable_dtypes: bool = False,
):
"""
Load a feather-format object from the file path.
@@ -118,6 +123,19 @@ def read_feather(
.. versionadded:: 1.2.0
+ use_nullable_dtypes : bool = False
+ Whether or not to use nullable dtypes as default when reading data. If
+ set to True, nullable dtypes are used for all dtypes that have a nullable
+ implementation, even if no nulls are present.
+
+ The nullable dtype implementation can be configured by calling
+ ``pd.set_option("mode.dtype_backend", "pandas")`` to use
+ numpy-backed nullable dtypes or
+ ``pd.set_option("mode.dtype_backend", "pyarrow")`` to use
+ pyarrow-backed nullable dtypes (using ``pd.ArrowDtype``).
+
+ .. versionadded:: 2.0
+
Returns
-------
type of object stored in file
@@ -128,7 +146,28 @@ def read_feather(
with get_handle(
path, "rb", storage_options=storage_options, is_text=False
) as handles:
+ if not use_nullable_dtypes:
+ return feather.read_feather(
+ handles.handle, columns=columns, use_threads=bool(use_threads)
+ )
- return feather.read_feather(
+ dtype_backend = get_option("mode.dtype_backend")
+
+ pa_table = feather.read_table(
handles.handle, columns=columns, use_threads=bool(use_threads)
)
+
+ if dtype_backend == "pandas":
+ from pandas.io._util import _arrow_dtype_mapping
+
+ return pa_table.to_pandas(types_mapper=_arrow_dtype_mapping().get)
+
+ elif dtype_backend == "pyarrow":
+ return DataFrame(
+ {
+ col_name: arrays.ArrowExtensionArray(pa_col)
+ for col_name, pa_col in zip(
+ pa_table.column_names, pa_table.itercolumns()
+ )
+ }
+ )
diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py
index 88bf04f518e12..28a6054098a6f 100644
--- a/pandas/tests/io/test_feather.py
+++ b/pandas/tests/io/test_feather.py
@@ -4,6 +4,10 @@
import pandas as pd
import pandas._testing as tm
+from pandas.core.arrays import (
+ ArrowStringArray,
+ StringArray,
+)
from pandas.io.feather_format import read_feather, to_feather # isort:skip
@@ -194,3 +198,60 @@ def test_http_path(self, feather_file):
expected = read_feather(feather_file)
res = read_feather(url)
tm.assert_frame_equal(expected, res)
+
+ @pytest.mark.parametrize("dtype_backend", ["pandas", "pyarrow"])
+ def test_read_json_nullable(self, string_storage, dtype_backend):
+ # GH#50765
+ pa = pytest.importorskip("pyarrow")
+ df = pd.DataFrame(
+ {
+ "a": pd.Series([1, np.nan, 3], dtype="Int64"),
+ "b": pd.Series([1, 2, 3], dtype="Int64"),
+ "c": pd.Series([1.5, np.nan, 2.5], dtype="Float64"),
+ "d": pd.Series([1.5, 2.0, 2.5], dtype="Float64"),
+ "e": [True, False, None],
+ "f": [True, False, True],
+ "g": ["a", "b", "c"],
+ "h": ["a", "b", None],
+ }
+ )
+
+ if string_storage == "python":
+ string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_))
+ string_array_na = StringArray(np.array(["a", "b", pd.NA], dtype=np.object_))
+
+ else:
+ string_array = ArrowStringArray(pa.array(["a", "b", "c"]))
+ string_array_na = ArrowStringArray(pa.array(["a", "b", None]))
+
+ with tm.ensure_clean() as path:
+ to_feather(df, path)
+ with pd.option_context("mode.string_storage", string_storage):
+ with pd.option_context("mode.dtype_backend", dtype_backend):
+ result = read_feather(path, use_nullable_dtypes=True)
+
+ expected = pd.DataFrame(
+ {
+ "a": pd.Series([1, np.nan, 3], dtype="Int64"),
+ "b": pd.Series([1, 2, 3], dtype="Int64"),
+ "c": pd.Series([1.5, np.nan, 2.5], dtype="Float64"),
+ "d": pd.Series([1.5, 2.0, 2.5], dtype="Float64"),
+ "e": pd.Series([True, False, pd.NA], dtype="boolean"),
+ "f": pd.Series([True, False, True], dtype="boolean"),
+ "g": string_array,
+ "h": string_array_na,
+ }
+ )
+
+ if dtype_backend == "pyarrow":
+
+ from pandas.arrays import ArrowExtensionArray
+
+ expected = pd.DataFrame(
+ {
+ col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))
+ for col in expected.columns
+ }
+ )
+
+ tm.assert_frame_equal(result, expected)
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50765 | 2023-01-15T23:20:15Z | 2023-01-17T17:55:02Z | 2023-01-17T17:55:02Z | 2023-01-17T18:38:07Z |
BUG: eval and query not working with ea dtypes | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index 532881fee0892..d8beff81e6c6b 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -1183,6 +1183,7 @@ Conversion
- Bug in :meth:`DataFrame.astype` not copying data when converting to pyarrow dtype (:issue:`50984`)
- Bug in :func:`to_datetime` was not respecting ``exact`` argument when ``format`` was an ISO8601 format (:issue:`12649`)
- Bug in :meth:`TimedeltaArray.astype` raising ``TypeError`` when converting to a pyarrow duration type (:issue:`49795`)
+- Bug in :meth:`DataFrame.eval` and :meth:`DataFrame.query` raising for extension array dtypes (:issue:`29618`, :issue:`50261`, :issue:`31913`)
-
Strings
diff --git a/pandas/core/computation/common.py b/pandas/core/computation/common.py
index a1ac3dfa06ee0..115191829f044 100644
--- a/pandas/core/computation/common.py
+++ b/pandas/core/computation/common.py
@@ -26,3 +26,23 @@ def result_type_many(*arrays_and_dtypes):
except ValueError:
# we have > NPY_MAXARGS terms in our expression
return reduce(np.result_type, arrays_and_dtypes)
+ except TypeError:
+ from pandas.core.dtypes.cast import find_common_type
+ from pandas.core.dtypes.common import is_extension_array_dtype
+
+ arr_and_dtypes = list(arrays_and_dtypes)
+ ea_dtypes, non_ea_dtypes = [], []
+ for arr_or_dtype in arr_and_dtypes:
+ if is_extension_array_dtype(arr_or_dtype):
+ ea_dtypes.append(arr_or_dtype)
+ else:
+ non_ea_dtypes.append(arr_or_dtype)
+
+ if non_ea_dtypes:
+ try:
+ np_dtype = np.result_type(*non_ea_dtypes)
+ except ValueError:
+ np_dtype = reduce(np.result_type, arrays_and_dtypes)
+ return find_common_type(ea_dtypes + [np_dtype])
+
+ return find_common_type(ea_dtypes)
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py
index f0127ae05182a..0326760a1ff24 100644
--- a/pandas/core/computation/eval.py
+++ b/pandas/core/computation/eval.py
@@ -7,8 +7,11 @@
from typing import TYPE_CHECKING
import warnings
+from pandas.util._exceptions import find_stack_level
from pandas.util._validators import validate_bool_kwarg
+from pandas.core.dtypes.common import is_extension_array_dtype
+
from pandas.core.computation.engines import ENGINES
from pandas.core.computation.expr import (
PARSERS,
@@ -333,6 +336,22 @@ def eval(
parsed_expr = Expr(expr, engine=engine, parser=parser, env=env)
+ if engine == "numexpr" and (
+ is_extension_array_dtype(parsed_expr.terms.return_type)
+ or getattr(parsed_expr.terms, "operand_types", None) is not None
+ and any(
+ is_extension_array_dtype(elem)
+ for elem in parsed_expr.terms.operand_types
+ )
+ ):
+ warnings.warn(
+ "Engine has switched to 'python' because numexpr does not support "
+ "extension array dtypes. Please set your engine to python manually.",
+ RuntimeWarning,
+ stacklevel=find_stack_level(),
+ )
+ engine = "python"
+
# construct the engine and evaluate the parsed expression
eng = ENGINES[engine]
eng_inst = eng(parsed_expr)
diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py
index 8a40461f10039..c815b897e6a14 100644
--- a/pandas/tests/frame/test_query_eval.py
+++ b/pandas/tests/frame/test_query_eval.py
@@ -3,6 +3,7 @@
import numpy as np
import pytest
+from pandas.compat import is_platform_windows
from pandas.errors import (
NumExprClobberingError,
UndefinedVariableError,
@@ -1291,3 +1292,79 @@ def func(*_):
with pytest.raises(TypeError, match="Only named functions are supported"):
df.eval("@funcs[0].__call__()")
+
+ def test_ea_dtypes(self, any_numeric_ea_and_arrow_dtype):
+ # GH#29618
+ df = DataFrame(
+ [[1, 2], [3, 4]], columns=["a", "b"], dtype=any_numeric_ea_and_arrow_dtype
+ )
+ warning = RuntimeWarning if NUMEXPR_INSTALLED else None
+ with tm.assert_produces_warning(warning):
+ result = df.eval("c = b - a")
+ expected = DataFrame(
+ [[1, 2, 1], [3, 4, 1]],
+ columns=["a", "b", "c"],
+ dtype=any_numeric_ea_and_arrow_dtype,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_ea_dtypes_and_scalar(self):
+ # GH#29618
+ df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"], dtype="Float64")
+ warning = RuntimeWarning if NUMEXPR_INSTALLED else None
+ with tm.assert_produces_warning(warning):
+ result = df.eval("c = b - 1")
+ expected = DataFrame(
+ [[1, 2, 1], [3, 4, 3]], columns=["a", "b", "c"], dtype="Float64"
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_ea_dtypes_and_scalar_operation(self, any_numeric_ea_and_arrow_dtype):
+ # GH#29618
+ df = DataFrame(
+ [[1, 2], [3, 4]], columns=["a", "b"], dtype=any_numeric_ea_and_arrow_dtype
+ )
+ result = df.eval("c = 2 - 1")
+ expected = DataFrame(
+ {
+ "a": Series([1, 3], dtype=any_numeric_ea_and_arrow_dtype),
+ "b": Series([2, 4], dtype=any_numeric_ea_and_arrow_dtype),
+ "c": Series(
+ [1, 1], dtype="int64" if not is_platform_windows() else "int32"
+ ),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["int64", "Int64", "int64[pyarrow]"])
+ def test_query_ea_dtypes(self, dtype):
+ if dtype == "int64[pyarrow]":
+ pytest.importorskip("pyarrow")
+ # GH#50261
+ df = DataFrame({"a": Series([1, 2], dtype=dtype)})
+ ref = {2} # noqa:F841
+ result = df.query("a in @ref")
+ expected = DataFrame({"a": Series([2], dtype=dtype, index=[1])})
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("engine", ["python", "numexpr"])
+ @pytest.mark.parametrize("dtype", ["int64", "Int64", "int64[pyarrow]"])
+ def test_query_ea_equality_comparison(self, dtype, engine):
+ # GH#50261
+ warning = RuntimeWarning if engine == "numexpr" else None
+ if engine == "numexpr" and not NUMEXPR_INSTALLED:
+ pytest.skip("numexpr not installed")
+ if dtype == "int64[pyarrow]":
+ pytest.importorskip("pyarrow")
+ df = DataFrame(
+ {"A": Series([1, 1, 2], dtype="Int64"), "B": Series([1, 2, 2], dtype=dtype)}
+ )
+ with tm.assert_produces_warning(warning):
+ result = df.query("A == B", engine=engine)
+ expected = DataFrame(
+ {
+ "A": Series([1, 2], dtype="Int64", index=[0, 2]),
+ "B": Series([1, 2], dtype=dtype, index=[0, 2]),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
| - [x] closes #29618 (Replace xxxx with the GitHub issue number)
- [x] closes #50261
- [x] closes #31913
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
This is really ugly, not sure if we want to do this. But could not find another way to make this work | https://api.github.com/repos/pandas-dev/pandas/pulls/50764 | 2023-01-15T22:58:23Z | 2023-02-09T16:45:15Z | 2023-02-09T16:45:15Z | 2023-02-09T16:46:38Z |
TYP: fix NDFrame._value type | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 46f8c73027f48..a146098b53934 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -960,12 +960,8 @@ def _can_fast_transpose(self) -> bool:
# TODO(EA2D) special case would be unnecessary with 2D EAs
return not is_1d_only_ea_dtype(dtype)
- # error: Return type "Union[ndarray, DatetimeArray, TimedeltaArray]" of
- # "_values" incompatible with return type "ndarray" in supertype "NDFrame"
@property
- def _values( # type: ignore[override]
- self,
- ) -> np.ndarray | DatetimeArray | TimedeltaArray | PeriodArray:
+ def _values(self) -> np.ndarray | DatetimeArray | TimedeltaArray | PeriodArray:
"""
Analogue to ._values that may return a 2D ExtensionArray.
"""
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 4ef91f6de5e27..0407615aa3256 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1805,14 +1805,7 @@ def _get_label_or_level_values(self, key: Level, axis: AxisInt = 0) -> ArrayLike
self._check_label_or_level_ambiguity(key, axis=axis)
values = self.xs(key, axis=other_axes[0])._values
elif self._is_level_reference(key, axis=axis):
- # error: Incompatible types in assignment (expression has type "Union[
- # ExtensionArray, ndarray[Any, Any]]", variable has type "ndarray[Any,
- # Any]")
- values = (
- self.axes[axis]
- .get_level_values(key) # type: ignore[assignment]
- ._values
- )
+ values = self.axes[axis].get_level_values(key)._values
else:
raise KeyError(key)
@@ -5975,7 +5968,7 @@ def values(self):
raise AbstractMethodError(self)
@property
- def _values(self) -> np.ndarray:
+ def _values(self) -> ArrayLike:
"""internal implementation"""
raise AbstractMethodError(self)
| xref https://github.com/pandas-dev/pandas/issues/37715
Fixes the type of `NDFrame._value` and allow to remove 2 related `# type: ignore`
Thanks! | https://api.github.com/repos/pandas-dev/pandas/pulls/50763 | 2023-01-15T22:13:30Z | 2023-01-18T19:45:22Z | 2023-01-18T19:45:22Z | 2023-01-18T20:05:29Z |
BUG: Series add casting to object for list and masked series | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index 033f47f0c994d..3dcee72770272 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -929,6 +929,7 @@ Numeric
- Bug in arithmetic operations on :class:`Series` not propagating mask when combining masked dtypes and numpy dtypes (:issue:`45810`, :issue:`42630`)
- Bug in DataFrame reduction methods (e.g. :meth:`DataFrame.sum`) with object dtype, ``axis=1`` and ``numeric_only=False`` would not be coerced to float (:issue:`49551`)
- Bug in :meth:`DataFrame.sem` and :meth:`Series.sem` where an erroneous ``TypeError`` would always raise when using data backed by an :class:`ArrowDtype` (:issue:`49759`)
+- Bug in :meth:`Series.__add__` casting to object for list and masked :class:`Series` (:issue:`22962`)
Conversion
^^^^^^^^^^
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index aaa7c706d95bb..77735add89bf7 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -621,6 +621,27 @@ def _arith_method(self, other, op):
op_name = op.__name__
omask = None
+ if (
+ not hasattr(other, "dtype")
+ and is_list_like(other)
+ and len(other) == len(self)
+ ):
+ # Try inferring masked dtype instead of casting to object
+ inferred_dtype = lib.infer_dtype(other, skipna=True)
+ if inferred_dtype == "integer":
+ from pandas.core.arrays import IntegerArray
+
+ other = IntegerArray._from_sequence(other)
+ elif inferred_dtype in ["floating", "mixed-integer-float"]:
+ from pandas.core.arrays import FloatingArray
+
+ other = FloatingArray._from_sequence(other)
+
+ elif inferred_dtype in ["boolean"]:
+ from pandas.core.arrays import BooleanArray
+
+ other = BooleanArray._from_sequence(other)
+
if isinstance(other, BaseMaskedArray):
other, omask = other._data, other._mask
diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py
index 35096540c70d3..a7f73f2e22fca 100644
--- a/pandas/tests/series/test_arithmetic.py
+++ b/pandas/tests/series/test_arithmetic.py
@@ -325,6 +325,27 @@ def test_mask_div_propagate_na_for_non_na_dtype(self):
result = ser2 / ser1
tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize("val, dtype", [(3, "Int64"), (3.5, "Float64")])
+ def test_add_list_to_masked_array(self, val, dtype):
+ # GH#22962
+ ser = Series([1, None, 3], dtype="Int64")
+ result = ser + [1, None, val]
+ expected = Series([2, None, 3 + val], dtype=dtype)
+ tm.assert_series_equal(result, expected)
+
+ result = [1, None, val] + ser
+ tm.assert_series_equal(result, expected)
+
+ def test_add_list_to_masked_array_boolean(self):
+ # GH#22962
+ ser = Series([True, None, False], dtype="boolean")
+ result = ser + [True, None, True]
+ expected = Series([True, None, True], dtype="boolean")
+ tm.assert_series_equal(result, expected)
+
+ result = [True, None, True] + ser
+ tm.assert_series_equal(result, expected)
+
# ------------------------------------------------------------------
# Comparisons
| - [x] closes #22962 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50762 | 2023-01-15T21:12:36Z | 2023-01-17T17:53:28Z | 2023-01-17T17:53:28Z | 2023-04-22T18:12:15Z |
BUG: .transform(ngroup) for axis=1 grouper | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index a30d68319cafe..504d03419b5dc 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -1126,6 +1126,7 @@ Groupby/resample/rolling
- Bug in :class:`.DataFrameGroupBy` would raise when used with an empty DataFrame, categorical grouper, and ``dropna=False`` (:issue:`50634`)
- Bug in :meth:`.SeriesGroupBy.value_counts` did not respect ``sort=False`` (:issue:`50482`)
- Bug in :meth:`.DataFrameGroupBy.resample` raises ``KeyError`` when getting the result from a key list when resampling on time index (:issue:`50840`)
+- Bug in :meth:`.DataFrameGroupBy.transform` and :meth:`.SeriesGroupBy.transform` would raise incorrectly when grouper had ``axis=1`` for ``"ngroup"`` argument (:issue:`45986`)
-
Reshaping
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index c15948ce877a8..a2fa58e795da5 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -3394,7 +3394,7 @@ def ngroup(self, ascending: bool = True):
dtype: int64
"""
with self._group_selection_context():
- index = self._selected_obj.index
+ index = self._selected_obj._get_axis(self.axis)
comp_ids = self.grouper.group_info[0]
dtype: type
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index ab4f2bd5e529b..81dca42b1d74f 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -164,10 +164,6 @@ def test_transform_broadcast(tsframe, ts):
def test_transform_axis_1(request, transformation_func):
# GH 36308
- if transformation_func == "ngroup":
- msg = "ngroup fails with axis=1: #45986"
- request.node.add_marker(pytest.mark.xfail(reason=msg))
-
df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, index=["x", "y"])
args = get_groupby_method_args(transformation_func, df)
result = df.groupby([0, 0, 1], axis=1).transform(transformation_func, *args)
| Part of #45986
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50761 | 2023-01-15T18:13:14Z | 2023-01-24T21:44:33Z | 2023-01-24T21:44:33Z | 2023-01-24T21:44:45Z |
BUG: replace raising RecursionError | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index 033f47f0c994d..f734db1419282 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -980,6 +980,8 @@ Missing
- Bug in :meth:`Series.map` caused incorrect result when data has NaNs and defaultdict mapping was used (:issue:`48813`)
- Bug in :class:`NA` raising a ``TypeError`` instead of return :class:`NA` when performing a binary operation with a ``bytes`` object (:issue:`49108`)
- Bug in :meth:`DataFrame.update` with ``overwrite=False`` raising ``TypeError`` when ``self`` has column with ``NaT`` values and column not present in ``other`` (:issue:`16713`)
+- Bug in :meth:`Series.replace` raising ``RecursionError`` when replacing value in object-dtype :class:`Series` containing ``NA`` (:issue:`47480`)
+- Bug in :meth:`Series.replace` raising ``RecursionError`` when replacing value in numeric :class:`Series` with ``NA`` (:issue:`50758`)
MultiIndex
^^^^^^^^^^
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index f7787aa52623b..4bb4882574228 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -21,6 +21,7 @@
writers,
)
from pandas._libs.internals import BlockPlacement
+from pandas._libs.missing import NA
from pandas._libs.tslibs import IncompatibleFrequency
from pandas._typing import (
ArrayLike,
@@ -569,7 +570,7 @@ def replace(
return blocks
elif self.ndim == 1 or self.shape[0] == 1:
- if value is None:
+ if value is None or value is NA:
blk = self.astype(np.dtype(object))
else:
blk = self.coerce_to_target_dtype(value)
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index 0da4f6404c3cc..162186bc4186a 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -32,6 +32,7 @@
from pandas.core.dtypes.common import (
is_array_like,
is_numeric_v_string_like,
+ is_object_dtype,
needs_i8_conversion,
)
from pandas.core.dtypes.missing import (
@@ -83,6 +84,12 @@ def mask_missing(arr: ArrayLike, values_to_mask) -> npt.NDArray[np.bool_]:
# _DTypeDict, Tuple[Any, Any]]]"
values_to_mask = np.array(values_to_mask, dtype=dtype) # type: ignore[arg-type]
+ potential_na = False
+ if is_object_dtype(arr):
+ # pre-compute mask to avoid comparison to NA
+ potential_na = True
+ arr_mask = ~isna(arr)
+
na_mask = isna(values_to_mask)
nonna = values_to_mask[~na_mask]
@@ -93,10 +100,15 @@ def mask_missing(arr: ArrayLike, values_to_mask) -> npt.NDArray[np.bool_]:
# GH#29553 prevent numpy deprecation warnings
pass
else:
- new_mask = arr == x
- if not isinstance(new_mask, np.ndarray):
- # usually BooleanArray
- new_mask = new_mask.to_numpy(dtype=bool, na_value=False)
+ if potential_na:
+ new_mask = np.zeros(arr.shape, dtype=np.bool_)
+ new_mask[arr_mask] = arr[arr_mask] == x
+ else:
+ new_mask = arr == x
+
+ if not isinstance(new_mask, np.ndarray):
+ # usually BooleanArray
+ new_mask = new_mask.to_numpy(dtype=bool, na_value=False)
mask |= new_mask
if na_mask.any():
diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py
index 1188c9452520c..44c224c120ea6 100644
--- a/pandas/tests/series/methods/test_replace.py
+++ b/pandas/tests/series/methods/test_replace.py
@@ -690,3 +690,25 @@ def test_replace_change_dtype_series(self):
df = pd.DataFrame.from_dict({"Test": ["0.5", None, "0.6"]})
df["Test"] = df["Test"].fillna(np.nan)
tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("dtype", ["object", "Int64"])
+ def test_replace_na_in_obj_column(self, dtype):
+ # GH#47480
+ ser = pd.Series([0, 1, pd.NA], dtype=dtype)
+ expected = pd.Series([0, 2, pd.NA], dtype=dtype)
+ result = ser.replace(to_replace=1, value=2)
+ tm.assert_series_equal(result, expected)
+
+ ser.replace(to_replace=1, value=2, inplace=True)
+ tm.assert_series_equal(ser, expected)
+
+ @pytest.mark.parametrize("val", [0, 0.5])
+ def test_replace_numeric_column_with_na(self, val):
+ # GH#50758
+ ser = pd.Series([val, 1])
+ expected = pd.Series([val, pd.NA])
+ result = ser.replace(to_replace=1, value=pd.NA)
+ tm.assert_series_equal(result, expected)
+
+ ser.replace(to_replace=1, value=pd.NA, inplace=True)
+ tm.assert_series_equal(ser, expected)
| - [x] closes #47480 (Replace xxxx with the GitHub issue number)
- [x] closes #50758 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Could also consider back porting | https://api.github.com/repos/pandas-dev/pandas/pulls/50760 | 2023-01-15T17:00:10Z | 2023-01-16T19:02:04Z | 2023-01-16T19:02:04Z | 2023-01-16T19:04:09Z |
BUG: Fix file-like objects failing in `read_xml` when iterparse is used | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index 8da9d7e3a04c0..eb6504a6a2948 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -1022,6 +1022,7 @@ I/O
- Fixed memory leak which stemmed from the initialization of the internal JSON module (:issue:`49222`)
- Fixed issue where :func:`json_normalize` would incorrectly remove leading characters from column names that matched the ``sep`` argument (:issue:`49861`)
- Bug in :meth:`DataFrame.to_json` where it would segfault when failing to encode a string (:issue:`50307`)
+- Bug in :func:`read_xml` where file-like objects failed when iterparse is used (:issue:`50641`)
Period
^^^^^^
diff --git a/pandas/io/xml.py b/pandas/io/xml.py
index 6ffa3356cc9de..1b32cf252d315 100644
--- a/pandas/io/xml.py
+++ b/pandas/io/xml.py
@@ -297,7 +297,7 @@ def _iterparse_nodes(self, iterparse: Callable) -> list[dict[str, str | None]]:
TypeError
* If `iterparse` is not a dict or its dict value is not list-like.
ParserError
- * If `path_or_buffer` is not a physical, decompressed file on disk.
+ * If `path_or_buffer` is not a physical file on disk or file-like object.
* If no data is returned from selected items in `iterparse`.
Notes
@@ -322,7 +322,7 @@ def _iterparse_nodes(self, iterparse: Callable) -> list[dict[str, str | None]]:
"for value in iterparse"
)
- if (
+ if (not hasattr(self.path_or_buffer, "read")) and (
not isinstance(self.path_or_buffer, str)
or is_url(self.path_or_buffer)
or is_fsspec_url(self.path_or_buffer)
diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py
index e3724f2a40409..6aaa11866a584 100644
--- a/pandas/tests/io/xml/test_xml.py
+++ b/pandas/tests/io/xml/test_xml.py
@@ -1351,18 +1351,81 @@ def test_string_error(parser):
)
-def test_file_like_error(datapath, parser, mode):
+def test_file_like_iterparse(datapath, parser, mode):
filename = datapath("io", "data", "xml", "books.xml")
- with pytest.raises(
- ParserError, match=("iterparse is designed for large XML files")
- ):
- with open(filename) as f:
- read_xml(
+
+ with open(filename, mode) as f:
+ if mode == "r" and parser == "lxml":
+ with pytest.raises(
+ TypeError, match=("reading file objects must return bytes objects")
+ ):
+ read_xml(
+ f,
+ parser=parser,
+ iterparse={
+ "book": ["category", "title", "year", "author", "price"]
+ },
+ )
+ return None
+ else:
+ df_filelike = read_xml(
f,
parser=parser,
iterparse={"book": ["category", "title", "year", "author", "price"]},
)
+ df_expected = DataFrame(
+ {
+ "category": ["cooking", "children", "web"],
+ "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
+ "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
+ "year": [2005, 2005, 2003],
+ "price": [30.00, 29.99, 39.95],
+ }
+ )
+
+ tm.assert_frame_equal(df_filelike, df_expected)
+
+
+def test_file_io_iterparse(datapath, parser, mode):
+ filename = datapath("io", "data", "xml", "books.xml")
+
+ funcIO = StringIO if mode == "r" else BytesIO
+ with open(filename, mode) as f:
+ with funcIO(f.read()) as b:
+ if mode == "r" and parser == "lxml":
+ with pytest.raises(
+ TypeError, match=("reading file objects must return bytes objects")
+ ):
+ read_xml(
+ b,
+ parser=parser,
+ iterparse={
+ "book": ["category", "title", "year", "author", "price"]
+ },
+ )
+ return None
+ else:
+ df_fileio = read_xml(
+ b,
+ parser=parser,
+ iterparse={
+ "book": ["category", "title", "year", "author", "price"]
+ },
+ )
+
+ df_expected = DataFrame(
+ {
+ "category": ["cooking", "children", "web"],
+ "title": ["Everyday Italian", "Harry Potter", "Learning XML"],
+ "author": ["Giada De Laurentiis", "J K. Rowling", "Erik T. Ray"],
+ "year": [2005, 2005, 2003],
+ "price": [30.00, 29.99, 39.95],
+ }
+ )
+
+ tm.assert_frame_equal(df_fileio, df_expected)
+
@pytest.mark.network
@tm.network(url="https://www.w3schools.com/xml/books.xml", check_before_test=True)
| - [X] closes #50641
- [X] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [X] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [X] Added an entry in the latest `doc/source/whatsnew/v2.0.0.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50759 | 2023-01-15T16:45:19Z | 2023-01-18T19:47:23Z | 2023-01-18T19:47:23Z | 2023-02-12T14:15:35Z |
BUG: Series constructor overflowing for UInt64 | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index 6c8dd2f8da938..e20a6a04ce417 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -1075,6 +1075,7 @@ ExtensionArray
- Bug in :meth:`array.PandasArray.to_numpy` raising with ``NA`` value when ``na_value`` is specified (:issue:`40638`)
- Bug in :meth:`api.types.is_numeric_dtype` where a custom :class:`ExtensionDtype` would not return ``True`` if ``_is_numeric`` returned ``True`` (:issue:`50563`)
- Bug in :meth:`api.types.is_integer_dtype`, :meth:`api.types.is_unsigned_integer_dtype`, :meth:`api.types.is_signed_integer_dtype`, :meth:`api.types.is_float_dtype` where a custom :class:`ExtensionDtype` would not return ``True`` if ``kind`` returned the corresponding NumPy type (:issue:`50667`)
+- Bug in :class:`Series` constructor unnecessarily overflowing for nullable unsigned integer dtypes (:issue:`38798`, :issue:`25880`)
Styler
^^^^^^
diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py
index 0a30c28acb090..6ae2c3a2e2749 100644
--- a/pandas/core/arrays/numeric.py
+++ b/pandas/core/arrays/numeric.py
@@ -168,6 +168,7 @@ def _coerce_to_data_and_mask(values, mask, dtype, copy, dtype_cls, default_dtype
mask = mask.copy()
return values, mask, dtype, inferred_type
+ original = values
values = np.array(values, copy=copy)
inferred_type = None
if is_object_dtype(values.dtype) or is_string_dtype(values.dtype):
@@ -204,6 +205,22 @@ def _coerce_to_data_and_mask(values, mask, dtype, copy, dtype_cls, default_dtype
else:
dtype = dtype.type
+ if is_integer_dtype(dtype) and is_float_dtype(values.dtype) and len(values) > 0:
+ if mask.all():
+ values = np.ones(values.shape, dtype=dtype)
+ else:
+ idx = np.nanargmax(values)
+ if int(values[idx]) != original[idx]:
+ # We have ints that lost precision during the cast.
+ inferred_type = lib.infer_dtype(original, skipna=True)
+ if (
+ inferred_type not in ["floating", "mixed-integer-float"]
+ and not mask.any()
+ ):
+ values = np.array(original, dtype=dtype, copy=False)
+ else:
+ values = np.array(original, dtype="object", copy=False)
+
# we copy as need to coerce here
if mask.any():
values = values.copy()
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 05e40e20f1226..bd53e38f4ce28 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -49,6 +49,7 @@
import pandas._testing as tm
from pandas.core.api import Int64Index
from pandas.core.arrays import (
+ IntegerArray,
IntervalArray,
period_array,
)
@@ -2007,6 +2008,50 @@ def test_series_constructor_ea_int_from_string_bool(self):
with pytest.raises(ValueError, match="invalid literal"):
Series(["True", "False", "True", pd.NA], dtype="Int64")
+ @pytest.mark.parametrize("val", [1, 1.0])
+ def test_series_constructor_overflow_uint_ea(self, val):
+ # GH#38798
+ max_val = np.iinfo(np.uint64).max - 1
+ result = Series([max_val, val], dtype="UInt64")
+ expected = Series(np.array([max_val, 1], dtype="uint64"), dtype="UInt64")
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("val", [1, 1.0])
+ def test_series_constructor_overflow_uint_ea_with_na(self, val):
+ # GH#38798
+ max_val = np.iinfo(np.uint64).max - 1
+ result = Series([max_val, val, pd.NA], dtype="UInt64")
+ expected = Series(
+ IntegerArray(
+ np.array([max_val, 1, 0], dtype="uint64"),
+ np.array([0, 0, 1], dtype=np.bool_),
+ )
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_series_constructor_overflow_uint_with_nan(self):
+ # GH#38798
+ max_val = np.iinfo(np.uint64).max - 1
+ result = Series([max_val, np.nan], dtype="UInt64")
+ expected = Series(
+ IntegerArray(
+ np.array([max_val, 1], dtype="uint64"),
+ np.array([0, 1], dtype=np.bool_),
+ )
+ )
+ tm.assert_series_equal(result, expected)
+
+ def test_series_constructor_ea_all_na(self):
+ # GH#38798
+ result = Series([np.nan, np.nan], dtype="UInt64")
+ expected = Series(
+ IntegerArray(
+ np.array([1, 1], dtype="uint64"),
+ np.array([1, 1], dtype=np.bool_),
+ )
+ )
+ tm.assert_series_equal(result, expected)
+
class TestSeriesConstructorIndexCoercion:
def test_series_constructor_datetimelike_index_coercion(self):
diff --git a/pandas/tests/tools/test_to_numeric.py b/pandas/tests/tools/test_to_numeric.py
index 1c0a8301d65cc..d3701c30aa50c 100644
--- a/pandas/tests/tools/test_to_numeric.py
+++ b/pandas/tests/tools/test_to_numeric.py
@@ -4,8 +4,6 @@
from numpy import iinfo
import pytest
-from pandas.compat import is_platform_arm
-
import pandas as pd
from pandas import (
DataFrame,
@@ -755,13 +753,7 @@ def test_to_numeric_from_nullable_string(values, nullable_string_dtype, expected
([1.0, 1.1], "Float64", "signed", "Float64"),
([1, pd.NA], "Int64", "signed", "Int8"),
([450, -300], "Int64", "signed", "Int16"),
- pytest.param(
- [np.iinfo(np.uint64).max - 1, 1],
- "UInt64",
- "signed",
- "UInt64",
- marks=pytest.mark.xfail(not is_platform_arm(), reason="GH38798"),
- ),
+ ([np.iinfo(np.uint64).max - 1, 1], "UInt64", "signed", "UInt64"),
([1, 1], "Int64", "unsigned", "UInt8"),
([1.0, 1.0], "Float32", "unsigned", "UInt8"),
([1.0, 1.1], "Float64", "unsigned", "Float64"),
| - [x] closes #38798 (Replace xxxx with the GitHub issue number)
- [x] closes #25880 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Not sure if there is a way to avoid loss of precision without using object in the mixed case. This does not impact the regular case without overflow risks | https://api.github.com/repos/pandas-dev/pandas/pulls/50757 | 2023-01-15T14:34:45Z | 2023-01-18T14:58:08Z | 2023-01-18T14:58:08Z | 2023-01-18T14:58:12Z |
TST: Test groupby method drop na | diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 5384b228850f4..b4a243671e287 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -2846,3 +2846,22 @@ def test_sum_of_booleans(n):
result = df.groupby("groupby_col").sum()
expected = DataFrame({"bool": [n]}, index=Index([1], name="groupby_col"))
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("method", ["head", "tail", "nth", "first", "last"])
+def test_groupby_method_drop_na(method):
+ # GH 21755
+ df = DataFrame({"A": ["a", np.nan, "b", np.nan, "c"], "B": range(5)})
+
+ if method == "nth":
+ result = getattr(df.groupby("A"), method)(n=0)
+ else:
+ result = getattr(df.groupby("A"), method)()
+
+ if method in ["first", "last"]:
+ expected = DataFrame({"B": [0, 2, 4]}).set_index(
+ Series(["a", "b", "c"], name="A")
+ )
+ else:
+ expected = DataFrame({"A": ["a", "b", "c"], "B": [0, 2, 4]}, index=[0, 2, 4])
+ tm.assert_frame_equal(result, expected)
| - [x] closes #21755 (Replace xxxx with GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) when a bug was fixed or a new feature was added - [ ] All [Code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit)
- [ ] [Type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) added to new arguments/methods/functions
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file when a bug was fixed or a new feature was added.
referred to [TST: Added test for groupby dropping NA when grouping by columns from pbhoopala](https://github.com/pandas-dev/pandas/pull/50156) | https://api.github.com/repos/pandas-dev/pandas/pulls/50755 | 2023-01-15T06:16:59Z | 2023-01-17T17:24:37Z | 2023-01-17T17:24:37Z | 2023-01-18T03:04:10Z |
TST: Determine groupby-transform not convert back type | diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index 528f417ea1039..ab4f2bd5e529b 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -1046,6 +1046,26 @@ def test_groupby_transform_with_datetimes(func, values):
tm.assert_series_equal(result, expected)
+def test_groupby_transform_dtype():
+ # GH 22243
+ df = DataFrame({"a": [1], "val": [1.35]})
+
+ result = df["val"].transform(lambda x: x.map(lambda y: f"+{y}"))
+ expected1 = Series(["+1.35"], name="val", dtype="object")
+ tm.assert_series_equal(result, expected1)
+
+ result = df.groupby("a")["val"].transform(lambda x: x.map(lambda y: f"+{y}"))
+ tm.assert_series_equal(result, expected1)
+
+ result = df.groupby("a")["val"].transform(lambda x: x.map(lambda y: f"+({y})"))
+ expected2 = Series(["+(1.35)"], name="val", dtype="object")
+ tm.assert_series_equal(result, expected2)
+
+ df["val"] = df["val"].astype(object)
+ result = df.groupby("a")["val"].transform(lambda x: x.map(lambda y: f"+{y}"))
+ tm.assert_series_equal(result, expected1)
+
+
@pytest.mark.parametrize("func", ["cumsum", "cumprod", "cummin", "cummax"])
def test_transform_absent_categories(func):
# GH 16771
| - [x] closes #22243 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50754 | 2023-01-15T04:24:19Z | 2023-01-17T18:51:38Z | 2023-01-17T18:51:37Z | 2023-01-18T13:43:08Z |
ENH: Add lazy copy to shift | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 4ef91f6de5e27..9bcf7793201cd 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -9908,7 +9908,7 @@ def shift(
2020-01-08 45 48 52
"""
if periods == 0:
- return self.copy()
+ return self.copy(deep=None)
if freq is None:
# when freq is None, data is shifted, index is not
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py
index 5c24a180c4d6d..87903f20f5232 100644
--- a/pandas/tests/copy_view/test_methods.py
+++ b/pandas/tests/copy_view/test_methods.py
@@ -244,6 +244,77 @@ def test_filter(using_copy_on_write, filter_kwargs):
tm.assert_frame_equal(df, df_orig)
+def test_shift_no_op(using_copy_on_write):
+ df = DataFrame(
+ [[1, 2], [3, 4], [5, 6]],
+ index=date_range("2020-01-01", "2020-01-03"),
+ columns=["a", "b"],
+ )
+ df_orig = df.copy()
+ df2 = df.shift(periods=0)
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
+ tm.assert_frame_equal(df2, df_orig)
+
+
+def test_shift_index(using_copy_on_write):
+ df = DataFrame(
+ [[1, 2], [3, 4], [5, 6]],
+ index=date_range("2020-01-01", "2020-01-03"),
+ columns=["a", "b"],
+ )
+ df2 = df.shift(periods=1, axis=0)
+
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+
+def test_shift_rows_freq(using_copy_on_write):
+ df = DataFrame(
+ [[1, 2], [3, 4], [5, 6]],
+ index=date_range("2020-01-01", "2020-01-03"),
+ columns=["a", "b"],
+ )
+ df_orig = df.copy()
+ df_orig.index = date_range("2020-01-02", "2020-01-04")
+ df2 = df.shift(periods=1, freq="1D")
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+ else:
+ assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
+
+ df.iloc[0, 0] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+ tm.assert_frame_equal(df2, df_orig)
+
+
+def test_shift_columns(using_copy_on_write):
+ df = DataFrame(
+ [[1, 2], [3, 4], [5, 6]], columns=date_range("2020-01-01", "2020-01-02")
+ )
+ df2 = df.shift(periods=1, axis=1)
+
+ assert np.shares_memory(get_array(df2, "2020-01-02"), get_array(df, "2020-01-01"))
+ df.iloc[0, 1] = 0
+ if using_copy_on_write:
+ assert not np.shares_memory(
+ get_array(df2, "2020-01-02"), get_array(df, "2020-01-01")
+ )
+ expected = DataFrame(
+ [[np.nan, 1], [np.nan, 3], [np.nan, 5]],
+ columns=date_range("2020-01-01", "2020-01-02"),
+ )
+ tm.assert_frame_equal(df2, expected)
+
+
def test_pop(using_copy_on_write):
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
df_orig = df.copy()
| - [ ] xref #49473 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50753 | 2023-01-15T00:52:47Z | 2023-01-16T09:10:28Z | 2023-01-16T09:10:28Z | 2023-01-16T10:08:30Z |
DOC: Clean whatsnew and dep warning | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index b53595621af11..6c8dd2f8da938 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -572,7 +572,7 @@ Other API changes
Deprecations
~~~~~~~~~~~~
- Deprecated argument ``infer_datetime_format`` in :func:`to_datetime` and :func:`read_csv`, as a strict version of it is now the default (:issue:`48621`)
-- Deprecated :func:`pandas.io.sql.execute`(:issue:`50185`)
+- Deprecated :func:`pandas.io.sql.execute` (:issue:`50185`)
- :meth:`Index.is_boolean` has been deprecated. Use :func:`pandas.api.types.is_bool_dtype` instead (:issue:`50042`)
- :meth:`Index.is_integer` has been deprecated. Use :func:`pandas.api.types.is_integer_dtype` instead (:issue:`50042`)
- :meth:`Index.is_floating` has been deprecated. Use :func:`pandas.api.types.is_float_dtype` instead (:issue:`50042`)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 9e00278f85cbc..59af8f2bbcd51 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -2225,7 +2225,7 @@ def is_boolean(self) -> bool:
"""
warnings.warn(
f"{type(self).__name__}.is_boolean is deprecated. "
- "Use pandas.api.types.is_bool_type instead",
+ "Use pandas.api.types.is_bool_type instead.",
FutureWarning,
stacklevel=find_stack_level(),
)
@@ -2320,8 +2320,8 @@ def is_floating(self) -> bool:
False
"""
warnings.warn(
- f"{type(self).__name__}.is_floating is deprecated."
- "Use pandas.api.types.is_float_dtype instead",
+ f"{type(self).__name__}.is_floating is deprecated. "
+ "Use pandas.api.types.is_float_dtype instead.",
FutureWarning,
stacklevel=find_stack_level(),
)
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50752 | 2023-01-14T23:53:45Z | 2023-01-15T01:51:00Z | 2023-01-15T01:51:00Z | 2023-01-15T01:51:04Z |
ENH: Add use_nullable_dtypes option to read_json | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index b22590759ea3f..02e290ea28051 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -41,6 +41,7 @@ The ``use_nullable_dtypes`` keyword argument has been expanded to the following
* :func:`read_excel`
* :func:`read_html`
* :func:`read_xml`
+* :func:`read_json`
* :func:`read_sql`
* :func:`read_sql_query`
* :func:`read_sql_table`
@@ -55,6 +56,7 @@ to select the nullable dtypes implementation.
* :func:`read_excel`
* :func:`read_html`
* :func:`read_xml`
+* :func:`read_json`
* :func:`read_parquet`
* :func:`read_orc`
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index c501cad721ef5..aa1342d0f135f 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -43,6 +43,7 @@
ensure_str,
is_period_dtype,
)
+from pandas.core.dtypes.generic import ABCIndex
from pandas import (
DataFrame,
@@ -396,6 +397,7 @@ def read_json(
compression: CompressionOptions = ...,
nrows: int | None = ...,
storage_options: StorageOptions = ...,
+ use_nullable_dtypes: bool = ...,
) -> JsonReader[Literal["frame"]]:
...
@@ -419,6 +421,7 @@ def read_json(
compression: CompressionOptions = ...,
nrows: int | None = ...,
storage_options: StorageOptions = ...,
+ use_nullable_dtypes: bool = ...,
) -> JsonReader[Literal["series"]]:
...
@@ -442,6 +445,7 @@ def read_json(
compression: CompressionOptions = ...,
nrows: int | None = ...,
storage_options: StorageOptions = ...,
+ use_nullable_dtypes: bool = ...,
) -> Series:
...
@@ -465,6 +469,7 @@ def read_json(
compression: CompressionOptions = ...,
nrows: int | None = ...,
storage_options: StorageOptions = ...,
+ use_nullable_dtypes: bool = ...,
) -> DataFrame:
...
@@ -491,6 +496,7 @@ def read_json(
compression: CompressionOptions = "infer",
nrows: int | None = None,
storage_options: StorageOptions = None,
+ use_nullable_dtypes: bool = False,
) -> DataFrame | Series | JsonReader:
"""
Convert a JSON string to pandas object.
@@ -629,6 +635,19 @@ def read_json(
.. versionadded:: 1.2.0
+ use_nullable_dtypes : bool = False
+ Whether or not to use nullable dtypes as default when reading data. If
+ set to True, nullable dtypes are used for all dtypes that have a nullable
+ implementation, even if no nulls are present.
+
+ The nullable dtype implementation can be configured by calling
+ ``pd.set_option("mode.dtype_backend", "pandas")`` to use
+ numpy-backed nullable dtypes or
+ ``pd.set_option("mode.dtype_backend", "pyarrow")`` to use
+ pyarrow-backed nullable dtypes (using ``pd.ArrowDtype``).
+
+ .. versionadded:: 2.0
+
Returns
-------
Series or DataFrame
@@ -740,6 +759,7 @@ def read_json(
nrows=nrows,
storage_options=storage_options,
encoding_errors=encoding_errors,
+ use_nullable_dtypes=use_nullable_dtypes,
)
if chunksize:
@@ -775,6 +795,7 @@ def __init__(
nrows: int | None,
storage_options: StorageOptions = None,
encoding_errors: str | None = "strict",
+ use_nullable_dtypes: bool = False,
) -> None:
self.orient = orient
@@ -794,6 +815,7 @@ def __init__(
self.nrows = nrows
self.encoding_errors = encoding_errors
self.handles: IOHandles[str] | None = None
+ self.use_nullable_dtypes = use_nullable_dtypes
if self.chunksize is not None:
self.chunksize = validate_integer("chunksize", self.chunksize, 1)
@@ -903,7 +925,10 @@ def read(self) -> DataFrame | Series:
obj = self._get_object_parser(self._combine_lines(data_lines))
else:
obj = self._get_object_parser(self.data)
- return obj
+ if self.use_nullable_dtypes:
+ return obj.convert_dtypes(infer_objects=False)
+ else:
+ return obj
def _get_object_parser(self, json) -> DataFrame | Series:
"""
@@ -919,6 +944,7 @@ def _get_object_parser(self, json) -> DataFrame | Series:
"keep_default_dates": self.keep_default_dates,
"precise_float": self.precise_float,
"date_unit": self.date_unit,
+ "use_nullable_dtypes": self.use_nullable_dtypes,
}
obj = None
if typ == "frame":
@@ -977,7 +1003,10 @@ def __next__(self) -> DataFrame | Series:
self.close()
raise ex
- return obj
+ if self.use_nullable_dtypes:
+ return obj.convert_dtypes(infer_objects=False)
+ else:
+ return obj
def __enter__(self) -> JsonReader[FrameSeriesStrT]:
return self
@@ -1013,6 +1042,7 @@ def __init__(
keep_default_dates: bool = False,
precise_float: bool = False,
date_unit=None,
+ use_nullable_dtypes: bool = False,
) -> None:
self.json = json
@@ -1037,6 +1067,7 @@ def __init__(
self.date_unit = date_unit
self.keep_default_dates = keep_default_dates
self.obj: DataFrame | Series | None = None
+ self.use_nullable_dtypes = use_nullable_dtypes
def check_keys_split(self, decoded) -> None:
"""
@@ -1119,7 +1150,10 @@ def _try_convert_data(
if result:
return new_data, True
- if data.dtype == "object":
+ if self.use_nullable_dtypes and not isinstance(data, ABCIndex):
+ # Fall through for conversion later on
+ return data, True
+ elif data.dtype == "object":
# try float
try:
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index d1de676a4eb2e..f675c34e2779a 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -15,6 +15,7 @@
import pandas as pd
from pandas import (
+ NA,
DataFrame,
DatetimeIndex,
Series,
@@ -22,6 +23,10 @@
read_json,
)
import pandas._testing as tm
+from pandas.core.arrays import (
+ ArrowStringArray,
+ StringArray,
+)
def assert_json_roundtrip_equal(result, expected, orient):
@@ -1866,3 +1871,88 @@ def test_json_uint64(self):
df = DataFrame(data={"col1": [13342205958987758245, 12388075603347835679]})
result = df.to_json(orient="split")
assert result == expected
+
+ @pytest.mark.parametrize("dtype_backend", ["pandas", "pyarrow"])
+ @pytest.mark.parametrize(
+ "orient", ["split", "records", "values", "index", "columns"]
+ )
+ def test_read_json_nullable(self, string_storage, dtype_backend, orient):
+ # GH#50750
+ pa = pytest.importorskip("pyarrow")
+ df = DataFrame(
+ {
+ "a": Series([1, np.nan, 3], dtype="Int64"),
+ "b": Series([1, 2, 3], dtype="Int64"),
+ "c": Series([1.5, np.nan, 2.5], dtype="Float64"),
+ "d": Series([1.5, 2.0, 2.5], dtype="Float64"),
+ "e": [True, False, None],
+ "f": [True, False, True],
+ "g": ["a", "b", "c"],
+ "h": ["a", "b", None],
+ }
+ )
+
+ if string_storage == "python":
+ string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_))
+ string_array_na = StringArray(np.array(["a", "b", NA], dtype=np.object_))
+
+ else:
+ string_array = ArrowStringArray(pa.array(["a", "b", "c"]))
+ string_array_na = ArrowStringArray(pa.array(["a", "b", None]))
+
+ out = df.to_json(orient=orient)
+ with pd.option_context("mode.string_storage", string_storage):
+ with pd.option_context("mode.dtype_backend", dtype_backend):
+ result = read_json(out, use_nullable_dtypes=True, orient=orient)
+
+ expected = DataFrame(
+ {
+ "a": Series([1, np.nan, 3], dtype="Int64"),
+ "b": Series([1, 2, 3], dtype="Int64"),
+ "c": Series([1.5, np.nan, 2.5], dtype="Float64"),
+ "d": Series([1.5, 2.0, 2.5], dtype="Float64"),
+ "e": Series([True, False, NA], dtype="boolean"),
+ "f": Series([True, False, True], dtype="boolean"),
+ "g": string_array,
+ "h": string_array_na,
+ }
+ )
+
+ if dtype_backend == "pyarrow":
+
+ from pandas.arrays import ArrowExtensionArray
+
+ expected = DataFrame(
+ {
+ col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))
+ for col in expected.columns
+ }
+ )
+
+ if orient == "values":
+ expected.columns = list(range(0, 8))
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype_backend", ["pandas", "pyarrow"])
+ @pytest.mark.parametrize("orient", ["split", "records", "index"])
+ def test_read_json_nullable_series(self, string_storage, dtype_backend, orient):
+ # GH#50750
+ pa = pytest.importorskip("pyarrow")
+ ser = Series([1, np.nan, 3], dtype="Int64")
+
+ out = ser.to_json(orient=orient)
+ with pd.option_context("mode.string_storage", string_storage):
+ with pd.option_context("mode.dtype_backend", dtype_backend):
+ result = read_json(
+ out, use_nullable_dtypes=True, orient=orient, typ="series"
+ )
+
+ expected = Series([1, np.nan, 3], dtype="Int64")
+
+ if dtype_backend == "pyarrow":
+ from pandas.arrays import ArrowExtensionArray
+
+ expected = Series(ArrowExtensionArray(pa.array(expected, from_pandas=True)))
+
+ tm.assert_series_equal(result, expected)
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
This is a shortcut for now, but want to get the option in for 2.0, want to implement this properly afterwards | https://api.github.com/repos/pandas-dev/pandas/pulls/50750 | 2023-01-14T21:15:06Z | 2023-01-17T19:07:49Z | 2023-01-17T19:07:49Z | 2023-01-17T19:17:27Z |
TST: Consolidate tests that raise in groupby | diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py
index d3f9dd31e9fa1..487daddd3d214 100644
--- a/pandas/tests/groupby/aggregate/test_cython.py
+++ b/pandas/tests/groupby/aggregate/test_cython.py
@@ -96,13 +96,8 @@ def test_cython_agg_nothing_to_agg():
with pytest.raises(TypeError, match=msg):
frame.groupby("a")["b"].mean(numeric_only=True)
- with pytest.raises(TypeError, match="Could not convert (foo|bar)*"):
- frame.groupby("a")["b"].mean()
-
frame = DataFrame({"a": np.random.randint(0, 5, 50), "b": ["foo", "bar"] * 25})
- with pytest.raises(TypeError, match="Could not convert"):
- frame[["b"]].groupby(frame["a"]).mean()
result = frame[["b"]].groupby(frame["a"]).mean(numeric_only=True)
expected = DataFrame(
[], index=frame["a"].sort_values().drop_duplicates(), columns=[]
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py
index 986ee48ca9876..9fe35876dc5b5 100644
--- a/pandas/tests/groupby/test_categorical.py
+++ b/pandas/tests/groupby/test_categorical.py
@@ -103,9 +103,6 @@ def test_basic(): # TODO: split this test
gb = df.groupby("A", observed=False)
exp_idx = CategoricalIndex(["a", "b", "z"], name="A", ordered=True)
expected = DataFrame({"values": Series([3, 7, 0], index=exp_idx)})
- msg = "category type does not support sum operations"
- with pytest.raises(TypeError, match=msg):
- gb.sum()
result = gb.sum(numeric_only=True)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index d7b015fa7104a..a7bd89942ea79 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -465,8 +465,6 @@ def test_multi_func(df):
col2 = df["B"]
grouped = df.groupby([col1.get, col2.get])
- with pytest.raises(TypeError, match="Could not convert"):
- grouped.mean()
agged = grouped.mean(numeric_only=True)
expected = df.groupby(["A", "B"]).mean()
@@ -665,17 +663,11 @@ def test_groupby_as_index_agg(df):
# single-key
- with pytest.raises(TypeError, match="Could not convert"):
- grouped.agg(np.mean)
result = grouped[["C", "D"]].agg(np.mean)
- with pytest.raises(TypeError, match="Could not convert"):
- grouped.mean()
expected = grouped.mean(numeric_only=True)
tm.assert_frame_equal(result, expected)
result2 = grouped.agg({"C": np.mean, "D": np.sum})
- with pytest.raises(TypeError, match="Could not convert"):
- grouped.mean()
expected2 = grouped.mean(numeric_only=True)
expected2["D"] = grouped.sum()["D"]
tm.assert_frame_equal(result2, expected2)
@@ -793,11 +785,7 @@ def test_groupby_as_index_cython(df):
# single-key
grouped = data.groupby("A", as_index=False)
- with pytest.raises(TypeError, match="Could not convert"):
- grouped.mean()
result = grouped.mean(numeric_only=True)
- with pytest.raises(TypeError, match="Could not convert"):
- data.groupby(["A"]).mean()
expected = data.groupby(["A"]).mean(numeric_only=True)
expected.insert(0, "A", expected.index)
expected.index = RangeIndex(len(expected))
@@ -960,11 +948,7 @@ def test_empty_groups_corner(mframe):
)
grouped = df.groupby(["k1", "k2"])
- with pytest.raises(TypeError, match="Could not convert"):
- grouped.agg(np.mean)
result = grouped[["v1", "v2"]].agg(np.mean)
- with pytest.raises(TypeError, match="Could not convert"):
- grouped.mean()
expected = grouped.mean(numeric_only=True)
tm.assert_frame_equal(result, expected)
@@ -1148,8 +1132,6 @@ def test_groupby_with_hier_columns():
# add a nuisance column
sorted_columns, _ = columns.sortlevel(0)
df["A", "foo"] = "bar"
- with pytest.raises(TypeError, match="Could not convert"):
- df.groupby(level=0).mean()
result = df.groupby(level=0).mean(numeric_only=True)
tm.assert_index_equal(result.columns, df.columns[:-1])
@@ -1183,11 +1165,7 @@ def test_groupby_wrong_multi_labels():
def test_groupby_series_with_name(df):
- with pytest.raises(TypeError, match="Could not convert"):
- df.groupby(df["A"]).mean()
result = df.groupby(df["A"]).mean(numeric_only=True)
- with pytest.raises(TypeError, match="Could not convert"):
- df.groupby(df["A"], as_index=False).mean()
result2 = df.groupby(df["A"], as_index=False).mean(numeric_only=True)
assert result.index.name == "A"
assert "A" in result2
@@ -1337,11 +1315,7 @@ def test_groupby_unit64_float_conversion():
def test_groupby_list_infer_array_like(df):
- with pytest.raises(TypeError, match="Could not convert"):
- df.groupby(list(df["A"])).mean()
result = df.groupby(list(df["A"])).mean(numeric_only=True)
- with pytest.raises(TypeError, match="Could not convert"):
- df.groupby(df["A"]).mean()
expected = df.groupby(df["A"]).mean(numeric_only=True)
tm.assert_frame_equal(result, expected, check_names=False)
@@ -1455,8 +1429,6 @@ def test_groupby_2d_malformed():
d["zeros"] = [0, 0]
d["ones"] = [1, 1]
d["label"] = ["l1", "l2"]
- with pytest.raises(TypeError, match="Could not convert"):
- d.groupby(["group"]).mean()
tmp = d.groupby(["group"]).mean(numeric_only=True)
res_values = np.array([[0.0, 1.0], [0.0, 1.0]])
tm.assert_index_equal(tmp.columns, Index(["zeros", "ones"]))
diff --git a/pandas/tests/groupby/test_index_as_string.py b/pandas/tests/groupby/test_index_as_string.py
index d3d34dfd6f90a..e32b5eb44d5dc 100644
--- a/pandas/tests/groupby/test_index_as_string.py
+++ b/pandas/tests/groupby/test_index_as_string.py
@@ -48,12 +48,7 @@ def series():
)
def test_grouper_index_level_as_string(frame, key_strs, groupers):
if "B" not in key_strs or "outer" in frame.columns:
- with pytest.raises(TypeError, match="Could not convert"):
- frame.groupby(key_strs).mean()
result = frame.groupby(key_strs).mean(numeric_only=True)
-
- with pytest.raises(TypeError, match="Could not convert"):
- frame.groupby(groupers).mean()
expected = frame.groupby(groupers).mean(numeric_only=True)
else:
result = frame.groupby(key_strs).mean()
diff --git a/pandas/tests/groupby/test_raises.py b/pandas/tests/groupby/test_raises.py
index 1c889e6ed457a..6ceb23a3c44b6 100644
--- a/pandas/tests/groupby/test_raises.py
+++ b/pandas/tests/groupby/test_raises.py
@@ -4,23 +4,60 @@
import datetime
+import numpy as np
import pytest
-from pandas import DataFrame
+from pandas import (
+ Categorical,
+ DataFrame,
+ Grouper,
+ Series,
+)
from pandas.tests.groupby import get_groupby_method_args
+@pytest.fixture(
+ params=[
+ "a",
+ ["a"],
+ ["a", "b"],
+ Grouper(key="a"),
+ lambda x: x % 2,
+ [0, 0, 0, 1, 2, 2, 2, 3, 3],
+ np.array([0, 0, 0, 1, 2, 2, 2, 3, 3]),
+ dict(zip(range(9), [0, 0, 0, 1, 2, 2, 2, 3, 3])),
+ Series([1, 1, 1, 1, 1, 2, 2, 2, 2]),
+ [Series([1, 1, 1, 1, 1, 2, 2, 2, 2]), Series([3, 3, 4, 4, 4, 4, 4, 3, 3])],
+ ]
+)
+def by(request):
+ return request.param
+
+
+@pytest.fixture(params=[True, False])
+def groupby_series(request):
+ return request.param
+
+
@pytest.mark.parametrize("how", ["method", "agg", "transform"])
-def test_groupby_raises_string(how, groupby_func, as_index, sort):
+def test_groupby_raises_string(how, by, groupby_series, groupby_func):
df = DataFrame(
{
- "a": [1, 1, 1, 2, 2],
- "b": range(5),
- "c": list("xyzwt"),
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": list("xyzwtyuio"),
}
)
args = get_groupby_method_args(groupby_func, df)
- gb = df.groupby("a", as_index=as_index, sort=sort)
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ if groupby_func == "corrwith":
+ assert not hasattr(gb, "corrwith")
+ return
klass, msg = {
"all": (None, ""),
@@ -29,10 +66,22 @@ def test_groupby_raises_string(how, groupby_func, as_index, sort):
"corrwith": (TypeError, "Could not convert"),
"count": (None, ""),
"cumcount": (None, ""),
- "cummax": (NotImplementedError, "function is not implemented for this dtype"),
- "cummin": (NotImplementedError, "function is not implemented for this dtype"),
- "cumprod": (NotImplementedError, "function is not implemented for this dtype"),
- "cumsum": (NotImplementedError, "function is not implemented for this dtype"),
+ "cummax": (
+ (NotImplementedError, TypeError),
+ "(function|cummax) is not (implemented|supported) for (this|object) dtype",
+ ),
+ "cummin": (
+ (NotImplementedError, TypeError),
+ "(function|cummin) is not (implemented|supported) for (this|object) dtype",
+ ),
+ "cumprod": (
+ (NotImplementedError, TypeError),
+ "(function|cumprod) is not (implemented|supported) for (this|object) dtype",
+ ),
+ "cumsum": (
+ (NotImplementedError, TypeError),
+ "(function|cumsum) is not (implemented|supported) for (this|object) dtype",
+ ),
"diff": (TypeError, "unsupported operand type"),
"ffill": (None, ""),
"fillna": (None, ""),
@@ -41,7 +90,7 @@ def test_groupby_raises_string(how, groupby_func, as_index, sort):
"idxmin": (TypeError, "'argmin' not allowed for this dtype"),
"last": (None, ""),
"max": (None, ""),
- "mean": (TypeError, "Could not convert xyz to numeric"),
+ "mean": (TypeError, "Could not convert xy?z?w?t?y?u?i?o? to numeric"),
"median": (TypeError, "could not convert string to float"),
"min": (None, ""),
"ngroup": (None, ""),
@@ -77,15 +126,19 @@ def test_groupby_raises_string(how, groupby_func, as_index, sort):
@pytest.mark.parametrize("how", ["agg", "transform"])
-def test_groupby_raises_string_udf(how):
+def test_groupby_raises_string_udf(how, by, groupby_series):
df = DataFrame(
{
- "a": [1, 1, 1, 2, 2],
- "b": range(5),
- "c": list("xyzwt"),
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": list("xyzwtyuio"),
}
)
- gb = df.groupby("a")
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
def func(x):
raise TypeError("Test error message")
@@ -94,17 +147,54 @@ def func(x):
getattr(gb, how)(func)
+@pytest.mark.parametrize("how", ["agg", "transform"])
+@pytest.mark.parametrize("groupby_func_np", [np.sum, np.mean])
+def test_groupby_raises_string_np(how, by, groupby_series, groupby_func_np):
+ # GH#50749
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": list("xyzwtyuio"),
+ }
+ )
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ klass, msg = {
+ np.sum: (None, ""),
+ np.mean: (TypeError, "Could not convert xy?z?w?t?y?u?i?o? to numeric"),
+ }[groupby_func_np]
+
+ if klass is None:
+ getattr(gb, how)(groupby_func_np)
+ else:
+ with pytest.raises(klass, match=msg):
+ getattr(gb, how)(groupby_func_np)
+
+
@pytest.mark.parametrize("how", ["method", "agg", "transform"])
-def test_groupby_raises_datetime(how, groupby_func, as_index, sort):
+def test_groupby_raises_datetime(how, by, groupby_series, groupby_func):
df = DataFrame(
{
- "a": [1, 1, 1, 2, 2],
- "b": range(5),
- "c": datetime.datetime(2005, 1, 1, 10, 30, 23, 540000),
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": datetime.datetime(2005, 1, 1, 10, 30, 23, 540000),
}
)
args = get_groupby_method_args(groupby_func, df)
- gb = df.groupby("a", as_index=as_index, sort=sort)
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ if groupby_func == "corrwith":
+ assert not hasattr(gb, "corrwith")
+ return
klass, msg = {
"all": (None, ""),
@@ -161,15 +251,200 @@ def test_groupby_raises_datetime(how, groupby_func, as_index, sort):
@pytest.mark.parametrize("how", ["agg", "transform"])
-def test_groupby_raises_datetime_udf(how):
+def test_groupby_raises_datetime_udf(how, by, groupby_series):
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": datetime.datetime(2005, 1, 1, 10, 30, 23, 540000),
+ }
+ )
+
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ def func(x):
+ raise TypeError("Test error message")
+
+ with pytest.raises(TypeError, match="Test error message"):
+ getattr(gb, how)(func)
+
+
+@pytest.mark.parametrize("how", ["agg", "transform"])
+@pytest.mark.parametrize("groupby_func_np", [np.sum, np.mean])
+def test_groupby_raises_datetime_np(how, by, groupby_series, groupby_func_np):
+ # GH#50749
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": datetime.datetime(2005, 1, 1, 10, 30, 23, 540000),
+ }
+ )
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ klass, msg = {
+ np.sum: (TypeError, "datetime64 type does not support sum operations"),
+ np.mean: (None, ""),
+ }[groupby_func_np]
+
+ if klass is None:
+ getattr(gb, how)(groupby_func_np)
+ else:
+ with pytest.raises(klass, match=msg):
+ getattr(gb, how)(groupby_func_np)
+
+
+@pytest.mark.parametrize("how", ["method", "agg", "transform"])
+def test_groupby_raises_category(how, by, groupby_series, groupby_func):
+ # GH#50749
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": Categorical(
+ ["a", "a", "a", "a", "b", "b", "b", "b", "c"],
+ categories=["a", "b", "c", "d"],
+ ordered=True,
+ ),
+ }
+ )
+ args = get_groupby_method_args(groupby_func, df)
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ if groupby_func == "corrwith":
+ assert not hasattr(gb, "corrwith")
+ return
+
+ klass, msg = {
+ "all": (None, ""),
+ "any": (None, ""),
+ "bfill": (None, ""),
+ "corrwith": (
+ TypeError,
+ r"unsupported operand type\(s\) for \*: 'Categorical' and 'int'",
+ ),
+ "count": (None, ""),
+ "cumcount": (None, ""),
+ "cummax": (
+ (NotImplementedError, TypeError),
+ "(category type does not support cummax operations|"
+ + "category dtype not supported|"
+ + "cummax is not supported for category dtype)",
+ ),
+ "cummin": (
+ (NotImplementedError, TypeError),
+ "(category type does not support cummin operations|"
+ + "category dtype not supported|"
+ "cummin is not supported for category dtype)",
+ ),
+ "cumprod": (
+ (NotImplementedError, TypeError),
+ "(category type does not support cumprod operations|"
+ + "category dtype not supported|"
+ "cumprod is not supported for category dtype)",
+ ),
+ "cumsum": (
+ (NotImplementedError, TypeError),
+ "(category type does not support cumsum operations|"
+ + "category dtype not supported|"
+ "cumsum is not supported for category dtype)",
+ ),
+ "diff": (
+ TypeError,
+ r"unsupported operand type\(s\) for -: 'Categorical' and 'Categorical'",
+ ),
+ "ffill": (None, ""),
+ "fillna": (
+ TypeError,
+ r"Cannot setitem on a Categorical with a new category \(0\), "
+ + "set the categories first",
+ ),
+ "first": (None, ""),
+ "idxmax": (None, ""),
+ "idxmin": (None, ""),
+ "last": (None, ""),
+ "max": (None, ""),
+ "mean": (
+ TypeError,
+ "'Categorical' with dtype category does not support reduction 'mean'",
+ ),
+ "median": (
+ TypeError,
+ "'Categorical' with dtype category does not support reduction 'median'",
+ ),
+ "min": (None, ""),
+ "ngroup": (None, ""),
+ "nunique": (None, ""),
+ "pct_change": (
+ TypeError,
+ r"unsupported operand type\(s\) for /: 'Categorical' and 'Categorical'",
+ ),
+ "prod": (TypeError, "category type does not support prod operations"),
+ "quantile": (TypeError, "No matching signature found"),
+ "rank": (None, ""),
+ "sem": (ValueError, "Cannot cast object dtype to float64"),
+ "shift": (None, ""),
+ "size": (None, ""),
+ "skew": (
+ TypeError,
+ "'Categorical' with dtype category does not support reduction 'skew'",
+ ),
+ "std": (ValueError, "Cannot cast object dtype to float64"),
+ "sum": (TypeError, "category type does not support sum operations"),
+ "var": (
+ TypeError,
+ "'Categorical' with dtype category does not support reduction 'var'",
+ ),
+ }[groupby_func]
+
+ if klass is None:
+ if how == "method":
+ getattr(gb, groupby_func)(*args)
+ elif how == "agg":
+ gb.agg(groupby_func, *args)
+ else:
+ gb.transform(groupby_func, *args)
+ else:
+ with pytest.raises(klass, match=msg):
+ if how == "method":
+ getattr(gb, groupby_func)(*args)
+ elif how == "agg":
+ gb.agg(groupby_func, *args)
+ else:
+ gb.transform(groupby_func, *args)
+
+
+@pytest.mark.parametrize("how", ["agg", "transform"])
+def test_groupby_raises_category_udf(how, by, groupby_series):
+ # GH#50749
df = DataFrame(
{
- "a": [1, 1, 1, 2, 2],
- "b": range(5),
- "c": datetime.datetime(2005, 1, 1, 10, 30, 23, 540000),
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": Categorical(
+ ["a", "a", "a", "a", "b", "b", "b", "b", "c"],
+ categories=["a", "b", "c", "d"],
+ ordered=True,
+ ),
}
)
- gb = df.groupby("a")
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
def func(x):
raise TypeError("Test error message")
@@ -178,6 +453,172 @@ def func(x):
getattr(gb, how)(func)
+@pytest.mark.parametrize("how", ["agg", "transform"])
+@pytest.mark.parametrize("groupby_func_np", [np.sum, np.mean])
+def test_groupby_raises_category_np(how, by, groupby_series, groupby_func_np):
+ # GH#50749
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": Categorical(
+ ["a", "a", "a", "a", "b", "b", "b", "b", "c"],
+ categories=["a", "b", "c", "d"],
+ ordered=True,
+ ),
+ }
+ )
+ gb = df.groupby(by=by)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ klass, msg = {
+ np.sum: (TypeError, "category type does not support sum operations"),
+ np.mean: (
+ TypeError,
+ "'Categorical' with dtype category does not support reduction 'mean'",
+ ),
+ }[groupby_func_np]
+
+ if klass is None:
+ getattr(gb, how)(groupby_func_np)
+ else:
+ with pytest.raises(klass, match=msg):
+ getattr(gb, how)(groupby_func_np)
+
+
+@pytest.mark.parametrize("how", ["method", "agg", "transform"])
+def test_groupby_raises_category_on_category(
+ how, by, groupby_series, groupby_func, observed
+):
+ # GH#50749
+ df = DataFrame(
+ {
+ "a": Categorical(
+ ["a", "a", "a", "a", "b", "b", "b", "b", "c"],
+ categories=["a", "b", "c", "d"],
+ ordered=True,
+ ),
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": Categorical(
+ ["a", "a", "a", "a", "b", "b", "c", "c", "c"],
+ categories=["a", "b", "c", "d"],
+ ordered=True,
+ ),
+ }
+ )
+ args = get_groupby_method_args(groupby_func, df)
+ gb = df.groupby(by=by, observed=observed)
+
+ if groupby_series:
+ gb = gb["d"]
+
+ if groupby_func == "corrwith":
+ assert not hasattr(gb, "corrwith")
+ return
+
+ empty_groups = any(group.empty for group in gb.groups.values())
+
+ klass, msg = {
+ "all": (None, ""),
+ "any": (None, ""),
+ "bfill": (None, ""),
+ "corrwith": (
+ TypeError,
+ r"unsupported operand type\(s\) for \*: 'Categorical' and 'int'",
+ ),
+ "count": (None, ""),
+ "cumcount": (None, ""),
+ "cummax": (
+ (NotImplementedError, TypeError),
+ "(cummax is not supported for category dtype|"
+ + "category dtype not supported|"
+ + "category type does not support cummax operations)",
+ ),
+ "cummin": (
+ (NotImplementedError, TypeError),
+ "(cummin is not supported for category dtype|"
+ + "category dtype not supported|"
+ "category type does not support cummin operations)",
+ ),
+ "cumprod": (
+ (NotImplementedError, TypeError),
+ "(cumprod is not supported for category dtype|"
+ + "category dtype not supported|"
+ "category type does not support cumprod operations)",
+ ),
+ "cumsum": (
+ (NotImplementedError, TypeError),
+ "(cumsum is not supported for category dtype|"
+ + "category dtype not supported|"
+ + "category type does not support cumsum operations)",
+ ),
+ "diff": (TypeError, "unsupported operand type"),
+ "ffill": (None, ""),
+ "fillna": (
+ TypeError,
+ r"Cannot setitem on a Categorical with a new category \(0\), "
+ + "set the categories first",
+ ),
+ "first": (None, ""),
+ "idxmax": (ValueError, "attempt to get argmax of an empty sequence")
+ if empty_groups
+ else (None, ""),
+ "idxmin": (ValueError, "attempt to get argmin of an empty sequence")
+ if empty_groups
+ else (None, ""),
+ "last": (None, ""),
+ "max": (None, ""),
+ "mean": (
+ TypeError,
+ "'Categorical' with dtype category does not support reduction 'mean'",
+ ),
+ "median": (
+ TypeError,
+ "'Categorical' with dtype category does not support reduction 'median'",
+ ),
+ "min": (None, ""),
+ "ngroup": (None, ""),
+ "nunique": (None, ""),
+ "pct_change": (TypeError, "unsupported operand type"),
+ "prod": (TypeError, "category type does not support prod operations"),
+ "quantile": (TypeError, ""),
+ "rank": (None, ""),
+ "sem": (ValueError, "Cannot cast object dtype to float64"),
+ "shift": (None, ""),
+ "size": (None, ""),
+ "skew": (
+ TypeError,
+ "'Categorical' with dtype category does not support reduction 'skew'",
+ ),
+ "std": (ValueError, "Cannot cast object dtype to float64"),
+ "sum": (TypeError, "category type does not support sum operations"),
+ "var": (
+ TypeError,
+ "'Categorical' with dtype category does not support reduction 'var'",
+ ),
+ }[groupby_func]
+
+ if klass is None:
+ if how == "method":
+ getattr(gb, groupby_func)(*args)
+ elif how == "agg":
+ gb.agg(groupby_func, *args)
+ else:
+ gb.transform(groupby_func, *args)
+ else:
+ with pytest.raises(klass, match=msg):
+ if how == "method":
+ getattr(gb, groupby_func)(*args)
+ elif how == "agg":
+ gb.agg(groupby_func, *args)
+ else:
+ gb.transform(groupby_func, *args)
+
+
def test_subsetting_columns_axis_1_raises():
# GH 35443
df = DataFrame({"a": [1], "b": [2], "c": [3]})
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Part of #50133. Continue the work of @rhshadrach started in #50404 for the groupby consolidation. | https://api.github.com/repos/pandas-dev/pandas/pulls/50749 | 2023-01-14T20:32:54Z | 2023-02-09T21:55:55Z | 2023-02-09T21:55:55Z | 2023-02-10T22:55:57Z |
ENH: Add global nullable option | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index dc05745c8c0e5..5450fdf6b1923 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -49,6 +49,16 @@ The ``use_nullable_dtypes`` keyword argument has been expanded to the following
* :func:`read_feather`
* :func:`to_numeric`
+To simplify opting-in to nullable dtypes for these functions, a new option ``nullable_dtypes`` was added that allows setting
+the keyword argument globally to ``True`` if not specified directly. The option can be enabled
+through:
+
+.. ipython:: python
+
+ pd.options.mode.nullable_dtypes = True
+
+The option will only work for functions with the keyword ``use_nullable_dtypes``.
+
Additionally a new global configuration, ``mode.dtype_backend`` can now be used in conjunction with the parameter ``use_nullable_dtypes=True`` in the following functions
to select the nullable dtypes implementation.
diff --git a/pandas/_config/__init__.py b/pandas/_config/__init__.py
index 5219abc697dbd..d12dd3b4cb8aa 100644
--- a/pandas/_config/__init__.py
+++ b/pandas/_config/__init__.py
@@ -33,3 +33,8 @@
def using_copy_on_write():
_mode_options = _global_config["mode"]
return _mode_options["copy_on_write"] and _mode_options["data_manager"] == "block"
+
+
+def using_nullable_dtypes():
+ _mode_options = _global_config["mode"]
+ return _mode_options["nullable_dtypes"]
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index da9e7de9821b1..2e1ddb3c0a628 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -560,6 +560,22 @@ def use_inf_as_na_cb(key) -> None:
validator=is_one_of_factory(["pandas", "pyarrow"]),
)
+
+nullable_dtypes_doc = """
+: bool
+ If nullable dtypes should be returned. This is only applicable to functions
+ where the ``use_nullable_dtypes`` keyword is implemented.
+"""
+
+with cf.config_prefix("mode"):
+ cf.register_option(
+ "nullable_dtypes",
+ False,
+ nullable_dtypes_doc,
+ validator=is_bool,
+ )
+
+
# Set up the io.excel specific reader configuration.
reader_engine_doc = """
: string
diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py
index 64bb34241d956..a2bebc7dd3217 100644
--- a/pandas/core/tools/numeric.py
+++ b/pandas/core/tools/numeric.py
@@ -4,7 +4,10 @@
import numpy as np
-from pandas._config import get_option
+from pandas._config import (
+ get_option,
+ using_nullable_dtypes,
+)
from pandas._libs import lib
from pandas._typing import (
@@ -38,7 +41,7 @@ def to_numeric(
arg,
errors: DateTimeErrorChoices = "raise",
downcast: Literal["integer", "signed", "unsigned", "float"] | None = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
):
"""
Convert argument to a numeric type.
@@ -157,6 +160,12 @@ def to_numeric(
if errors not in ("ignore", "raise", "coerce"):
raise ValueError("invalid error value specified")
+ _use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
is_series = False
is_index = False
is_scalars = False
@@ -204,11 +213,11 @@ def to_numeric(
values = ensure_object(values)
coerce_numeric = errors not in ("ignore", "raise")
try:
- values, new_mask = lib.maybe_convert_numeric( # type: ignore[call-overload]
+ values, new_mask = lib.maybe_convert_numeric(
values,
set(),
coerce_numeric=coerce_numeric,
- convert_to_masked_nullable=use_nullable_dtypes,
+ convert_to_masked_nullable=_use_nullable_dtypes,
)
except (ValueError, TypeError):
if errors == "raise":
@@ -218,7 +227,7 @@ def to_numeric(
# Remove unnecessary values, is expected later anyway and enables
# downcasting
values = values[~new_mask]
- elif use_nullable_dtypes and new_mask is None:
+ elif _use_nullable_dtypes and new_mask is None:
new_mask = np.zeros(values.shape, dtype=np.bool_)
# attempt downcast only if the data has been successfully converted
diff --git a/pandas/io/clipboards.py b/pandas/io/clipboards.py
index 44bee11518cd3..0ba3846f415ad 100644
--- a/pandas/io/clipboards.py
+++ b/pandas/io/clipboards.py
@@ -4,6 +4,9 @@
from io import StringIO
import warnings
+from pandas._config import using_nullable_dtypes
+
+from pandas._libs import lib
from pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.generic import ABCDataFrame
@@ -15,7 +18,9 @@
def read_clipboard(
- sep: str = r"\s+", use_nullable_dtypes: bool = False, **kwargs
+ sep: str = r"\s+",
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
+ **kwargs,
): # pragma: no cover
r"""
Read text from clipboard and pass to read_csv.
@@ -56,6 +61,12 @@ def read_clipboard(
if encoding is not None and encoding.lower().replace("-", "") != "utf8":
raise NotImplementedError("reading from clipboard only supports utf-8 encoding")
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
from pandas.io.clipboard import clipboard_get
from pandas.io.parsers import read_csv
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 6f706a4554855..d44bdc466aed9 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -23,8 +23,12 @@
)
import zipfile
-from pandas._config import config
+from pandas._config import (
+ config,
+ using_nullable_dtypes,
+)
+from pandas._libs import lib
from pandas._libs.parsers import STR_NA_VALUES
from pandas._typing import (
DtypeArg,
@@ -380,7 +384,7 @@ def read_excel(
comment: str | None = ...,
skipfooter: int = ...,
storage_options: StorageOptions = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> DataFrame:
...
@@ -419,7 +423,7 @@ def read_excel(
comment: str | None = ...,
skipfooter: int = ...,
storage_options: StorageOptions = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> dict[IntStrT, DataFrame]:
...
@@ -458,7 +462,7 @@ def read_excel(
comment: str | None = None,
skipfooter: int = 0,
storage_options: StorageOptions = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
) -> DataFrame | dict[IntStrT, DataFrame]:
should_close = False
@@ -471,6 +475,12 @@ def read_excel(
"an ExcelFile - ExcelFile already has the engine set"
)
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
try:
data = io.parse(
sheet_name=sheet_name,
diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py
index cb2890777621a..136f49fef156e 100644
--- a/pandas/io/feather_format.py
+++ b/pandas/io/feather_format.py
@@ -6,6 +6,9 @@
Sequence,
)
+from pandas._config import using_nullable_dtypes
+
+from pandas._libs import lib
from pandas._typing import (
FilePath,
ReadBuffer,
@@ -103,7 +106,7 @@ def read_feather(
columns: Sequence[Hashable] | None = None,
use_threads: bool = True,
storage_options: StorageOptions = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
):
"""
Load a feather-format object from the file path.
@@ -143,6 +146,12 @@ def read_feather(
import_optional_dependency("pyarrow")
from pyarrow import feather
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
with get_handle(
path, "rb", storage_options=storage_options, is_text=False
) as handles:
diff --git a/pandas/io/html.py b/pandas/io/html.py
index f025e12bd0f55..dd1f7ef239f73 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -18,6 +18,9 @@
cast,
)
+from pandas._config import using_nullable_dtypes
+
+from pandas._libs import lib
from pandas._typing import (
BaseBuffer,
FilePath,
@@ -1036,7 +1039,7 @@ def read_html(
keep_default_na: bool = True,
displayed_only: bool = True,
extract_links: Literal[None, "header", "footer", "body", "all"] = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
) -> list[DataFrame]:
r"""
Read HTML tables into a ``list`` of ``DataFrame`` objects.
@@ -1206,6 +1209,12 @@ def read_html(
)
validate_header_arg(header)
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
io = stringify_path(io)
return _parse(
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index aa1342d0f135f..afb0be0729344 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -21,6 +21,9 @@
import numpy as np
+from pandas._config import using_nullable_dtypes
+
+from pandas._libs import lib
from pandas._libs.json import (
dumps,
loads,
@@ -496,7 +499,7 @@ def read_json(
compression: CompressionOptions = "infer",
nrows: int | None = None,
storage_options: StorageOptions = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
) -> DataFrame | Series | JsonReader:
"""
Convert a JSON string to pandas object.
@@ -732,6 +735,12 @@ def read_json(
if orient == "table" and convert_axes:
raise ValueError("cannot pass both convert_axes and orient='table'")
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
if dtype is None and orient != "table":
# error: Incompatible types in assignment (expression has type "bool", variable
# has type "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float],
diff --git a/pandas/io/orc.py b/pandas/io/orc.py
index 169cb5d16da8d..ccc7afe7ee0f7 100644
--- a/pandas/io/orc.py
+++ b/pandas/io/orc.py
@@ -8,8 +8,12 @@
Literal,
)
-from pandas._config import get_option
+from pandas._config import (
+ get_option,
+ using_nullable_dtypes,
+)
+from pandas._libs import lib
from pandas._typing import (
FilePath,
ReadBuffer,
@@ -33,7 +37,7 @@
def read_orc(
path: FilePath | ReadBuffer[bytes],
columns: list[str] | None = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
**kwargs,
) -> DataFrame:
"""
@@ -86,6 +90,12 @@ def read_orc(
orc = import_optional_dependency("pyarrow.orc")
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
with get_handle(path, "rb", is_text=False) as handles:
orc_file = orc.ORCFile(handles.handle)
pa_table = orc_file.read(columns=columns, **kwargs)
diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py
index cb66d1a422811..2a33ec8969838 100644
--- a/pandas/io/parquet.py
+++ b/pandas/io/parquet.py
@@ -9,6 +9,9 @@
)
from warnings import catch_warnings
+from pandas._config import using_nullable_dtypes
+
+from pandas._libs import lib
from pandas._typing import (
FilePath,
ReadBuffer,
@@ -453,7 +456,7 @@ def read_parquet(
engine: str = "auto",
columns: list[str] | None = None,
storage_options: StorageOptions = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
**kwargs,
) -> DataFrame:
"""
@@ -511,6 +514,12 @@ def read_parquet(
"""
impl = get_engine(engine)
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
return impl.read(
path,
columns=columns,
diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py
index b97c0161958fa..410b4fc0bf9c0 100644
--- a/pandas/io/parsers/readers.py
+++ b/pandas/io/parsers/readers.py
@@ -24,7 +24,10 @@
import numpy as np
-from pandas._config import get_option
+from pandas._config import (
+ get_option,
+ using_nullable_dtypes,
+)
from pandas._libs import lib
from pandas._libs.parsers import STR_NA_VALUES
@@ -639,7 +642,7 @@ def read_csv(
memory_map: bool = ...,
float_precision: Literal["high", "legacy"] | None = ...,
storage_options: StorageOptions = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> TextFileReader:
...
@@ -695,7 +698,7 @@ def read_csv(
memory_map: bool = ...,
float_precision: Literal["high", "legacy"] | None = ...,
storage_options: StorageOptions = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> TextFileReader:
...
@@ -751,7 +754,7 @@ def read_csv(
memory_map: bool = ...,
float_precision: Literal["high", "legacy"] | None = ...,
storage_options: StorageOptions = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> DataFrame:
...
@@ -807,7 +810,7 @@ def read_csv(
memory_map: bool = ...,
float_precision: Literal["high", "legacy"] | None = ...,
storage_options: StorageOptions = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> DataFrame | TextFileReader:
...
@@ -879,7 +882,7 @@ def read_csv(
memory_map: bool = False,
float_precision: Literal["high", "legacy"] | None = None,
storage_options: StorageOptions = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
) -> DataFrame | TextFileReader:
if infer_datetime_format is not lib.no_default:
warnings.warn(
@@ -904,6 +907,7 @@ def read_csv(
on_bad_lines,
names,
defaults={"delimiter": ","},
+ use_nullable_dtypes=use_nullable_dtypes,
)
kwds.update(kwds_defaults)
@@ -961,7 +965,7 @@ def read_table(
memory_map: bool = ...,
float_precision: str | None = ...,
storage_options: StorageOptions = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> TextFileReader:
...
@@ -1017,7 +1021,7 @@ def read_table(
memory_map: bool = ...,
float_precision: str | None = ...,
storage_options: StorageOptions = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> TextFileReader:
...
@@ -1073,7 +1077,7 @@ def read_table(
memory_map: bool = ...,
float_precision: str | None = ...,
storage_options: StorageOptions = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> DataFrame:
...
@@ -1129,7 +1133,7 @@ def read_table(
memory_map: bool = ...,
float_precision: str | None = ...,
storage_options: StorageOptions = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> DataFrame | TextFileReader:
...
@@ -1201,7 +1205,7 @@ def read_table(
memory_map: bool = False,
float_precision: str | None = None,
storage_options: StorageOptions = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
) -> DataFrame | TextFileReader:
# locals() should never be modified
kwds = locals().copy()
@@ -1217,6 +1221,7 @@ def read_table(
on_bad_lines,
names,
defaults={"delimiter": "\t"},
+ use_nullable_dtypes=use_nullable_dtypes,
)
kwds.update(kwds_defaults)
@@ -1229,7 +1234,7 @@ def read_fwf(
colspecs: Sequence[tuple[int, int]] | str | None = "infer",
widths: Sequence[int] | None = None,
infer_nrows: int = 100,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
**kwds,
) -> DataFrame | TextFileReader:
r"""
@@ -1292,6 +1297,12 @@ def read_fwf(
if colspecs not in (None, "infer") and widths is not None:
raise ValueError("You must specify only one of 'widths' and 'colspecs'")
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
# Compute 'colspecs' from 'widths', if specified.
if widths is not None:
colspecs, col = [], 0
@@ -1858,6 +1869,7 @@ def _refine_defaults_read(
on_bad_lines: str | Callable,
names: Sequence[Hashable] | None | lib.NoDefault,
defaults: dict[str, Any],
+ use_nullable_dtypes: bool | lib.NoDefault,
):
"""Validate/refine default values of input parameters of read_csv, read_table.
@@ -1971,6 +1983,13 @@ def _refine_defaults_read(
else:
raise ValueError(f"Argument {on_bad_lines} is invalid for on_bad_lines")
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+ kwds["use_nullable_dtypes"] = use_nullable_dtypes
+
return kwds
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 8acc57685dc16..8ba208aa84286 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -29,6 +29,8 @@
import numpy as np
+from pandas._config import using_nullable_dtypes
+
from pandas._libs import lib
from pandas._typing import (
DateTimeErrorChoices,
@@ -230,7 +232,7 @@ def read_sql_table(
parse_dates: list[str] | dict[str, str] | None = ...,
columns: list[str] | None = ...,
chunksize: None = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> DataFrame:
...
@@ -245,7 +247,7 @@ def read_sql_table(
parse_dates: list[str] | dict[str, str] | None = ...,
columns: list[str] | None = ...,
chunksize: int = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> Iterator[DataFrame]:
...
@@ -259,7 +261,7 @@ def read_sql_table(
parse_dates: list[str] | dict[str, str] | None = None,
columns: list[str] | None = None,
chunksize: int | None = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
) -> DataFrame | Iterator[DataFrame]:
"""
Read SQL database table into a DataFrame.
@@ -322,6 +324,12 @@ def read_sql_table(
--------
>>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP
"""
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
with pandasSQL_builder(con, schema=schema) as pandas_sql:
if not pandas_sql.has_table(table_name):
raise ValueError(f"Table {table_name} not found")
@@ -352,7 +360,7 @@ def read_sql_query(
parse_dates: list[str] | dict[str, str] | None = ...,
chunksize: None = ...,
dtype: DtypeArg | None = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> DataFrame:
...
@@ -367,7 +375,7 @@ def read_sql_query(
parse_dates: list[str] | dict[str, str] | None = ...,
chunksize: int = ...,
dtype: DtypeArg | None = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
) -> Iterator[DataFrame]:
...
@@ -381,7 +389,7 @@ def read_sql_query(
parse_dates: list[str] | dict[str, str] | None = None,
chunksize: int | None = None,
dtype: DtypeArg | None = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
) -> DataFrame | Iterator[DataFrame]:
"""
Read SQL query into a DataFrame.
@@ -446,6 +454,12 @@ def read_sql_query(
Any datetime values with time zone information parsed via the `parse_dates`
parameter will be converted to UTC.
"""
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
with pandasSQL_builder(con) as pandas_sql:
return pandas_sql.read_query(
sql,
@@ -469,7 +483,7 @@ def read_sql(
parse_dates=...,
columns: list[str] = ...,
chunksize: None = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
dtype: DtypeArg | None = None,
) -> DataFrame:
...
@@ -485,7 +499,7 @@ def read_sql(
parse_dates=...,
columns: list[str] = ...,
chunksize: int = ...,
- use_nullable_dtypes: bool = ...,
+ use_nullable_dtypes: bool | lib.NoDefault = ...,
dtype: DtypeArg | None = None,
) -> Iterator[DataFrame]:
...
@@ -500,7 +514,7 @@ def read_sql(
parse_dates=None,
columns: list[str] | None = None,
chunksize: int | None = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
dtype: DtypeArg | None = None,
) -> DataFrame | Iterator[DataFrame]:
"""
@@ -630,6 +644,12 @@ def read_sql(
0 0 2012-11-10
1 1 2010-11-12
"""
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
with pandasSQL_builder(con) as pandas_sql:
if isinstance(pandas_sql, SQLiteDatabase):
diff --git a/pandas/io/xml.py b/pandas/io/xml.py
index 1b32cf252d315..4e6afbf4f4164 100644
--- a/pandas/io/xml.py
+++ b/pandas/io/xml.py
@@ -11,6 +11,9 @@
Sequence,
)
+from pandas._config import using_nullable_dtypes
+
+from pandas._libs import lib
from pandas._typing import (
TYPE_CHECKING,
CompressionOptions,
@@ -868,7 +871,7 @@ def read_xml(
iterparse: dict[str, list[str]] | None = None,
compression: CompressionOptions = "infer",
storage_options: StorageOptions = None,
- use_nullable_dtypes: bool = False,
+ use_nullable_dtypes: bool | lib.NoDefault = lib.no_default,
) -> DataFrame:
r"""
Read XML document into a ``DataFrame`` object.
@@ -1110,6 +1113,12 @@ def read_xml(
2 triangle 180 3.0
"""
+ use_nullable_dtypes = (
+ use_nullable_dtypes
+ if use_nullable_dtypes is not lib.no_default
+ else using_nullable_dtypes()
+ )
+
return _parse(
path_or_buffer=path_or_buffer,
xpath=xpath,
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 5899125ca2904..f194cadbc73d8 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -540,7 +540,8 @@ def test_reader_dtype_str(self, read_ext, dtype, expected):
"dtype_backend",
["pandas", pytest.param("pyarrow", marks=td.skip_if_no("pyarrow"))],
)
- def test_use_nullable_dtypes(self, read_ext, dtype_backend):
+ @pytest.mark.parametrize("option", [True, False])
+ def test_use_nullable_dtypes(self, read_ext, dtype_backend, option):
# GH#36712
if read_ext in (".xlsb", ".xls"):
pytest.skip(f"No engine for filetype: '{read_ext}'")
@@ -562,9 +563,13 @@ def test_use_nullable_dtypes(self, read_ext, dtype_backend):
with tm.ensure_clean(read_ext) as file_path:
df.to_excel(file_path, "test", index=False)
with pd.option_context("mode.dtype_backend", dtype_backend):
- result = pd.read_excel(
- file_path, sheet_name="test", use_nullable_dtypes=True
- )
+ if not option:
+ result = pd.read_excel(
+ file_path, sheet_name="test", use_nullable_dtypes=True
+ )
+ else:
+ with pd.option_context("mode.nullable_dtypes", True):
+ result = pd.read_excel(file_path, sheet_name="test")
if dtype_backend == "pyarrow":
import pyarrow as pa
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index 31566f67bef2c..7b473a56aa200 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -1873,7 +1873,8 @@ def test_json_uint64(self):
@pytest.mark.parametrize(
"orient", ["split", "records", "values", "index", "columns"]
)
- def test_read_json_nullable(self, string_storage, dtype_backend, orient):
+ @pytest.mark.parametrize("option", [True, False])
+ def test_read_json_nullable(self, string_storage, dtype_backend, orient, option):
# GH#50750
pa = pytest.importorskip("pyarrow")
df = DataFrame(
@@ -1900,7 +1901,11 @@ def test_read_json_nullable(self, string_storage, dtype_backend, orient):
out = df.to_json(orient=orient)
with pd.option_context("mode.string_storage", string_storage):
with pd.option_context("mode.dtype_backend", dtype_backend):
- result = read_json(out, use_nullable_dtypes=True, orient=orient)
+ if option:
+ with pd.option_context("mode.nullable_dtypes", option):
+ result = read_json(out, orient=orient)
+ else:
+ result = read_json(out, use_nullable_dtypes=True, orient=orient)
expected = DataFrame(
{
diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
index 52b142d81cd5e..ca12b1ce4b967 100644
--- a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
+++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
@@ -530,6 +530,22 @@ def test_use_nullable_dtypes_pyarrow_backend(all_parsers, request):
tm.assert_frame_equal(result, expected)
+@pytest.mark.usefixtures("pyarrow_xfail")
+def test_use_nullable_dtypes_option(all_parsers):
+ # GH#50748
+
+ parser = all_parsers
+
+ data = """a
+1
+3
+"""
+ with pd.option_context("mode.nullable_dtypes", True):
+ result = parser.read_csv(StringIO(data))
+ expected = DataFrame({"a": pd.Series([1, 3], dtype="Int64")})
+ tm.assert_frame_equal(result, expected)
+
+
def test_ea_int_avoid_overflow(all_parsers):
# GH#32134
parser = all_parsers
diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py
index f4320f6480517..434e617ff05f9 100644
--- a/pandas/tests/io/parser/test_read_fwf.py
+++ b/pandas/tests/io/parser/test_read_fwf.py
@@ -994,3 +994,16 @@ def test_use_nullable_dtypes(string_storage, dtype_backend):
expected["i"] = ArrowExtensionArray(pa.array([None, None]))
tm.assert_frame_equal(result, expected)
+
+
+def test_use_nullable_dtypes_option():
+ # GH#50748
+
+ data = """a
+1
+3"""
+ with pd.option_context("mode.nullable_dtypes", True):
+ result = read_fwf(StringIO(data))
+
+ expected = DataFrame({"a": pd.Series([1, 3], dtype="Int64")})
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py
index ae9c5aacf6e6b..5e4b2c1ebad9d 100644
--- a/pandas/tests/io/test_clipboard.py
+++ b/pandas/tests/io/test_clipboard.py
@@ -466,3 +466,20 @@ def test_read_clipboard_nullable_dtypes(
expected["g"] = ArrowExtensionArray(pa.array([None, None]))
tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("engine", ["c", "python"])
+ def test_read_clipboard_nullable_dtypes_option(
+ self, request, mock_clipboard, engine
+ ):
+ # GH#50748
+
+ text = """a
+1
+2"""
+ mock_clipboard[request.node.name] = text
+
+ with pd.option_context("mode.nullable_dtypes", True):
+ result = read_clipboard(sep=",", engine=engine)
+
+ expected = DataFrame({"a": Series([1, 2], dtype="Int64")})
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py
index 28a6054098a6f..7e07ad0ec2ad3 100644
--- a/pandas/tests/io/test_feather.py
+++ b/pandas/tests/io/test_feather.py
@@ -200,7 +200,8 @@ def test_http_path(self, feather_file):
tm.assert_frame_equal(expected, res)
@pytest.mark.parametrize("dtype_backend", ["pandas", "pyarrow"])
- def test_read_json_nullable(self, string_storage, dtype_backend):
+ @pytest.mark.parametrize("option", [True, False])
+ def test_read_json_nullable(self, string_storage, dtype_backend, option):
# GH#50765
pa = pytest.importorskip("pyarrow")
df = pd.DataFrame(
@@ -228,7 +229,11 @@ def test_read_json_nullable(self, string_storage, dtype_backend):
to_feather(df, path)
with pd.option_context("mode.string_storage", string_storage):
with pd.option_context("mode.dtype_backend", dtype_backend):
- result = read_feather(path, use_nullable_dtypes=True)
+ if option:
+ with pd.option_context("mode.nullable_dtypes", option):
+ result = read_feather(path)
+ else:
+ result = read_feather(path, use_nullable_dtypes=True)
expected = pd.DataFrame(
{
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py
index f8284b5ab1c65..de36548f08a12 100644
--- a/pandas/tests/io/test_html.py
+++ b/pandas/tests/io/test_html.py
@@ -196,6 +196,17 @@ def test_use_nullable_dtypes(self, storage, dtype_backend):
tm.assert_frame_equal(result, expected)
+ def test_use_nullable_dtypes_option(self):
+ # GH#50748
+ df = DataFrame({"a": Series([1, np.nan, 3], dtype="Int64")})
+
+ out = df.to_html(index=False)
+ with pd.option_context("mode.nullable_dtypes", True):
+ result = self.read_html(out)[0]
+
+ expected = DataFrame({"a": Series([1, np.nan, 3], dtype="Int64")})
+ tm.assert_frame_equal(result, expected)
+
@pytest.mark.network
@tm.network(
url=(
diff --git a/pandas/tests/io/test_orc.py b/pandas/tests/io/test_orc.py
index a519d9536eb32..2a95240a5f83d 100644
--- a/pandas/tests/io/test_orc.py
+++ b/pandas/tests/io/test_orc.py
@@ -383,3 +383,16 @@ def test_orc_use_nullable_dtypes_pandas_backend():
)
tm.assert_frame_equal(result, expected)
+
+
+@td.skip_if_no("pyarrow", min_version="7.0.0")
+def test_orc_use_nullable_dtypes_option():
+ # GH#50748
+ df = pd.DataFrame({"int": list(range(1, 4))})
+
+ bytes_data = df.copy().to_orc()
+ with pd.option_context("mode.nullable_dtypes", True):
+ result = read_orc(BytesIO(bytes_data))
+
+ expected = pd.DataFrame({"int": pd.Series([1, 2, 3], dtype="Int64")})
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index b5841593d4f45..4c884e20cf423 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -640,6 +640,28 @@ def test_use_nullable_dtypes(self, engine, request):
expected = expected.drop("c", axis=1)
tm.assert_frame_equal(result2, expected)
+ def test_use_nullable_dtypes_option(self, engine, request):
+ # GH#50748
+ import pyarrow.parquet as pq
+
+ if engine == "fastparquet":
+ # We are manually disabling fastparquet's
+ # nullable dtype support pending discussion
+ mark = pytest.mark.xfail(
+ reason="Fastparquet nullable dtype support is disabled"
+ )
+ request.node.add_marker(mark)
+
+ table = pyarrow.table({"a": pyarrow.array([1, 2, 3, None], "int64")})
+ with tm.ensure_clean() as path:
+ # write manually with pyarrow to write integers
+ pq.write_table(table, path)
+ with pd.option_context("mode.nullable_dtypes", True):
+ result2 = read_parquet(path, engine=engine)
+
+ expected = pd.DataFrame({"a": pd.array([1, 2, 3, None], dtype="Int64")})
+ tm.assert_frame_equal(result2, expected)
+
@pytest.mark.parametrize(
"dtype",
[
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index a1dbec1bb2f44..a5bcfa8845785 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -2291,17 +2291,22 @@ def test_get_engine_auto_error_message(self):
pass
# TODO(GH#36893) fill this in when we add more engines
+ @pytest.mark.parametrize("option", [True, False])
@pytest.mark.parametrize("func", ["read_sql", "read_sql_query"])
- def test_read_sql_nullable_dtypes(self, string_storage, func):
+ def test_read_sql_nullable_dtypes(self, string_storage, func, option):
# GH#50048
table = "test"
df = self.nullable_data()
df.to_sql(table, self.conn, index=False, if_exists="replace")
with pd.option_context("mode.string_storage", string_storage):
- result = getattr(pd, func)(
- f"Select * from {table}", self.conn, use_nullable_dtypes=True
- )
+ if option:
+ with pd.option_context("mode.nullable_dtypes", True):
+ result = getattr(pd, func)(f"Select * from {table}", self.conn)
+ else:
+ result = getattr(pd, func)(
+ f"Select * from {table}", self.conn, use_nullable_dtypes=True
+ )
expected = self.nullable_expected(string_storage)
tm.assert_frame_equal(result, expected)
@@ -2316,15 +2321,20 @@ def test_read_sql_nullable_dtypes(self, string_storage, func):
for result in iterator:
tm.assert_frame_equal(result, expected)
+ @pytest.mark.parametrize("option", [True, False])
@pytest.mark.parametrize("func", ["read_sql", "read_sql_table"])
- def test_read_sql_nullable_dtypes_table(self, string_storage, func):
+ def test_read_sql_nullable_dtypes_table(self, string_storage, func, option):
# GH#50048
table = "test"
df = self.nullable_data()
df.to_sql(table, self.conn, index=False, if_exists="replace")
with pd.option_context("mode.string_storage", string_storage):
- result = getattr(pd, func)(table, self.conn, use_nullable_dtypes=True)
+ if option:
+ with pd.option_context("mode.nullable_dtypes", True):
+ result = getattr(pd, func)(table, self.conn)
+ else:
+ result = getattr(pd, func)(table, self.conn, use_nullable_dtypes=True)
expected = self.nullable_expected(string_storage)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py
index 6aaa11866a584..2d3435eab9f60 100644
--- a/pandas/tests/io/xml/test_xml.py
+++ b/pandas/tests/io/xml/test_xml.py
@@ -1842,3 +1842,21 @@ def test_read_xml_nullable_dtypes(parser, string_storage, dtype_backend):
expected["g"] = ArrowExtensionArray(pa.array([None, None]))
tm.assert_frame_equal(result, expected)
+
+
+def test_use_nullable_dtypes_option(parser):
+ # GH#50748
+
+ data = """<?xml version='1.0' encoding='utf-8'?>
+ <data xmlns="http://example.com">
+ <row>
+ <a>1</a>
+ </row>
+ <row>
+ <a>3</a>
+ </row>
+ </data>"""
+ with pd.option_context("mode.nullable_dtypes", True):
+ result = read_xml(data, parser=parser)
+ expected = DataFrame({"a": Series([1, 3], dtype="Int64")})
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/tools/test_to_numeric.py b/pandas/tests/tools/test_to_numeric.py
index a2b94883d457d..8b57bbe03f9e7 100644
--- a/pandas/tests/tools/test_to_numeric.py
+++ b/pandas/tests/tools/test_to_numeric.py
@@ -838,6 +838,15 @@ def test_to_numeric_use_nullable_dtypes_na(val, dtype):
tm.assert_series_equal(result, expected)
+def test_to_numeric_use_nullable_dtypes_option():
+ # GH#50748
+ ser = Series([1, None], dtype=object)
+ with option_context("mode.nullable_dtypes", True):
+ result = to_numeric(ser)
+ expected = Series([1, pd.NA], dtype="Int64")
+ tm.assert_series_equal(result, expected)
+
+
@pytest.mark.parametrize(
"val, dtype, downcast",
[
| - [x] closes #50747 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50748 | 2023-01-14T19:23:38Z | 2023-01-24T13:34:14Z | 2023-01-24T13:34:14Z | 2023-01-24T13:34:18Z |
ENH: Add lazy copy to replace | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 46f8c73027f48..ef4746311645c 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5530,7 +5530,7 @@ def _replace_columnwise(
DataFrame or None
"""
# Operate column-wise
- res = self if inplace else self.copy()
+ res = self if inplace else self.copy(deep=None)
ax = self.columns
for i, ax_value in enumerate(ax):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 4ef91f6de5e27..1604748fef2be 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -7046,6 +7046,7 @@ def replace(
to_replace = [to_replace]
if isinstance(to_replace, (tuple, list)):
+ # TODO: Consider copy-on-write for non-replaced columns's here
if isinstance(self, ABCDataFrame):
from pandas import Series
@@ -7105,7 +7106,7 @@ def replace(
if not self.size:
if inplace:
return None
- return self.copy()
+ return self.copy(deep=None)
if is_dict_like(to_replace):
if is_dict_like(value): # {'A' : NA} -> {'A' : 0}
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 2ce294f257d75..1a0aba0778da5 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1220,10 +1220,16 @@ def value_getitem(placement):
if inplace and blk.should_store(value):
# Updating inplace -> check if we need to do Copy-on-Write
if using_copy_on_write() and not self._has_no_reference_block(blkno_l):
- blk.set_inplace(blk_locs, value_getitem(val_locs), copy=True)
+ nbs_tup = tuple(blk.delete(blk_locs))
+ first_nb = new_block_2d(
+ value_getitem(val_locs), BlockPlacement(blk.mgr_locs[blk_locs])
+ )
+ if self.refs is not None:
+ self.refs.extend([self.refs[blkno_l]] * len(nbs_tup))
self._clear_reference_block(blkno_l)
else:
blk.set_inplace(blk_locs, value_getitem(val_locs))
+ continue
else:
unfit_mgr_locs.append(blk.mgr_locs.as_array[blk_locs])
unfit_val_locs.append(val_locs)
@@ -1231,25 +1237,26 @@ def value_getitem(placement):
# If all block items are unfit, schedule the block for removal.
if len(val_locs) == len(blk.mgr_locs):
removed_blknos.append(blkno_l)
+ continue
else:
nbs = blk.delete(blk_locs)
# Add first block where old block was and remaining blocks at
# the end to avoid updating all block numbers
first_nb = nbs[0]
nbs_tup = tuple(nbs[1:])
- nr_blocks = len(self.blocks)
- blocks_tup = (
- self.blocks[:blkno_l]
- + (first_nb,)
- + self.blocks[blkno_l + 1 :]
- + nbs_tup
- )
- self.blocks = blocks_tup
- self._blklocs[first_nb.mgr_locs.indexer] = np.arange(len(first_nb))
+ nr_blocks = len(self.blocks)
+ blocks_tup = (
+ self.blocks[:blkno_l]
+ + (first_nb,)
+ + self.blocks[blkno_l + 1 :]
+ + nbs_tup
+ )
+ self.blocks = blocks_tup
+ self._blklocs[first_nb.mgr_locs.indexer] = np.arange(len(first_nb))
- for i, nb in enumerate(nbs_tup):
- self._blklocs[nb.mgr_locs.indexer] = np.arange(len(nb))
- self._blknos[nb.mgr_locs.indexer] = i + nr_blocks
+ for i, nb in enumerate(nbs_tup):
+ self._blklocs[nb.mgr_locs.indexer] = np.arange(len(nb))
+ self._blknos[nb.mgr_locs.indexer] = i + nr_blocks
if len(removed_blknos):
# Remove blocks & update blknos and refs accordingly
diff --git a/pandas/tests/copy_view/test_internals.py b/pandas/tests/copy_view/test_internals.py
index 1938a1c58fe3d..506ae7d3465c5 100644
--- a/pandas/tests/copy_view/test_internals.py
+++ b/pandas/tests/copy_view/test_internals.py
@@ -5,6 +5,7 @@
import pandas as pd
from pandas import DataFrame
+import pandas._testing as tm
from pandas.tests.copy_view.util import get_array
@@ -93,3 +94,49 @@ def test_switch_options():
subset.iloc[0, 0] = 0
# df updated with CoW disabled
assert df.iloc[0, 0] == 0
+
+
+@td.skip_array_manager_invalid_test
+@pytest.mark.parametrize("dtype", [np.intp, np.int8])
+@pytest.mark.parametrize(
+ "locs, arr",
+ [
+ ([0], np.array([-1, -2, -3])),
+ ([1], np.array([-1, -2, -3])),
+ ([5], np.array([-1, -2, -3])),
+ ([0, 1], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
+ ([0, 2], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
+ ([0, 1, 2], np.array([[-1, -2, -3], [-4, -5, -6], [-4, -5, -6]]).T),
+ ([1, 2], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
+ ([1, 3], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
+ ([1, 3], np.array([[-1, -2, -3], [-4, -5, -6]]).T),
+ ],
+)
+def test_iset_splits_blocks_inplace(using_copy_on_write, locs, arr, dtype):
+ # Nothing currently calls iset with
+ # more than 1 loc with inplace=True (only happens with inplace=False)
+ # but ensure that it works
+ df = DataFrame(
+ {
+ "a": [1, 2, 3],
+ "b": [4, 5, 6],
+ "c": [7, 8, 9],
+ "d": [10, 11, 12],
+ "e": [13, 14, 15],
+ "f": ["a", "b", "c"],
+ },
+ )
+ arr = arr.astype(dtype)
+ df_orig = df.copy()
+ df2 = df.copy(deep=None) # Trigger a CoW (if enabled, otherwise makes copy)
+ df2._mgr.iset(locs, arr, inplace=True)
+
+ tm.assert_frame_equal(df, df_orig)
+
+ if using_copy_on_write:
+ for i, col in enumerate(df.columns):
+ if i not in locs:
+ assert np.shares_memory(get_array(df, col), get_array(df2, col))
+ else:
+ for col in df.columns:
+ assert not np.shares_memory(get_array(df, col), get_array(df2, col))
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py
index 5c24a180c4d6d..d1184c3a70610 100644
--- a/pandas/tests/copy_view/test_methods.py
+++ b/pandas/tests/copy_view/test_methods.py
@@ -903,6 +903,44 @@ def test_squeeze(using_copy_on_write):
assert df.loc[0, "a"] == 0
+@pytest.mark.parametrize(
+ "replace_kwargs",
+ [
+ {"to_replace": {"a": 1, "b": 4}, "value": -1},
+ # Test CoW splits blocks to avoid copying unchanged columns
+ {"to_replace": {"a": 1}, "value": -1},
+ {"to_replace": {"b": 4}, "value": -1},
+ {"to_replace": {"b": {4: 1}}},
+ # TODO: Add these in a further optimization
+ # We would need to see which columns got replaced in the mask
+ # which could be expensive
+ # {"to_replace": {"b": 1}},
+ # 1
+ ],
+)
+def test_replace(using_copy_on_write, replace_kwargs):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": ["foo", "bar", "baz"]})
+ df_orig = df.copy()
+
+ df_replaced = df.replace(**replace_kwargs)
+
+ if using_copy_on_write:
+ if (df_replaced["b"] == df["b"]).all():
+ assert np.shares_memory(get_array(df_replaced, "b"), get_array(df, "b"))
+ assert np.shares_memory(get_array(df_replaced, "c"), get_array(df, "c"))
+
+ # mutating squeezed df triggers a copy-on-write for that column/block
+ df_replaced.loc[0, "c"] = -1
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(df_replaced, "c"), get_array(df, "c"))
+
+ if "a" in replace_kwargs["to_replace"]:
+ arr = get_array(df_replaced, "a")
+ df_replaced.loc[0, "a"] = 100
+ assert np.shares_memory(get_array(df_replaced, "a"), arr)
+ tm.assert_frame_equal(df, df_orig)
+
+
def test_putmask(using_copy_on_write):
df = DataFrame({"a": [1, 2], "b": 1, "c": 2})
view = df[:]
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
cc @lithomas1 as discussed on slack | https://api.github.com/repos/pandas-dev/pandas/pulls/50746 | 2023-01-14T19:11:26Z | 2023-01-17T04:13:44Z | 2023-01-17T04:13:44Z | 2023-01-17T16:52:08Z |
REF: groupby Series selection with as_index=False | diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 02a9444dd4f97..c28da1bc758cd 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -2,12 +2,14 @@
import abc
from collections import defaultdict
+from contextlib import nullcontext
from functools import partial
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
+ ContextManager,
DefaultDict,
Dict,
Hashable,
@@ -292,6 +294,10 @@ def agg_list_like(self) -> DataFrame | Series:
-------
Result of aggregation.
"""
+ from pandas.core.groupby.generic import (
+ DataFrameGroupBy,
+ SeriesGroupBy,
+ )
from pandas.core.reshape.concat import concat
obj = self.obj
@@ -312,26 +318,36 @@ def agg_list_like(self) -> DataFrame | Series:
results = []
keys = []
- # degenerate case
- if selected_obj.ndim == 1:
- for a in arg:
- colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj)
- new_res = colg.aggregate(a)
- results.append(new_res)
+ is_groupby = isinstance(obj, (DataFrameGroupBy, SeriesGroupBy))
+ context_manager: ContextManager
+ if is_groupby:
+ # When as_index=False, we combine all results using indices
+ # and adjust index after
+ context_manager = com.temp_setattr(obj, "as_index", True)
+ else:
+ context_manager = nullcontext()
+ with context_manager:
+ # degenerate case
+ if selected_obj.ndim == 1:
- # make sure we find a good name
- name = com.get_callable_name(a) or a
- keys.append(name)
+ for a in arg:
+ colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj)
+ new_res = colg.aggregate(a)
+ results.append(new_res)
- # multiples
- else:
- indices = []
- for index, col in enumerate(selected_obj):
- colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index])
- new_res = colg.aggregate(arg)
- results.append(new_res)
- indices.append(index)
- keys = selected_obj.columns.take(indices)
+ # make sure we find a good name
+ name = com.get_callable_name(a) or a
+ keys.append(name)
+
+ # multiples
+ else:
+ indices = []
+ for index, col in enumerate(selected_obj):
+ colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index])
+ new_res = colg.aggregate(arg)
+ results.append(new_res)
+ indices.append(index)
+ keys = selected_obj.columns.take(indices)
try:
concatenated = concat(results, keys=keys, axis=1, sort=False)
@@ -366,6 +382,10 @@ def agg_dict_like(self) -> DataFrame | Series:
Result of aggregation.
"""
from pandas import Index
+ from pandas.core.groupby.generic import (
+ DataFrameGroupBy,
+ SeriesGroupBy,
+ )
from pandas.core.reshape.concat import concat
obj = self.obj
@@ -384,15 +404,24 @@ def agg_dict_like(self) -> DataFrame | Series:
arg = self.normalize_dictlike_arg("agg", selected_obj, arg)
- if selected_obj.ndim == 1:
- # key only used for output
- colg = obj._gotitem(selection, ndim=1)
- results = {key: colg.agg(how) for key, how in arg.items()}
+ is_groupby = isinstance(obj, (DataFrameGroupBy, SeriesGroupBy))
+ context_manager: ContextManager
+ if is_groupby:
+ # When as_index=False, we combine all results using indices
+ # and adjust index after
+ context_manager = com.temp_setattr(obj, "as_index", True)
else:
- # key used for column selection and output
- results = {
- key: obj._gotitem(key, ndim=1).agg(how) for key, how in arg.items()
- }
+ context_manager = nullcontext()
+ with context_manager:
+ if selected_obj.ndim == 1:
+ # key only used for output
+ colg = obj._gotitem(selection, ndim=1)
+ results = {key: colg.agg(how) for key, how in arg.items()}
+ else:
+ # key used for column selection and output
+ results = {
+ key: obj._gotitem(key, ndim=1).agg(how) for key, how in arg.items()
+ }
# set the final keys
keys = list(arg.keys())
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 3f32f3cff8607..9cf93ea8eee2f 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -216,6 +216,9 @@ def _obj_with_exclusions(self):
if self._selection is not None and isinstance(self.obj, ABCDataFrame):
return self.obj[self._selection_list]
+ if isinstance(self.obj, ABCSeries):
+ return self.obj
+
if len(self.exclusions) > 0:
# equivalent to `self.obj.drop(self.exclusions, axis=1)
# but this avoids consolidating and making a copy
@@ -235,17 +238,11 @@ def __getitem__(self, key):
raise KeyError(f"Columns not found: {str(bad_keys)[1:-1]}")
return self._gotitem(list(key), ndim=2)
- elif not getattr(self, "as_index", False):
- if key not in self.obj.columns:
- raise KeyError(f"Column not found: {key}")
- return self._gotitem(key, ndim=2)
-
else:
if key not in self.obj:
raise KeyError(f"Column not found: {key}")
- subset = self.obj[key]
- ndim = subset.ndim
- return self._gotitem(key, ndim=ndim, subset=subset)
+ ndim = self.obj[key].ndim
+ return self._gotitem(key, ndim=ndim)
def _gotitem(self, key, ndim: int, subset=None):
"""
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 905c1193713cc..2340c36d14301 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -248,7 +248,11 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
data.to_frame(), func, *args, engine_kwargs=engine_kwargs, **kwargs
)
index = self.grouper.result_index
- return self.obj._constructor(result.ravel(), index=index, name=data.name)
+ result = self.obj._constructor(result.ravel(), index=index, name=data.name)
+ if not self.as_index:
+ result = self._insert_inaxis_grouper(result)
+ result.index = default_index(len(result))
+ return result
relabeling = func is None
columns = None
@@ -268,6 +272,9 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
# columns is not narrowed by mypy from relabeling flag
assert columns is not None # for mypy
ret.columns = columns
+ if not self.as_index:
+ ret = self._insert_inaxis_grouper(ret)
+ ret.index = default_index(len(ret))
return ret
else:
@@ -287,23 +294,24 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
# result is a dict whose keys are the elements of result_index
index = self.grouper.result_index
- return Series(result, index=index)
+ result = Series(result, index=index)
+ if not self.as_index:
+ result = self._insert_inaxis_grouper(result)
+ result.index = default_index(len(result))
+ return result
agg = aggregate
def _aggregate_multiple_funcs(self, arg) -> DataFrame:
if isinstance(arg, dict):
-
- # show the deprecation, but only if we
- # have not shown a higher level one
- # GH 15931
- raise SpecificationError("nested renamer is not supported")
-
- if any(isinstance(x, (tuple, list)) for x in arg):
+ if self.as_index:
+ # GH 15931
+ raise SpecificationError("nested renamer is not supported")
+ else:
+ # GH#50684 - This accidentally worked in 1.x
+ arg = list(arg.items())
+ elif any(isinstance(x, (tuple, list)) for x in arg):
arg = [(x, x) if not isinstance(x, (tuple, list)) else x for x in arg]
-
- # indicated column order
- columns = next(zip(*arg))
else:
# list of functions / function names
columns = []
@@ -313,10 +321,13 @@ def _aggregate_multiple_funcs(self, arg) -> DataFrame:
arg = zip(columns, arg)
results: dict[base.OutputKey, DataFrame | Series] = {}
- for idx, (name, func) in enumerate(arg):
+ with com.temp_setattr(self, "as_index", True):
+ # Combine results using the index, need to adjust index after
+ # if as_index=False (GH#50724)
+ for idx, (name, func) in enumerate(arg):
- key = base.OutputKey(label=name, position=idx)
- results[key] = self.aggregate(func)
+ key = base.OutputKey(label=name, position=idx)
+ results[key] = self.aggregate(func)
if any(isinstance(x, DataFrame) for x in results.values()):
from pandas import concat
@@ -396,12 +407,18 @@ def _wrap_applied_output(
)
if isinstance(result, Series):
result.name = self.obj.name
+ if not self.as_index and not_indexed_same:
+ result = self._insert_inaxis_grouper(result)
+ result.index = default_index(len(result))
return result
else:
# GH #6265 #24880
result = self.obj._constructor(
data=values, index=self.grouper.result_index, name=self.obj.name
)
+ if not self.as_index:
+ result = self._insert_inaxis_grouper(result)
+ result.index = default_index(len(result))
return self._reindex_output(result)
def _aggregate_named(self, func, *args, **kwargs):
@@ -577,7 +594,7 @@ def true_and_notna(x) -> bool:
filtered = self._apply_filter(indices, dropna)
return filtered
- def nunique(self, dropna: bool = True) -> Series:
+ def nunique(self, dropna: bool = True) -> Series | DataFrame:
"""
Return number of unique elements in the group.
@@ -629,7 +646,12 @@ def nunique(self, dropna: bool = True) -> Series:
# GH#21334s
res[ids[idx]] = out
- result = self.obj._constructor(res, index=ri, name=self.obj.name)
+ result: Series | DataFrame = self.obj._constructor(
+ res, index=ri, name=self.obj.name
+ )
+ if not self.as_index:
+ result = self._insert_inaxis_grouper(result)
+ result.index = default_index(len(result))
return self._reindex_output(result, fill_value=0)
@doc(Series.describe)
@@ -643,12 +665,11 @@ def value_counts(
ascending: bool = False,
bins=None,
dropna: bool = True,
- ) -> Series:
+ ) -> Series | DataFrame:
if bins is None:
result = self._value_counts(
normalize=normalize, sort=sort, ascending=ascending, dropna=dropna
)
- assert isinstance(result, Series)
return result
from pandas.core.reshape.merge import get_join_indexers
@@ -786,7 +807,11 @@ def build_codes(lev_codes: np.ndarray) -> np.ndarray:
if is_integer_dtype(out.dtype):
out = ensure_int64(out)
- return self.obj._constructor(out, index=mi, name=self.obj.name)
+ result = self.obj._constructor(out, index=mi, name=self.obj.name)
+ if not self.as_index:
+ result.name = "proportion" if normalize else "count"
+ result = result.reset_index()
+ return result
def fillna(
self,
@@ -1274,7 +1299,7 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
result.columns = result.columns.droplevel(-1)
if not self.as_index:
- self._insert_inaxis_grouper_inplace(result)
+ result = self._insert_inaxis_grouper(result)
result.index = default_index(len(result))
return result
@@ -1386,7 +1411,7 @@ def _wrap_applied_output(
return self.obj._constructor_sliced(values, index=key_index)
else:
result = self.obj._constructor(values, columns=[self._selection])
- self._insert_inaxis_grouper_inplace(result)
+ result = self._insert_inaxis_grouper(result)
return result
else:
# values are Series
@@ -1443,7 +1468,7 @@ def _wrap_applied_output_series(
result = self.obj._constructor(stacked_values, index=index, columns=columns)
if not self.as_index:
- self._insert_inaxis_grouper_inplace(result)
+ result = self._insert_inaxis_grouper(result)
return self._reindex_output(result)
@@ -1774,7 +1799,9 @@ def _gotitem(self, key, ndim: int, subset=None):
subset,
level=self.level,
grouper=self.grouper,
+ exclusions=self.exclusions,
selection=key,
+ as_index=self.as_index,
sort=self.sort,
group_keys=self.group_keys,
observed=self.observed,
@@ -1790,19 +1817,6 @@ def _get_data_to_aggregate(self) -> Manager2D:
else:
return obj._mgr
- def _insert_inaxis_grouper_inplace(self, result: DataFrame) -> None:
- # zip in reverse so we can always insert at loc 0
- columns = result.columns
- for name, lev, in_axis in zip(
- reversed(self.grouper.names),
- reversed(self.grouper.get_group_levels()),
- reversed([grp.in_axis for grp in self.grouper.groupings]),
- ):
- # GH #28549
- # When using .apply(-), name will be in columns already
- if in_axis and name not in columns:
- result.insert(0, name, lev)
-
def _indexed_output_to_ndframe(
self, output: Mapping[base.OutputKey, ArrayLike]
) -> DataFrame:
@@ -1825,7 +1839,7 @@ def _wrap_agged_manager(self, mgr: Manager2D) -> DataFrame:
mgr.set_axis(1, index)
result = self.obj._constructor(mgr)
- self._insert_inaxis_grouper_inplace(result)
+ result = self._insert_inaxis_grouper(result)
result = result._consolidate()
else:
index = self.grouper.result_index
@@ -1918,7 +1932,7 @@ def nunique(self, dropna: bool = True) -> DataFrame:
if not self.as_index:
results.index = default_index(len(results))
- self._insert_inaxis_grouper_inplace(results)
+ results = self._insert_inaxis_grouper(results)
return results
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 431b23023b094..a7e3b4215625b 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -123,6 +123,7 @@ class providing the base-class of operations.
Index,
MultiIndex,
RangeIndex,
+ default_index,
)
from pandas.core.internals.blocks import ensure_block_shape
from pandas.core.series import Series
@@ -910,8 +911,6 @@ def __init__(
self.level = level
if not as_index:
- if not isinstance(obj, DataFrame):
- raise TypeError("as_index=False only valid with DataFrame")
if axis != 0:
raise ValueError("as_index=False only valid for axis=0")
@@ -1157,6 +1156,24 @@ def _set_result_index_ordered(
return result
+ def _insert_inaxis_grouper(self, result: Series | DataFrame) -> DataFrame:
+ if isinstance(result, Series):
+ result = result.to_frame()
+
+ # zip in reverse so we can always insert at loc 0
+ columns = result.columns
+ for name, lev, in_axis in zip(
+ reversed(self.grouper.names),
+ reversed(self.grouper.get_group_levels()),
+ reversed([grp.in_axis for grp in self.grouper.groupings]),
+ ):
+ # GH #28549
+ # When using .apply(-), name will be in columns already
+ if in_axis and name not in columns:
+ result.insert(0, name, lev)
+
+ return result
+
def _indexed_output_to_ndframe(
self, result: Mapping[base.OutputKey, ArrayLike]
) -> Series | DataFrame:
@@ -1193,7 +1210,7 @@ def _wrap_aggregated_output(
if not self.as_index:
# `not self.as_index` is only relevant for DataFrameGroupBy,
# enforced in __init__
- self._insert_inaxis_grouper_inplace(result)
+ result = self._insert_inaxis_grouper(result)
result = result._consolidate()
index = Index(range(self.grouper.ngroups))
@@ -1613,7 +1630,10 @@ def array_func(values: ArrayLike) -> ArrayLike:
res = self._wrap_agged_manager(new_mgr)
if is_ser:
- res.index = self.grouper.result_index
+ if self.as_index:
+ res.index = self.grouper.result_index
+ else:
+ res = self._insert_inaxis_grouper(res)
return self._reindex_output(res)
else:
return res
@@ -1887,7 +1907,10 @@ def hfunc(bvalues: ArrayLike) -> ArrayLike:
result = self._wrap_agged_manager(new_mgr)
if result.ndim == 1:
- result.index = self.grouper.result_index
+ if self.as_index:
+ result.index = self.grouper.result_index
+ else:
+ result = self._insert_inaxis_grouper(result)
return self._reindex_output(result, fill_value=0)
@@ -2622,31 +2645,33 @@ def describe(
exclude=None,
) -> NDFrameT:
with self._group_selection_context():
- if len(self._selected_obj) == 0:
- described = self._selected_obj.describe(
+ selected_obj = self._selected_obj
+ if len(selected_obj) == 0:
+ described = selected_obj.describe(
percentiles=percentiles, include=include, exclude=exclude
)
- if self._selected_obj.ndim == 1:
+ if selected_obj.ndim == 1:
result = described
else:
result = described.unstack()
return result.to_frame().T.iloc[:0]
- result = self._python_apply_general(
- lambda x: x.describe(
- percentiles=percentiles, include=include, exclude=exclude
- ),
- self._selected_obj,
- not_indexed_same=True,
- )
+ with com.temp_setattr(self, "as_index", True):
+ result = self._python_apply_general(
+ lambda x: x.describe(
+ percentiles=percentiles, include=include, exclude=exclude
+ ),
+ selected_obj,
+ not_indexed_same=True,
+ )
if self.axis == 1:
return result.T
# GH#49256 - properly handle the grouping column(s)
- if self._selected_obj.ndim != 1 or self.as_index:
- result = result.unstack()
- if not self.as_index:
- self._insert_inaxis_grouper_inplace(result)
+ result = result.unstack()
+ if not self.as_index:
+ result = self._insert_inaxis_grouper(result)
+ result.index = default_index(len(result))
return result
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index ea902800cf7e0..f88236b2464c1 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -946,7 +946,7 @@ def result_index(self) -> Index:
@final
def get_group_levels(self) -> list[ArrayLike]:
- # Note: only called from _insert_inaxis_grouper_inplace, which
+ # Note: only called from _insert_inaxis_grouper, which
# is only called for BaseGrouper, never for BinGrouper
if len(self.groupings) == 1:
return [self.groupings[0].group_arraylike]
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 992b86a532433..642fd30bb631e 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1992,6 +1992,8 @@ def groupby(
if level is None and by is None:
raise TypeError("You have to supply one of 'by' and 'level'")
+ if not as_index:
+ raise TypeError("as_index=False only valid with DataFrame")
axis = self._get_axis_number(axis)
return SeriesGroupBy(
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 5384b228850f4..f6382bb8800a9 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -655,6 +655,8 @@ def test_groupby_as_index_select_column_sum_empty_df():
left = df.groupby(by="A", as_index=False)["B"].sum(numeric_only=False)
expected = DataFrame(columns=df.columns[:2], index=range(0))
+ # GH#50744 - Columns after selection shouldn't retain names
+ expected.columns.names = [None]
tm.assert_frame_equal(left, expected)
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Currently `.groupby(..., as_index=False)['column']` gives back a DataFrameGroupBy This is because `SeriesGroupBy` doesn't implement `as_index=False`. This gives rise to having a `DataFrameGroupBy` object with `self.obj` being a Series. It also might be a bit surprising to users that this gives them back a DataFrameGroupBy (though this is probably rarely noticed).
Eliminating this case simplifies the states groupby code must consider. It also is a step toward #46944.
There should be no changes in behavior from a user perspective except getting back a SeriesGroupBy and the one noted in the comments below.
cc @jbrockmendel | https://api.github.com/repos/pandas-dev/pandas/pulls/50744 | 2023-01-14T15:42:01Z | 2023-01-18T19:48:31Z | 2023-01-18T19:48:31Z | 2023-01-23T21:50:22Z |
TST: Test dtype sparseDtype with specificd fill value | diff --git a/pandas/tests/arrays/sparse/test_astype.py b/pandas/tests/arrays/sparse/test_astype.py
index d729a31668ade..86d69610059b3 100644
--- a/pandas/tests/arrays/sparse/test_astype.py
+++ b/pandas/tests/arrays/sparse/test_astype.py
@@ -3,7 +3,11 @@
from pandas._libs.sparse import IntIndex
-from pandas import Timestamp
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core.arrays.sparse import (
SparseArray,
@@ -131,3 +135,13 @@ def test_astype_dt64_to_int64(self):
arr3 = SparseArray(values, dtype=dtype)
result3 = arr3.astype("int64")
tm.assert_numpy_array_equal(result3, expected)
+
+
+def test_dtype_sparse_with_fill_value_not_present_in_data():
+ # GH 49987
+ df = DataFrame([["a", 0], ["b", 1], ["b", 2]], columns=["A", "B"])
+ result = df["A"].astype(SparseDtype("category", fill_value="c"))
+ expected = Series(
+ ["a", "b", "b"], name="A", dtype=SparseDtype("object", fill_value="c")
+ )
+ tm.assert_series_equal(result, expected)
| - [x] closes #49987 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50743 | 2023-01-14T14:17:47Z | 2023-01-16T00:09:49Z | 2023-01-16T00:09:49Z | 2023-01-16T03:06:57Z |
DOC: Add datetime.tzinfo to paramater tz in tz_localize and tz_convert | diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index f1da99825d5fd..2c1ef7f05fa03 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -803,7 +803,7 @@ def tz_convert(self, tz) -> DatetimeArray:
Parameters
----------
- tz : str, pytz.timezone, dateutil.tz.tzfile or None
+ tz : str, pytz.timezone, dateutil.tz.tzfile, datetime.tzinfo or None
Time zone for time. Corresponding timestamps would be converted
to this time zone of the Datetime Array/Index. A `tz` of None will
convert to UTC and remove the timezone information.
@@ -892,7 +892,7 @@ def tz_localize(
Parameters
----------
- tz : str, pytz.timezone, dateutil.tz.tzfile or None
+ tz : str, pytz.timezone, dateutil.tz.tzfile, datetime.tzinfo or None
Time zone to convert timestamps to. Passing ``None`` will
remove the time zone information preserving local time.
ambiguous : 'infer', 'NaT', bool array, default 'raise'
| - [x] closes #50655 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50742 | 2023-01-14T07:34:46Z | 2023-01-16T19:18:14Z | 2023-01-16T19:18:14Z | 2023-01-17T07:28:56Z |
TST: Fix undefined variables in tests | diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 2dce3e72b1e3f..523463b9593a2 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -528,6 +528,7 @@ def test_groupby_extension_transform(self, data_for_grouping, request):
def test_groupby_extension_apply(
self, data_for_grouping, groupby_apply_op, request
):
+ pa_dtype = data_for_grouping.dtype.pyarrow_dtype
with tm.maybe_produces_warning(
PerformanceWarning,
pa_version_under7p0 and not pa.types.is_duration(pa_dtype),
@@ -770,6 +771,7 @@ def test_value_counts(self, all_data, dropna, request):
super().test_value_counts(all_data, dropna)
def test_value_counts_with_normalize(self, data, request):
+ pa_dtype = data.dtype.pyarrow_dtype
with tm.maybe_produces_warning(
PerformanceWarning,
pa_version_under7p0 and not pa.types.is_duration(pa_dtype),
@@ -869,6 +871,7 @@ def test_sort_values_missing(
@pytest.mark.parametrize("ascending", [True, False])
def test_sort_values_frame(self, data_for_sorting, ascending, request):
+ pa_dtype = data_for_sorting.dtype.pyarrow_dtype
with tm.maybe_produces_warning(
PerformanceWarning,
pa_version_under7p0 and not pa.types.is_duration(pa_dtype),
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
I think I got all of them from #50669. Feel free to push if I missed one. | https://api.github.com/repos/pandas-dev/pandas/pulls/50741 | 2023-01-14T05:20:10Z | 2023-01-14T15:52:46Z | 2023-01-14T15:52:46Z | 2023-01-14T15:52:47Z |
TST: Sync pyproject.toml Pytest version with min deps | diff --git a/pyproject.toml b/pyproject.toml
index 0308f86beb0d4..dc237d32c022c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -356,7 +356,7 @@ disable = [
[tool.pytest.ini_options]
# sync minversion with pyproject.toml & install.rst
-minversion = "6.0"
+minversion = "7.0"
addopts = "--strict-data-files --strict-markers --strict-config --capture=no --durations=30 --junitxml=test-data.xml"
empty_parameter_set_mark = "fail_at_collect"
xfail_strict = true
| Bumped in https://github.com/pandas-dev/pandas/pull/50481 | https://api.github.com/repos/pandas-dev/pandas/pulls/50740 | 2023-01-14T00:14:34Z | 2023-01-14T19:11:20Z | 2023-01-14T19:11:20Z | 2023-01-14T19:11:23Z |
Backport PR #50396 on branch 1.5.x (BUG/COMPAT: fix assert_* functions for nested arrays with latest numpy) | diff --git a/doc/source/whatsnew/v1.5.3.rst b/doc/source/whatsnew/v1.5.3.rst
index 51e36359946e7..9d17d3cf7bea9 100644
--- a/doc/source/whatsnew/v1.5.3.rst
+++ b/doc/source/whatsnew/v1.5.3.rst
@@ -31,6 +31,7 @@ Bug fixes
- Bug in :meth:`Series.quantile` emitting warning from NumPy when :class:`Series` has only ``NA`` values (:issue:`50681`)
- Bug when chaining several :meth:`.Styler.concat` calls, only the last styler was concatenated (:issue:`49207`)
- Fixed bug when instantiating a :class:`DataFrame` subclass inheriting from ``typing.Generic`` that triggered a ``UserWarning`` on python 3.11 (:issue:`49649`)
+- Bug in :func:`pandas.testing.assert_series_equal` (and equivalent ``assert_`` functions) when having nested data and using numpy >= 1.25 (:issue:`50360`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index 189ffc3d485bf..e7f57ae0e6658 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -594,6 +594,10 @@ def _array_equivalent_object(left: np.ndarray, right: np.ndarray, strict_nan: bo
if "boolean value of NA is ambiguous" in str(err):
return False
raise
+ except ValueError:
+ # numpy can raise a ValueError if left and right cannot be
+ # compared (e.g. nested arrays)
+ return False
return True
diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py
index 9f761c505075b..9a242e9491537 100644
--- a/pandas/tests/dtypes/test_missing.py
+++ b/pandas/tests/dtypes/test_missing.py
@@ -525,18 +525,120 @@ def test_array_equivalent_str(dtype):
)
-def test_array_equivalent_nested():
+@pytest.mark.parametrize(
+ "strict_nan", [pytest.param(True, marks=pytest.mark.xfail), False]
+)
+def test_array_equivalent_nested(strict_nan):
# reached in groupby aggregations, make sure we use np.any when checking
# if the comparison is truthy
- left = np.array([np.array([50, 70, 90]), np.array([20, 30, 40])], dtype=object)
- right = np.array([np.array([50, 70, 90]), np.array([20, 30, 40])], dtype=object)
+ left = np.array([np.array([50, 70, 90]), np.array([20, 30])], dtype=object)
+ right = np.array([np.array([50, 70, 90]), np.array([20, 30])], dtype=object)
- assert array_equivalent(left, right, strict_nan=True)
- assert not array_equivalent(left, right[::-1], strict_nan=True)
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
- left = np.array([np.array([50, 50, 50]), np.array([40, 40, 40])], dtype=object)
+ left = np.empty(2, dtype=object)
+ left[:] = [np.array([50, 70, 90]), np.array([20, 30, 40])]
+ right = np.empty(2, dtype=object)
+ right[:] = [np.array([50, 70, 90]), np.array([20, 30, 40])]
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ left = np.array([np.array([50, 50, 50]), np.array([40, 40])], dtype=object)
right = np.array([50, 40])
- assert not array_equivalent(left, right, strict_nan=True)
+ assert not array_equivalent(left, right, strict_nan=strict_nan)
+
+
+@pytest.mark.parametrize(
+ "strict_nan", [pytest.param(True, marks=pytest.mark.xfail), False]
+)
+def test_array_equivalent_nested2(strict_nan):
+ # more than one level of nesting
+ left = np.array(
+ [
+ np.array([np.array([50, 70]), np.array([90])], dtype=object),
+ np.array([np.array([20, 30])], dtype=object),
+ ],
+ dtype=object,
+ )
+ right = np.array(
+ [
+ np.array([np.array([50, 70]), np.array([90])], dtype=object),
+ np.array([np.array([20, 30])], dtype=object),
+ ],
+ dtype=object,
+ )
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ left = np.array([np.array([np.array([50, 50, 50])], dtype=object)], dtype=object)
+ right = np.array([50])
+ assert not array_equivalent(left, right, strict_nan=strict_nan)
+
+
+@pytest.mark.parametrize(
+ "strict_nan", [pytest.param(True, marks=pytest.mark.xfail), False]
+)
+def test_array_equivalent_nested_list(strict_nan):
+ left = np.array([[50, 70, 90], [20, 30]], dtype=object)
+ right = np.array([[50, 70, 90], [20, 30]], dtype=object)
+
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ left = np.array([[50, 50, 50], [40, 40]], dtype=object)
+ right = np.array([50, 40])
+ assert not array_equivalent(left, right, strict_nan=strict_nan)
+
+
+@pytest.mark.xfail(reason="failing")
+@pytest.mark.parametrize("strict_nan", [True, False])
+def test_array_equivalent_nested_mixed_list(strict_nan):
+ # mixed arrays / lists in left and right
+ # https://github.com/pandas-dev/pandas/issues/50360
+ left = np.array([np.array([1, 2, 3]), np.array([4, 5])], dtype=object)
+ right = np.array([[1, 2, 3], [4, 5]], dtype=object)
+
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ # multiple levels of nesting
+ left = np.array(
+ [
+ np.array([np.array([1, 2, 3]), np.array([4, 5])], dtype=object),
+ np.array([np.array([6]), np.array([7, 8]), np.array([9])], dtype=object),
+ ],
+ dtype=object,
+ )
+ right = np.array([[[1, 2, 3], [4, 5]], [[6], [7, 8], [9]]], dtype=object)
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ # same-length lists
+ subarr = np.empty(2, dtype=object)
+ subarr[:] = [
+ np.array([None, "b"], dtype=object),
+ np.array(["c", "d"], dtype=object),
+ ]
+ left = np.array([subarr, None], dtype=object)
+ right = np.array([list([[None, "b"], ["c", "d"]]), None], dtype=object)
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+
+@pytest.mark.xfail(reason="failing")
+@pytest.mark.parametrize("strict_nan", [True, False])
+def test_array_equivalent_nested_dicts(strict_nan):
+ left = np.array([{"f1": 1, "f2": np.array(["a", "b"], dtype=object)}], dtype=object)
+ right = np.array(
+ [{"f1": 1, "f2": np.array(["a", "b"], dtype=object)}], dtype=object
+ )
+ assert array_equivalent(left, right, strict_nan=strict_nan)
+ assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
+
+ right2 = np.array([{"f1": 1, "f2": ["a", "b"]}], dtype=object)
+ assert array_equivalent(left, right2, strict_nan=strict_nan)
+ assert not array_equivalent(left, right2[::-1], strict_nan=strict_nan)
@pytest.mark.parametrize(
diff --git a/pandas/tests/util/test_assert_almost_equal.py b/pandas/tests/util/test_assert_almost_equal.py
index ab53707771be6..4e6c420341bc2 100644
--- a/pandas/tests/util/test_assert_almost_equal.py
+++ b/pandas/tests/util/test_assert_almost_equal.py
@@ -458,3 +458,87 @@ def test_assert_almost_equal_iterable_values_mismatch():
with pytest.raises(AssertionError, match=msg):
tm.assert_almost_equal([1, 2], [1, 3])
+
+
+subarr = np.empty(2, dtype=object)
+subarr[:] = [np.array([None, "b"], dtype=object), np.array(["c", "d"], dtype=object)]
+
+NESTED_CASES = [
+ # nested array
+ (
+ np.array([np.array([50, 70, 90]), np.array([20, 30])], dtype=object),
+ np.array([np.array([50, 70, 90]), np.array([20, 30])], dtype=object),
+ ),
+ # >1 level of nesting
+ (
+ np.array(
+ [
+ np.array([np.array([50, 70]), np.array([90])], dtype=object),
+ np.array([np.array([20, 30])], dtype=object),
+ ],
+ dtype=object,
+ ),
+ np.array(
+ [
+ np.array([np.array([50, 70]), np.array([90])], dtype=object),
+ np.array([np.array([20, 30])], dtype=object),
+ ],
+ dtype=object,
+ ),
+ ),
+ # lists
+ (
+ np.array([[50, 70, 90], [20, 30]], dtype=object),
+ np.array([[50, 70, 90], [20, 30]], dtype=object),
+ ),
+ # mixed array/list
+ (
+ np.array([np.array([1, 2, 3]), np.array([4, 5])], dtype=object),
+ np.array([[1, 2, 3], [4, 5]], dtype=object),
+ ),
+ (
+ np.array(
+ [
+ np.array([np.array([1, 2, 3]), np.array([4, 5])], dtype=object),
+ np.array(
+ [np.array([6]), np.array([7, 8]), np.array([9])], dtype=object
+ ),
+ ],
+ dtype=object,
+ ),
+ np.array([[[1, 2, 3], [4, 5]], [[6], [7, 8], [9]]], dtype=object),
+ ),
+ # same-length lists
+ (
+ np.array([subarr, None], dtype=object),
+ np.array([list([[None, "b"], ["c", "d"]]), None], dtype=object),
+ ),
+ # dicts
+ (
+ np.array([{"f1": 1, "f2": np.array(["a", "b"], dtype=object)}], dtype=object),
+ np.array([{"f1": 1, "f2": np.array(["a", "b"], dtype=object)}], dtype=object),
+ ),
+ (
+ np.array([{"f1": 1, "f2": np.array(["a", "b"], dtype=object)}], dtype=object),
+ np.array([{"f1": 1, "f2": ["a", "b"]}], dtype=object),
+ ),
+ # array/list of dicts
+ (
+ np.array(
+ [
+ np.array(
+ [{"f1": 1, "f2": np.array(["a", "b"], dtype=object)}], dtype=object
+ ),
+ np.array([], dtype=object),
+ ],
+ dtype=object,
+ ),
+ np.array([[{"f1": 1, "f2": ["a", "b"]}], []], dtype=object),
+ ),
+]
+
+
+@pytest.mark.filterwarnings("ignore:elementwise comparison failed:DeprecationWarning")
+@pytest.mark.parametrize("a,b", NESTED_CASES)
+def test_assert_almost_equal_array_nested(a, b):
+ _assert_almost_equal_both(a, b)
| Backport PR #50396: BUG/COMPAT: fix assert_* functions for nested arrays with latest numpy | https://api.github.com/repos/pandas-dev/pandas/pulls/50739 | 2023-01-13T23:14:08Z | 2023-01-14T05:21:24Z | 2023-01-14T05:21:24Z | 2023-01-14T05:21:24Z |
DOC: list supported float dtypes I | diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst
index f30c66d75b525..8ca81acd6a704 100644
--- a/doc/source/user_guide/basics.rst
+++ b/doc/source/user_guide/basics.rst
@@ -2073,6 +2073,8 @@ documentation sections for more on each type.
| | | | | ``'Int64'``, ``'UInt8'``, ``'UInt16'``,|
| | | | | ``'UInt32'``, ``'UInt64'`` |
+-------------------------------------------------+---------------------------+--------------------+-------------------------------+----------------------------------------+
+| ``nullable float`` | :class:`Float64Dtype`, ...| (none) | :class:`arrays.FloatingArray` | ``'Float32'``, ``'Float64'`` |
++-------------------------------------------------+---------------------------+--------------------+-------------------------------+----------------------------------------+
| :ref:`Strings <text>` | :class:`StringDtype` | :class:`str` | :class:`arrays.StringArray` | ``'string'`` |
+-------------------------------------------------+---------------------------+--------------------+-------------------------------+----------------------------------------+
| :ref:`Boolean (with NA) <api.arrays.bool>` | :class:`BooleanDtype` | :class:`bool` | :class:`arrays.BooleanArray` | ``'boolean'`` |
| - [x] closes #50216
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
Updated documentation for `pandas.to_numeric()`, pointed out that `downcast` parameter doesn’t support `float16` dtype. Listed in the description of [dtype](https://pandas.pydata.org/docs/user_guide/basics.html#dtypes) supported floating point types and added Link to [NumPy types](https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy). | https://api.github.com/repos/pandas-dev/pandas/pulls/50738 | 2023-01-13T20:52:12Z | 2023-02-15T18:31:45Z | 2023-02-15T18:31:45Z | 2023-02-15T18:31:52Z |
REF: array_with_unit_to_datetime | diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 10bcf6c9eabbf..fc6ba89ecfa24 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -262,7 +262,6 @@ def array_with_unit_to_datetime(
bint is_coerce = errors=="coerce"
bint is_raise = errors=="raise"
ndarray[int64_t] iresult
- ndarray[object] oresult
object tz = None
bint is_ym
float fval
@@ -283,10 +282,10 @@ def array_with_unit_to_datetime(
result = np.empty(n, dtype="M8[ns]")
iresult = result.view("i8")
- try:
- for i in range(n):
- val = values[i]
+ for i in range(n):
+ val = values[i]
+ try:
if checknull_with_nat_and_na(val):
iresult[i] = NPY_NAT
@@ -297,26 +296,17 @@ def array_with_unit_to_datetime(
else:
if is_ym and is_float_object(val) and not val.is_integer():
# Analogous to GH#47266 for Timestamp
- if is_raise:
- raise ValueError(
- f"Conversion of non-round float with unit={unit} "
- "is ambiguous"
- )
- elif is_ignore:
- raise AssertionError
- iresult[i] = NPY_NAT
- continue
+ raise ValueError(
+ f"Conversion of non-round float with unit={unit} "
+ "is ambiguous"
+ )
try:
iresult[i] = cast_from_unit(val, unit)
except OverflowError:
- if is_raise:
- raise OutOfBoundsDatetime(
- f"cannot convert input {val} with the unit '{unit}'"
- )
- elif is_ignore:
- raise AssertionError
- iresult[i] = NPY_NAT
+ raise OutOfBoundsDatetime(
+ f"cannot convert input {val} with the unit '{unit}'"
+ )
elif isinstance(val, str):
if len(val) == 0 or val in nat_strings:
@@ -327,65 +317,56 @@ def array_with_unit_to_datetime(
try:
fval = float(val)
except ValueError:
- if is_raise:
- raise ValueError(
- f"non convertible value {val} with the unit '{unit}'"
- )
- elif is_ignore:
- raise AssertionError
- iresult[i] = NPY_NAT
- continue
+ raise ValueError(
+ f"non convertible value {val} with the unit '{unit}'"
+ )
if is_ym and not fval.is_integer():
# Analogous to GH#47266 for Timestamp
- if is_raise:
- raise ValueError(
- f"Conversion of non-round float with unit={unit} "
- "is ambiguous"
- )
- elif is_ignore:
- raise AssertionError
- iresult[i] = NPY_NAT
- continue
+ raise ValueError(
+ f"Conversion of non-round float with unit={unit} "
+ "is ambiguous"
+ )
try:
iresult[i] = cast_from_unit(fval, unit)
except ValueError:
- if is_raise:
- raise ValueError(
- f"non convertible value {val} with the unit '{unit}'"
- )
- elif is_ignore:
- raise AssertionError
- iresult[i] = NPY_NAT
+ raise ValueError(
+ f"non convertible value {val} with the unit '{unit}'"
+ )
except OverflowError:
- if is_raise:
- raise OutOfBoundsDatetime(
- f"cannot convert input {val} with the unit '{unit}'"
- )
- elif is_ignore:
- raise AssertionError
- iresult[i] = NPY_NAT
+ raise OutOfBoundsDatetime(
+ f"cannot convert input {val} with the unit '{unit}'"
+ )
else:
+ # TODO: makes more sense as TypeError, but that would be an
+ # API change.
+ raise ValueError(
+ f"unit='{unit}' not valid with non-numerical val='{val}'"
+ )
- if is_raise:
- raise ValueError(
- f"unit='{unit}' not valid with non-numerical val='{val}'"
- )
- if is_ignore:
- raise AssertionError
-
+ except (ValueError, OutOfBoundsDatetime, TypeError) as err:
+ if is_raise:
+ err.args = (f"{err}, at position {i}",)
+ raise
+ elif is_ignore:
+ # we have hit an exception
+ # and are in ignore mode
+ # redo as object
+ return _array_with_unit_to_datetime_object_fallback(values, unit)
+ else:
+ # is_coerce
iresult[i] = NPY_NAT
- return result, tz
+ return result, tz
- except AssertionError:
- pass
- # we have hit an exception
- # and are in ignore mode
- # redo as object
+cdef _array_with_unit_to_datetime_object_fallback(ndarray[object] values, str unit):
+ cdef:
+ Py_ssize_t i, n = len(values)
+ ndarray[object] oresult
+ object tz = None
# TODO: fix subtle differences between this and no-unit code
oresult = cnp.PyArray_EMPTY(values.ndim, values.shape, cnp.NPY_OBJECT, 0)
| use the same pattern @MarcoGorelli recently implemented in array_to_datetime | https://api.github.com/repos/pandas-dev/pandas/pulls/50737 | 2023-01-13T19:55:44Z | 2023-01-17T11:57:13Z | 2023-01-17T11:57:13Z | 2023-01-17T16:20:27Z |
REF: share string parsing code | diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 10bcf6c9eabbf..36001248d664b 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -51,7 +51,7 @@ from pandas._libs.tslibs.parsing import parse_datetime_string
from pandas._libs.tslibs.conversion cimport (
_TSObject,
cast_from_unit,
- convert_datetime_to_tsobject,
+ convert_str_to_tsobject,
convert_timezone,
get_datetime64_nanos,
parse_pydatetime,
@@ -482,7 +482,6 @@ cpdef array_to_datetime(
object val, tz
ndarray[int64_t] iresult
npy_datetimestruct dts
- NPY_DATETIMEUNIT out_bestunit
bint utc_convert = bool(utc)
bint seen_datetime_offset = False
bint is_raise = errors=="raise"
@@ -490,12 +489,8 @@ cpdef array_to_datetime(
bint is_coerce = errors=="coerce"
bint is_same_offsets
_TSObject _ts
- int64_t value
- int out_local = 0, out_tzoffset = 0
float tz_offset
set out_tzoffset_vals = set()
- bint string_to_dts_failed
- datetime py_dt
tzinfo tz_out = None
bint found_tz = False, found_naive = False
cnp.broadcast mi
@@ -557,61 +552,40 @@ cpdef array_to_datetime(
# GH#32264 np.str_ object
val = str(val)
- if len(val) == 0 or val in nat_strings:
- iresult[i] = NPY_NAT
+ if parse_today_now(val, &iresult[i], utc):
+ # We can't _quite_ dispatch this to convert_str_to_tsobject
+ # bc there isn't a nice way to pass "utc"
cnp.PyArray_MultiIter_NEXT(mi)
continue
- string_to_dts_failed = string_to_dts(
- val, &dts, &out_bestunit, &out_local,
- &out_tzoffset, False, None, False
+ _ts = convert_str_to_tsobject(
+ val, None, unit="ns", dayfirst=dayfirst, yearfirst=yearfirst
)
- if string_to_dts_failed:
- # An error at this point is a _parsing_ error
- # specifically _not_ OutOfBoundsDatetime
- if parse_today_now(val, &iresult[i], utc):
- cnp.PyArray_MultiIter_NEXT(mi)
- continue
-
- py_dt = parse_datetime_string(val,
- dayfirst=dayfirst,
- yearfirst=yearfirst)
- # If the dateutil parser returned tzinfo, capture it
- # to check if all arguments have the same tzinfo
- tz = py_dt.utcoffset()
-
- if tz is not None:
- seen_datetime_offset = True
- # dateutil timezone objects cannot be hashed, so
- # store the UTC offsets in seconds instead
- out_tzoffset_vals.add(tz.total_seconds())
- else:
- # Add a marker for naive string, to track if we are
- # parsing mixed naive and aware strings
- out_tzoffset_vals.add("naive")
-
- _ts = convert_datetime_to_tsobject(py_dt, None)
- iresult[i] = _ts.value
+ try:
+ _ts.ensure_reso(NPY_FR_ns)
+ except OutOfBoundsDatetime as err:
+ # re-raise with better exception message
+ raise OutOfBoundsDatetime(
+ f"Out of bounds nanosecond timestamp: {val}"
+ ) from err
+
+ iresult[i] = _ts.value
+
+ tz = _ts.tzinfo
+ if tz is not None:
+ # dateutil timezone objects cannot be hashed, so
+ # store the UTC offsets in seconds instead
+ nsecs = tz.utcoffset(None).total_seconds()
+ out_tzoffset_vals.add(nsecs)
+ # need to set seen_datetime_offset *after* the
+ # potentially-raising timezone(timedelta(...)) call,
+ # otherwise we can go down the is_same_offsets path
+ # bc len(out_tzoffset_vals) == 0
+ seen_datetime_offset = True
else:
- # No error reported by string_to_dts, pick back up
- # where we left off
- value = npy_datetimestruct_to_datetime(NPY_FR_ns, &dts)
- if out_local == 1:
- seen_datetime_offset = True
- # Store the out_tzoffset in seconds
- # since we store the total_seconds of
- # dateutil.tz.tzoffset objects
- out_tzoffset_vals.add(out_tzoffset * 60.)
- tz = timezone(timedelta(minutes=out_tzoffset))
- value = tz_localize_to_utc_single(value, tz)
- out_local = 0
- out_tzoffset = 0
- else:
- # Add a marker for naive string, to track if we are
- # parsing mixed naive and aware strings
- out_tzoffset_vals.add("naive")
- iresult[i] = value
- check_dts_bounds(&dts)
+ # Add a marker for naive string, to track if we are
+ # parsing mixed naive and aware strings
+ out_tzoffset_vals.add("naive")
else:
raise TypeError(f"{type(val)} is not convertible to datetime")
diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd
index 332ff1522ccf5..756ab67aa7084 100644
--- a/pandas/_libs/tslibs/conversion.pxd
+++ b/pandas/_libs/tslibs/conversion.pxd
@@ -35,6 +35,10 @@ cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz,
int32_t nanos=*,
NPY_DATETIMEUNIT reso=*)
+cdef _TSObject convert_str_to_tsobject(str ts, tzinfo tz, str unit,
+ bint dayfirst=*,
+ bint yearfirst=*)
+
cdef int64_t get_datetime64_nanos(object val, NPY_DATETIMEUNIT reso) except? -1
cpdef datetime localize_pydatetime(datetime dt, tzinfo tz)
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index 7cff269d2191e..aacb06fe36037 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -246,7 +246,7 @@ cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit,
obj = _TSObject()
if isinstance(ts, str):
- return _convert_str_to_tsobject(ts, tz, unit, dayfirst, yearfirst)
+ return convert_str_to_tsobject(ts, tz, unit, dayfirst, yearfirst)
if ts is None or ts is NaT:
obj.value = NPY_NAT
@@ -463,9 +463,9 @@ cdef _TSObject _create_tsobject_tz_using_offset(npy_datetimestruct dts,
return obj
-cdef _TSObject _convert_str_to_tsobject(str ts, tzinfo tz, str unit,
- bint dayfirst=False,
- bint yearfirst=False):
+cdef _TSObject convert_str_to_tsobject(str ts, tzinfo tz, str unit,
+ bint dayfirst=False,
+ bint yearfirst=False):
"""
Convert a string input `ts`, along with optional timezone object`tz`
to a _TSObject.
diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py
index be05a649ec0b6..622f41236edb9 100644
--- a/pandas/tests/indexes/datetimes/test_scalar_compat.py
+++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py
@@ -38,7 +38,10 @@ def test_dti_date(self):
@pytest.mark.parametrize("data", [["1400-01-01"], [datetime(1400, 1, 1)]])
def test_dti_date_out_of_range(self, data):
# GH#1475
- msg = "^Out of bounds nanosecond timestamp: 1400-01-01 00:00:00, at position 0$"
+ msg = (
+ "^Out of bounds nanosecond timestamp: "
+ "1400-01-01( 00:00:00)?, at position 0$"
+ )
with pytest.raises(OutOfBoundsDatetime, match=msg):
DatetimeIndex(data)
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index a6e40c30d5b82..bf0db0da1c3e3 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -2783,7 +2783,7 @@ def test_day_not_in_month_coerce(self, cache, arg, format, warning):
assert isna(to_datetime(arg, errors="coerce", format=format, cache=cache))
def test_day_not_in_month_raise(self, cache):
- msg = "day is out of range for month"
+ msg = "could not convert string to Timestamp"
with pytest.raises(ValueError, match=msg):
with tm.assert_produces_warning(
UserWarning, match="Could not infer format"
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50736 | 2023-01-13T18:44:16Z | 2023-01-16T18:17:14Z | 2023-01-16T18:17:14Z | 2023-01-16T18:19:27Z |
BUG: stringdtype.astype(dt64_or_td64) | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index b53595621af11..554c972b56b34 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -946,6 +946,7 @@ Conversion
Strings
^^^^^^^
- Bug in :func:`pandas.api.dtypes.is_string_dtype` that would not return ``True`` for :class:`StringDtype` (:issue:`15585`)
+- Bug in converting string dtypes to "datetime64[ns]" or "timedelta64[ns]" incorrectly raising ``TypeError`` (:issue:`36153`)
-
Interval
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 422b9effeface..4497583f60d71 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -55,9 +55,11 @@
from pandas.core.dtypes.cast import maybe_cast_to_extension_array
from pandas.core.dtypes.common import (
+ is_datetime64_dtype,
is_dtype_equal,
is_list_like,
is_scalar,
+ is_timedelta64_dtype,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import ExtensionDtype
@@ -580,6 +582,16 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
cls = dtype.construct_array_type()
return cls._from_sequence(self, dtype=dtype, copy=copy)
+ elif is_datetime64_dtype(dtype):
+ from pandas.core.arrays import DatetimeArray
+
+ return DatetimeArray._from_sequence(self, dtype=dtype, copy=copy)
+
+ elif is_timedelta64_dtype(dtype):
+ from pandas.core.arrays import TimedeltaArray
+
+ return TimedeltaArray._from_sequence(self, dtype=dtype, copy=copy)
+
return np.array(self, dtype=dtype, copy=copy)
def isna(self) -> np.ndarray | ExtensionArraySupportsAnyAll:
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index 8d8d9ce20cefd..e1ea001819b1c 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -73,17 +73,7 @@ def test_setitem_with_scalar_string(dtype):
tm.assert_extension_array_equal(arr, expected)
-def test_astype_roundtrip(dtype, request):
- if dtype.storage == "pyarrow":
- reason = "ValueError: Could not convert object to NumPy datetime"
- mark = pytest.mark.xfail(reason=reason, raises=ValueError)
- request.node.add_marker(mark)
- else:
- mark = pytest.mark.xfail(
- reason="GH#36153 casting from StringArray to dt64 fails", raises=ValueError
- )
- request.node.add_marker(mark)
-
+def test_astype_roundtrip(dtype):
ser = pd.Series(pd.date_range("2000", periods=12))
ser[0] = None
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
index 9cc49199166b8..024cdf9300157 100644
--- a/pandas/tests/series/methods/test_astype.py
+++ b/pandas/tests/series/methods/test_astype.py
@@ -454,9 +454,7 @@ class TestAstypeString:
def test_astype_string_to_extension_dtype_roundtrip(
self, data, dtype, request, nullable_string_dtype
):
- if dtype == "boolean" or (
- dtype in ("datetime64[ns]", "timedelta64[ns]") and NaT in data
- ):
+ if dtype == "boolean" or (dtype == "timedelta64[ns]" and NaT in data):
mark = pytest.mark.xfail(
reason="TODO StringArray.astype() with missing values #GH40566"
)
| - [x] closes #36153 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50734 | 2023-01-13T16:17:30Z | 2023-01-17T19:11:25Z | 2023-01-17T19:11:25Z | 2023-01-17T19:27:47Z |
CLN explicit float casts in tests | diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py
index e7c5142bc05ca..ab3494f0823ad 100644
--- a/pandas/tests/frame/test_arithmetic.py
+++ b/pandas/tests/frame/test_arithmetic.py
@@ -1936,15 +1936,19 @@ def test_dataframe_blockwise_slicelike():
# GH#34367
arr = np.random.randint(0, 1000, (100, 10))
df1 = DataFrame(arr)
- df2 = df1.copy()
+ # Explicit cast to float to avoid implicit cast when setting nan
+ df2 = df1.copy().astype({1: "float", 3: "float", 7: "float"})
df2.iloc[0, [1, 3, 7]] = np.nan
- df3 = df1.copy()
+ # Explicit cast to float to avoid implicit cast when setting nan
+ df3 = df1.copy().astype({5: "float"})
df3.iloc[0, [5]] = np.nan
- df4 = df1.copy()
+ # Explicit cast to float to avoid implicit cast when setting nan
+ df4 = df1.copy().astype({2: "float", 3: "float", 4: "float"})
df4.iloc[0, np.arange(2, 5)] = np.nan
- df5 = df1.copy()
+ # Explicit cast to float to avoid implicit cast when setting nan
+ df5 = df1.copy().astype({4: "float", 5: "float", 6: "float"})
df5.iloc[0, np.arange(4, 7)] = np.nan
for left, right in [(df1, df2), (df2, df3), (df4, df5)]:
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index 875037b390883..da3bc2109341b 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -826,6 +826,8 @@ def test_cummin(dtypes_for_minmax):
tm.assert_frame_equal(result, expected, check_exact=True)
# Test nan in some values
+ # Explicit cast to float to avoid implicit cast when setting nan
+ base_df = base_df.astype({"B": "float"})
base_df.loc[[0, 2, 4, 6], "B"] = np.nan
expected = DataFrame({"B": [np.nan, 4, np.nan, 2, np.nan, 3, np.nan, 1]})
result = base_df.groupby("A").cummin()
@@ -891,6 +893,8 @@ def test_cummax(dtypes_for_minmax):
tm.assert_frame_equal(result, expected)
# Test nan in some values
+ # Explicit cast to float to avoid implicit cast when setting nan
+ base_df = base_df.astype({"B": "float"})
base_df.loc[[0, 2, 4, 6], "B"] = np.nan
expected = DataFrame({"B": [np.nan, 4, np.nan, 4, np.nan, 3, np.nan, 3]})
result = base_df.groupby("A").cummax()
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index d04e5183d980f..521b9c417c312 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -193,7 +193,8 @@ def test_eng_float_formatter(self, float_frame):
)
def test_show_counts(self, row, columns, show_counts, result):
- df = DataFrame(1, columns=range(10), index=range(10))
+ # Explicit cast to float to avoid implicit cast when setting nan
+ df = DataFrame(1, columns=range(10), index=range(10)).astype({1: "float"})
df.iloc[1, 1] = np.nan
with option_context(
diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py
index 55e8c4e818ce3..19445c35f0bb6 100644
--- a/pandas/tests/resample/test_base.py
+++ b/pandas/tests/resample/test_base.py
@@ -68,7 +68,8 @@ def test_asfreq_fill_value(series, create_index):
expected = ser.reindex(new_index)
tm.assert_series_equal(result, expected)
- frame = ser.to_frame("value")
+ # Explicit cast to float to avoid implicit cast when setting None
+ frame = ser.astype("float").to_frame("value")
frame.iloc[1] = None
result = frame.resample("1H").asfreq(fill_value=4.0)
new_index = create_index(frame.index[0], frame.index[-1], freq="1H")
diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py
index 0dbe45eeb1e82..293e5ea58e3b0 100644
--- a/pandas/tests/reshape/merge/test_multi.py
+++ b/pandas/tests/reshape/merge/test_multi.py
@@ -123,7 +123,8 @@ def run_asserts(left, right, sort):
lc = list(map(chr, np.arange(ord("a"), ord("z") + 1)))
left = DataFrame(np.random.choice(lc, (5000, 2)), columns=["1st", "3rd"])
- left.insert(1, "2nd", np.random.randint(0, 1000, len(left)))
+ # Explicit cast to float to avoid implicit cast when setting nan
+ left.insert(1, "2nd", np.random.randint(0, 1000, len(left)).astype("float"))
i = np.random.permutation(len(left))
right = left.iloc[i].copy()
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index 60049d0ac633a..f6c96375407e0 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -433,6 +433,8 @@ def test_closed_uneven():
def test_closed_min_max_minp(func, closed, expected):
# see gh-21704
ser = Series(data=np.arange(10), index=date_range("2000", periods=10))
+ # Explicit cast to float to avoid implicit cast when setting nan
+ ser = ser.astype("float")
ser[ser.index[-3:]] = np.nan
result = getattr(ser.rolling("3D", min_periods=2, closed=closed), func)()
expected = Series(expected, index=ser.index)
diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py
index d04cdb3e46bc0..f33dfb2ca94ec 100644
--- a/pandas/tests/window/test_timeseries_window.py
+++ b/pandas/tests/window/test_timeseries_window.py
@@ -579,7 +579,8 @@ def test_ragged_max(self, ragged):
def test_freqs_ops(self, freq, op, result_data):
# GH 21096
index = date_range(start="2018-1-1 01:00:00", freq=f"1{freq}", periods=10)
- s = Series(data=0, index=index)
+ # Explicit cast to float to avoid implicit cast when setting nan
+ s = Series(data=0, index=index, dtype="float")
s.iloc[1] = np.nan
s.iloc[-1] = 2
result = getattr(s.rolling(window=f"10{freq}"), op)()
| Similar to https://github.com/pandas-dev/pandas/pull/50493
There are places when an implicit cast happens, but it's not the purpose of the test - the cast might as well be done explicitly then
This would help pave the way towards https://github.com/pandas-dev/pandas/pull/50424
---
I expect this to be the last precursor PR, after this one I'll raise a draft PR to try enforcing PDEP6 in some cases (note that merging would only take place _after_ 2.0 is released) | https://api.github.com/repos/pandas-dev/pandas/pulls/50733 | 2023-01-13T15:26:31Z | 2023-01-13T18:14:39Z | 2023-01-13T18:14:39Z | 2023-01-13T18:14:47Z |
Enhanced the documentation and added examples in pandas tseries offsets Week class | diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index cf02b0cb396bd..17d4e0dd3234b 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -2782,13 +2782,33 @@ cdef class Week(SingleConstructorOffset):
Parameters
----------
weekday : int or None, default None
- Always generate specific day of week. 0 for Monday.
+ Always generate specific day of week.
+ 0 for Monday and 6 for Sunday.
- Examples
+ See Also
--------
- >>> ts = pd.Timestamp(2022, 1, 1)
- >>> ts + pd.offsets.Week()
- Timestamp('2022-01-08 00:00:00')
+ pd.tseries.offsets.WeekOfMonth :
+ Describes monthly dates like, the Tuesday of the
+ 2nd week of each month.
+
+ Examples
+ ---------
+
+ >>> date_object = pd.Timestamp("2023-01-13")
+ >>> date_object
+ Timestamp('2023-01-13 00:00:00')
+
+ >>> date_plus_one_week = date_object + pd.tseries.offsets.Week(n=1)
+ >>> date_plus_one_week
+ Timestamp('2023-01-20 00:00:00')
+
+ >>> date_next_monday = date_object + pd.tseries.offsets.Week(weekday=0)
+ >>> date_next_monday
+ Timestamp('2023-01-16 00:00:00')
+
+ >>> date_next_sunday = date_object + pd.tseries.offsets.Week(weekday=6)
+ >>> date_next_sunday
+ Timestamp('2023-01-15 00:00:00')
"""
_inc = timedelta(weeks=1)
| - [ ] closes #47651 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50732 | 2023-01-13T14:57:15Z | 2023-01-17T12:43:16Z | 2023-01-17T12:43:16Z | 2023-01-17T12:43:17Z |
Backport PR #50728 on branch 1.5.x (CI fix failing python-dev job) | diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index c07a101cc433b..0d265182b3924 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -73,7 +73,7 @@ jobs:
run: |
python --version
python -m pip install --upgrade pip setuptools wheel
- python -m pip install --extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
+ python -m pip install --pre --extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
python -m pip install git+https://github.com/nedbat/coveragepy.git
python -m pip install python-dateutil pytz cython hypothesis==6.52.1 pytest>=6.2.5 pytest-xdist pytest-cov pytest-asyncio>=0.17
python -m pip list
| Backport PR #50728: CI fix failing python-dev job | https://api.github.com/repos/pandas-dev/pandas/pulls/50731 | 2023-01-13T13:27:27Z | 2023-01-13T15:07:44Z | 2023-01-13T15:07:44Z | 2023-01-13T15:07:44Z |
TST: mark copy_view test_switch_options test as single_cpu | diff --git a/pandas/tests/copy_view/test_internals.py b/pandas/tests/copy_view/test_internals.py
index 7a2965f2e1c61..1938a1c58fe3d 100644
--- a/pandas/tests/copy_view/test_internals.py
+++ b/pandas/tests/copy_view/test_internals.py
@@ -65,6 +65,7 @@ def test_clear_parent(using_copy_on_write):
assert subset._mgr.parent is None
+@pytest.mark.single_cpu
@td.skip_array_manager_invalid_test
def test_switch_options():
# ensure we can switch the value of the option within one session
| While backporting https://github.com/pandas-dev/pandas/pull/49771 in https://github.com/pandas-dev/pandas/pull/50128, I had to mark the test to not run in parallel to get it passing. This was not needed on the main branch, but since this can depend on the exact order and presence of other tests, seems safer to apply this to the main branch as well. | https://api.github.com/repos/pandas-dev/pandas/pulls/50729 | 2023-01-13T12:53:35Z | 2023-01-13T15:56:52Z | 2023-01-13T15:56:51Z | 2023-01-13T20:03:24Z |
CI fix failing python-dev job | diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index cded739856a82..2ece92dc50b87 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -73,7 +73,7 @@ jobs:
run: |
python --version
python -m pip install --upgrade pip setuptools wheel
- python -m pip install --extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
+ python -m pip install --pre --extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
python -m pip install git+https://github.com/nedbat/coveragepy.git
python -m pip install versioneer[toml]
python -m pip install python-dateutil pytz cython hypothesis>=6.34.2 pytest>=7.0.0 pytest-xdist>=2.2.0 pytest-cov pytest-asyncio>=0.17
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
without `--pre`, it wasn't taking the latest nightly | https://api.github.com/repos/pandas-dev/pandas/pulls/50728 | 2023-01-13T10:42:53Z | 2023-01-13T13:26:53Z | 2023-01-13T13:26:53Z | 2023-01-13T13:27:01Z |
Backport PR #50630 on branch 1.5.x (BUG: Fix bug in putmask for CoW) | diff --git a/doc/source/whatsnew/v1.5.3.rst b/doc/source/whatsnew/v1.5.3.rst
index b2039abe9f715..9263ee42c98c0 100644
--- a/doc/source/whatsnew/v1.5.3.rst
+++ b/doc/source/whatsnew/v1.5.3.rst
@@ -26,6 +26,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
+- Bug in the Copy-on-Write implementation losing track of views when indexing a :class:`DataFrame` with another :class:`DataFrame` (:issue:`50630`)
- Bug in :meth:`.Styler.to_excel` leading to error when unrecognized ``border-style`` (e.g. ``"hair"``) provided to Excel writers (:issue:`48649`)
- Bug when chaining several :meth:`.Styler.concat` calls, only the last styler was concatenated (:issue:`49207`)
- Fixed bug when instantiating a :class:`DataFrame` subclass inheriting from ``typing.Generic`` that triggered a ``UserWarning`` on python 3.11 (:issue:`49649`)
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 82d39fab54106..1f95808437614 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -393,10 +393,8 @@ def setitem(self: T, indexer, value) -> T:
return self.apply("setitem", indexer=indexer, value=value)
def putmask(self, mask, new, align: bool = True):
- if (
- _using_copy_on_write()
- and self.refs is not None
- and not all(ref is None for ref in self.refs)
+ if _using_copy_on_write() and any(
+ not self._has_no_reference_block(i) for i in range(len(self.blocks))
):
# some reference -> copy full dataframe
# TODO(CoW) this could be optimized to only copy the blocks that would
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py
index 956e2cf98c9b6..0b366f378fa13 100644
--- a/pandas/tests/copy_view/test_methods.py
+++ b/pandas/tests/copy_view/test_methods.py
@@ -214,3 +214,18 @@ def test_chained_methods(request, method, idx, using_copy_on_write):
df.iloc[0, 0] = 0
if not df2_is_view:
tm.assert_frame_equal(df2.iloc[:, idx:], df_orig)
+
+
+def test_putmask(using_copy_on_write):
+ df = DataFrame({"a": [1, 2], "b": 1, "c": 2})
+ view = df[:]
+ df_orig = df.copy()
+ df[df == df] = 5
+
+ if using_copy_on_write:
+ assert not np.shares_memory(get_array(view, "a"), get_array(df, "a"))
+ tm.assert_frame_equal(view, df_orig)
+ else:
+ # Without CoW the original will be modified
+ assert np.shares_memory(get_array(view, "a"), get_array(df, "a"))
+ assert view.iloc[0, 0] == 5
| #50630 | https://api.github.com/repos/pandas-dev/pandas/pulls/50726 | 2023-01-13T08:26:49Z | 2023-01-13T10:32:06Z | 2023-01-13T10:32:06Z | 2023-01-21T01:33:26Z |
TST: Cleanup more warning filtering | diff --git a/pandas/conftest.py b/pandas/conftest.py
index e4e32ab4a7350..1a410f87c8552 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -92,10 +92,6 @@
except zoneinfo.ZoneInfoNotFoundError: # type: ignore[attr-defined]
zoneinfo = None
-# Until https://github.com/numpy/numpy/issues/19078 is sorted out, just suppress
-suppress_npdev_promotion_warning = pytest.mark.filterwarnings(
- "ignore:Promotion of numbers and bools:FutureWarning"
-)
# ----------------------------------------------------------------
# Configuration / Settings
@@ -171,7 +167,6 @@ def pytest_collection_modifyitems(items, config) -> None:
# mark all tests in the pandas/tests/frame directory with "arraymanager"
if "/frame/" in item.nodeid:
item.add_marker(pytest.mark.arraymanager)
- item.add_marker(suppress_npdev_promotion_warning)
for (mark, kwd, skip_if_found, arg_name) in marks:
if kwd in item.keywords:
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index f9c6465cd948e..1ee74f62b6645 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -752,7 +752,9 @@ def get_median(x):
return np.nan
with warnings.catch_warnings():
# Suppress RuntimeWarning about All-NaN slice
- warnings.filterwarnings("ignore", "All-NaN slice encountered")
+ warnings.filterwarnings(
+ "ignore", "All-NaN slice encountered", RuntimeWarning
+ )
res = np.nanmedian(x[mask])
return res
@@ -780,7 +782,9 @@ def get_median(x):
# fastpath for the skipna case
with warnings.catch_warnings():
# Suppress RuntimeWarning about All-NaN slice
- warnings.filterwarnings("ignore", "All-NaN slice encountered")
+ warnings.filterwarnings(
+ "ignore", "All-NaN slice encountered", RuntimeWarning
+ )
res = np.nanmedian(values, axis)
else:
diff --git a/pandas/tests/arrays/floating/test_function.py b/pandas/tests/arrays/floating/test_function.py
index f31ac8f885de6..f2af3118c6cbe 100644
--- a/pandas/tests/arrays/floating/test_function.py
+++ b/pandas/tests/arrays/floating/test_function.py
@@ -9,7 +9,7 @@
@pytest.mark.parametrize("ufunc", [np.abs, np.sign])
# np.sign emits a warning with nans, <https://github.com/numpy/numpy/issues/15127>
-@pytest.mark.filterwarnings("ignore:invalid value encountered in sign")
+@pytest.mark.filterwarnings("ignore:invalid value encountered in sign:RuntimeWarning")
def test_ufuncs_single(ufunc):
a = pd.array([1, 2, -3, np.nan], dtype="Float64")
result = ufunc(a)
diff --git a/pandas/tests/arrays/integer/test_function.py b/pandas/tests/arrays/integer/test_function.py
index 000ed477666ea..e5177e9e50d71 100644
--- a/pandas/tests/arrays/integer/test_function.py
+++ b/pandas/tests/arrays/integer/test_function.py
@@ -8,7 +8,7 @@
@pytest.mark.parametrize("ufunc", [np.abs, np.sign])
# np.sign emits a warning with nans, <https://github.com/numpy/numpy/issues/15127>
-@pytest.mark.filterwarnings("ignore:invalid value encountered in sign")
+@pytest.mark.filterwarnings("ignore:invalid value encountered in sign:RuntimeWarning")
def test_ufuncs_single_int(ufunc):
a = pd.array([1, 2, -3, np.nan])
result = ufunc(a)
diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py
index 477d3b05c0a74..c4d02d71390cc 100644
--- a/pandas/tests/io/excel/test_xlsxwriter.py
+++ b/pandas/tests/io/excel/test_xlsxwriter.py
@@ -1,5 +1,4 @@
import contextlib
-import warnings
import pytest
@@ -16,10 +15,7 @@
def test_column_format(ext):
# Test that column formats are applied to cells. Test for issue #9167.
# Applicable to xlsxwriter only.
- with warnings.catch_warnings():
- # Ignore the openpyxl lxml warning.
- warnings.simplefilter("ignore")
- openpyxl = pytest.importorskip("openpyxl")
+ openpyxl = pytest.importorskip("openpyxl")
with tm.ensure_clean(ext) as path:
frame = DataFrame({"A": [123456, 123456], "B": [123456, 123456]})
diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py
index f4c8b9e764d6d..8cd5b8adb27a5 100644
--- a/pandas/tests/io/json/test_json_table_schema.py
+++ b/pandas/tests/io/json/test_json_table_schema.py
@@ -260,9 +260,6 @@ def test_read_json_from_to_json_results(self):
tm.assert_frame_equal(result1, df)
tm.assert_frame_equal(result2, df)
- @pytest.mark.filterwarnings(
- "ignore:an integer is required (got type float)*:DeprecationWarning"
- )
def test_to_json(self, df_table):
df = df_table
df.index.name = "idx"
@@ -439,9 +436,6 @@ def test_to_json_categorical_index(self):
assert result == expected
- @pytest.mark.filterwarnings(
- "ignore:an integer is required (got type float)*:DeprecationWarning"
- )
def test_date_format_raises(self, df_table):
msg = (
"Trying to write with `orient='table'` and `date_format='epoch'`. Table "
@@ -785,9 +779,6 @@ def test_read_json_table_timezones_orient(self, idx, vals, recwarn):
result = pd.read_json(out, orient="table")
tm.assert_frame_equal(df, result)
- @pytest.mark.filterwarnings(
- "ignore:an integer is required (got type float)*:DeprecationWarning"
- )
def test_comprehensive(self):
df = DataFrame(
{
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index d1de676a4eb2e..36a91d587a2ef 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -32,9 +32,6 @@ def assert_json_roundtrip_equal(result, expected, orient):
tm.assert_frame_equal(result, expected)
-@pytest.mark.filterwarnings(
- "ignore:an integer is required (got type float)*:DeprecationWarning"
-)
class TestPandasContainer:
@pytest.fixture
def categorical_frame(self):
diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py
index 798d64899a43c..845b6e373edd7 100644
--- a/pandas/tests/io/parser/common/test_read_errors.py
+++ b/pandas/tests/io/parser/common/test_read_errors.py
@@ -221,9 +221,9 @@ def test_open_file(request, all_parsers):
file = Path(path)
file.write_bytes(b"\xe4\na\n1")
- # should not trigger a ResourceWarning
- warnings.simplefilter("always", category=ResourceWarning)
with warnings.catch_warnings(record=True) as record:
+ # should not trigger a ResourceWarning
+ warnings.simplefilter("always", category=ResourceWarning)
with pytest.raises(csv.Error, match="Could not determine delimiter"):
parser.read_csv(file, sep=None, encoding_errors="replace")
assert len(record) == 0, record[0].message
diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py
index 5633b9f8a71c7..80562e77cae02 100644
--- a/pandas/tests/io/pytables/test_append.py
+++ b/pandas/tests/io/pytables/test_append.py
@@ -26,7 +26,6 @@
pytestmark = pytest.mark.single_cpu
-@pytest.mark.filterwarnings("ignore:object name:tables.exceptions.NaturalNameWarning")
def test_append(setup_path):
with ensure_clean_store(setup_path) as store:
diff --git a/pandas/tests/io/pytables/test_retain_attributes.py b/pandas/tests/io/pytables/test_retain_attributes.py
index 4a2bfee5dc2dc..3043cd3604e58 100644
--- a/pandas/tests/io/pytables/test_retain_attributes.py
+++ b/pandas/tests/io/pytables/test_retain_attributes.py
@@ -73,9 +73,6 @@ def test_retain_index_attributes(setup_path):
store.append("df2", df3)
-@pytest.mark.filterwarnings(
- "ignore:\\nthe :pandas.io.pytables.AttributeConflictWarning"
-)
def test_retain_index_attributes2(tmp_path, setup_path):
path = tmp_path / setup_path
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index cf83dfdad3f1f..06684f076aefe 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -31,9 +31,6 @@
)
_default_compressor = "blosc"
-ignore_natural_naming_warning = pytest.mark.filterwarnings(
- "ignore:object name:tables.exceptions.NaturalNameWarning"
-)
from pandas.io.pytables import (
HDFStore,
@@ -154,7 +151,6 @@ def test_repr(setup_path):
str(s)
-@pytest.mark.filterwarnings("ignore:object name:tables.exceptions.NaturalNameWarning")
def test_contains(setup_path):
with ensure_clean_store(setup_path) as store:
@@ -598,9 +594,6 @@ def test_overwrite_node(setup_path):
tm.assert_series_equal(store["a"], ts)
-@pytest.mark.filterwarnings(
- "ignore:\\nthe :pandas.io.pytables.AttributeConflictWarning"
-)
def test_coordinates(setup_path):
df = tm.makeTimeDataFrame()
@@ -972,9 +965,6 @@ def test_columns_multiindex_modified(tmp_path, setup_path):
assert cols2load_original == cols2load
-pytest.mark.filterwarnings("ignore:object name:tables.exceptions.NaturalNameWarning")
-
-
def test_to_hdf_with_object_column_names(tmp_path, setup_path):
# GH9057
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index f83b6b0373a87..06ab39b878e85 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -665,7 +665,12 @@ def psql_insert_copy(table, conn, keys, data_iter):
def test_execute_typeerror(sqlite_iris_engine):
with pytest.raises(TypeError, match="pandas.io.sql.execute requires a connection"):
- sql.execute("select * from iris", sqlite_iris_engine)
+ with tm.assert_produces_warning(
+ FutureWarning,
+ match="`pandas.io.sql.execute` is deprecated and "
+ "will be removed in the future version.",
+ ):
+ sql.execute("select * from iris", sqlite_iris_engine)
def test_execute_deprecated(sqlite_buildin_iris):
diff --git a/pandas/tests/window/test_win_type.py b/pandas/tests/window/test_win_type.py
index 71a7f8e76d058..8438e0727c174 100644
--- a/pandas/tests/window/test_win_type.py
+++ b/pandas/tests/window/test_win_type.py
@@ -110,7 +110,6 @@ def test_constructor_with_win_type_invalid(frame_or_series):
@td.skip_if_no_scipy
-@pytest.mark.filterwarnings("ignore:can't resolve:ImportWarning")
def test_window_with_args(step):
# make sure that we are aggregating window functions correctly with arg
r = Series(np.random.randn(100)).rolling(
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50723 | 2023-01-13T01:58:42Z | 2023-01-13T23:27:02Z | 2023-01-13T23:27:02Z | 2023-01-13T23:27:05Z |
REF: stricter typing, better naming in parsing.pyx | diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 10bcf6c9eabbf..03450c53781c7 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -770,6 +770,15 @@ cdef _array_to_datetime_object(
oresult[i] = "NaT"
cnp.PyArray_MultiIter_NEXT(mi)
continue
+ elif val == "now":
+ oresult[i] = datetime.now()
+ cnp.PyArray_MultiIter_NEXT(mi)
+ continue
+ elif val == "today":
+ oresult[i] = datetime.today()
+ cnp.PyArray_MultiIter_NEXT(mi)
+ continue
+
try:
oresult[i] = parse_datetime_string(val, dayfirst=dayfirst,
yearfirst=yearfirst)
diff --git a/pandas/_libs/tslibs/parsing.pyi b/pandas/_libs/tslibs/parsing.pyi
index a4440ffff5be9..c5d53f77762f9 100644
--- a/pandas/_libs/tslibs/parsing.pyi
+++ b/pandas/_libs/tslibs/parsing.pyi
@@ -2,7 +2,6 @@ from datetime import datetime
import numpy as np
-from pandas._libs.tslibs.offsets import BaseOffset
from pandas._typing import npt
class DateParseError(ValueError): ...
@@ -12,9 +11,9 @@ def parse_datetime_string(
dayfirst: bool = ...,
yearfirst: bool = ...,
) -> datetime: ...
-def parse_time_string(
- arg: str,
- freq: BaseOffset | str | None = ...,
+def parse_datetime_string_with_reso(
+ date_string: str,
+ freq: str | None = ...,
dayfirst: bool | None = ...,
yearfirst: bool | None = ...,
) -> tuple[datetime, str]: ...
diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx
index dabeab3e30f4d..36794d9a539de 100644
--- a/pandas/_libs/tslibs/parsing.pyx
+++ b/pandas/_libs/tslibs/parsing.pyx
@@ -59,7 +59,6 @@ from pandas._libs.tslibs.np_datetime cimport (
npy_datetimestruct,
string_to_dts,
)
-from pandas._libs.tslibs.offsets cimport is_offset_object
from pandas._libs.tslibs.strptime import array_strptime
from pandas._libs.tslibs.util cimport (
get_c_string_buf_and_size,
@@ -257,6 +256,10 @@ def parse_datetime_string(
Returns
-------
datetime
+
+ Notes
+ -----
+ Does not handle "today" or "now", which caller is responsible for handling.
"""
cdef:
@@ -275,14 +278,6 @@ def parse_datetime_string(
if dt is not None:
return dt
- # Handling special case strings today & now
- if date_string == "now":
- dt = datetime.now()
- return dt
- elif date_string == "today":
- dt = datetime.today()
- return dt
-
try:
dt, _ = _parse_dateabbr_string(date_string, _DEFAULT_DATETIME, freq=None)
return dt
@@ -308,16 +303,22 @@ def parse_datetime_string(
return dt
-def parse_time_string(arg, freq=None, dayfirst=None, yearfirst=None):
+def parse_datetime_string_with_reso(
+ str date_string, str freq=None, dayfirst=None, yearfirst=None
+):
+ # NB: This will break with np.str_ (GH#45580) even though
+ # isinstance(npstrobj, str) evaluates to True, so caller must ensure
+ # the argument is *exactly* 'str'
"""
Try hard to parse datetime string, leveraging dateutil plus some extra
goodies like quarter recognition.
Parameters
----------
- arg : str
- freq : str or DateOffset, default None
+ date_string : str
+ freq : str or None, default None
Helps with interpreting time string if supplied
+ Corresponds to `offset.rule_code`
dayfirst : bool, default None
If None uses default from print_config
yearfirst : bool, default None
@@ -328,50 +329,21 @@ def parse_time_string(arg, freq=None, dayfirst=None, yearfirst=None):
datetime
str
Describing resolution of parsed string.
- """
- if type(arg) is not str:
- # GH#45580 np.str_ satisfies isinstance(obj, str) but if we annotate
- # arg as "str" this raises here
- if not isinstance(arg, np.str_):
- raise TypeError(
- "Argument 'arg' has incorrect type "
- f"(expected str, got {type(arg).__name__})"
- )
- arg = str(arg)
- if is_offset_object(freq):
- freq = freq.rule_code
+ Raises
+ ------
+ ValueError : preliminary check suggests string is not datetime
+ DateParseError : error within dateutil
+ """
if dayfirst is None:
dayfirst = get_option("display.date_dayfirst")
if yearfirst is None:
yearfirst = get_option("display.date_yearfirst")
- res = parse_datetime_string_with_reso(arg, freq=freq,
- dayfirst=dayfirst,
- yearfirst=yearfirst)
- return res
-
-
-cdef parse_datetime_string_with_reso(
- str date_string, str freq=None, bint dayfirst=False, bint yearfirst=False,
-):
- """
- Parse datetime string and try to identify its resolution.
-
- Returns
- -------
- datetime
- str
- Inferred resolution of the parsed string.
-
- Raises
- ------
- ValueError : preliminary check suggests string is not datetime
- DateParseError : error within dateutil
- """
cdef:
- object parsed, reso
+ datetime parsed
+ str reso
bint string_to_dts_failed
npy_datetimestruct dts
NPY_DATETIMEUNIT out_bestunit
@@ -483,7 +455,7 @@ cpdef bint _does_string_look_like_datetime(str py_string):
cdef object _parse_dateabbr_string(object date_string, datetime default,
str freq=None):
cdef:
- object ret
+ datetime ret
# year initialized to prevent compiler warnings
int year = -1, quarter = -1, month
Py_ssize_t date_len
@@ -505,8 +477,8 @@ cdef object _parse_dateabbr_string(object date_string, datetime default,
except ValueError:
pass
- try:
- if 4 <= date_len <= 7:
+ if 4 <= date_len <= 7:
+ try:
i = date_string.index("Q", 1, 6)
if i == 1:
quarter = int(date_string[0])
@@ -553,10 +525,11 @@ cdef object _parse_dateabbr_string(object date_string, datetime default,
ret = default.replace(year=year, month=month)
return ret, "quarter"
- except DateParseError:
- raise
- except ValueError:
- pass
+ except DateParseError:
+ raise
+ except ValueError:
+ # e.g. if "Q" is not in date_string and .index raised
+ pass
if date_len == 6 and freq == "M":
year = int(date_string[:4])
@@ -564,8 +537,9 @@ cdef object _parse_dateabbr_string(object date_string, datetime default,
try:
ret = default.replace(year=year, month=month)
return ret, "month"
- except ValueError:
- pass
+ except ValueError as err:
+ # We can infer that none of the patterns below will match
+ raise ValueError(f"Unable to parse {date_string}") from err
for pat in ["%Y-%m", "%b %Y", "%b-%Y"]:
try:
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index f93afc0d1c3f2..64bd76adb0ae2 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -88,7 +88,7 @@ from pandas._libs.tslibs.dtypes cimport (
)
from pandas._libs.tslibs.parsing cimport quarter_to_myear
-from pandas._libs.tslibs.parsing import parse_time_string
+from pandas._libs.tslibs.parsing import parse_datetime_string_with_reso
from pandas._libs.tslibs.nattype cimport (
NPY_NAT,
@@ -2589,7 +2589,9 @@ class Period(_Period):
value = str(value)
value = value.upper()
- dt, reso = parse_time_string(value, freq)
+
+ freqstr = freq.rule_code if freq is not None else None
+ dt, reso = parse_datetime_string_with_reso(value, freqstr)
try:
ts = Timestamp(value)
except ValueError:
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 002b9832e9e6e..ea0c93e75f496 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -241,7 +241,18 @@ def _parse_with_reso(self, label: str):
freq = self.freq
except NotImplementedError:
freq = getattr(self, "freqstr", getattr(self, "inferred_freq", None))
- parsed, reso_str = parsing.parse_time_string(label, freq)
+
+ freqstr: str | None
+ if freq is not None and not isinstance(freq, str):
+ freqstr = freq.rule_code
+ else:
+ freqstr = freq
+
+ if isinstance(label, np.str_):
+ # GH#45580
+ label = str(label)
+
+ parsed, reso_str = parsing.parse_datetime_string_with_reso(label, freqstr)
reso = Resolution.from_attrname(reso_str)
return parsed, reso
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index cb65ecf411118..50d0c649fffc2 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -276,8 +276,9 @@ def test_loc_npstr(self):
def test_contains_raise_error_if_period_index_is_in_multi_index(self, msg, key):
# GH#20684
"""
- parse_time_string return parameter if type not matched.
- PeriodIndex.get_loc takes returned value from parse_time_string as a tuple.
+ parse_datetime_string_with_reso return parameter if type not matched.
+ PeriodIndex.get_loc takes returned value from parse_datetime_string_with_reso
+ as a tuple.
If first argument is Period and a tuple has 3 items,
process go on not raise exception
"""
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index dd1012d57d6bc..75cec7931edcc 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -1623,10 +1623,14 @@ def test_mixed_offsets_with_native_datetime_raises(self):
"2015-03-14T16:15:14.123-08:00",
"2019-03-04T21:56:32.620-07:00",
None,
+ "today",
+ "now",
]
ser = Series(vals)
assert all(ser[i] is vals[i] for i in range(len(vals))) # GH#40111
+ now = Timestamp("now")
+ today = Timestamp("today")
mixed = to_datetime(ser)
expected = Series(
[
@@ -1638,7 +1642,11 @@ def test_mixed_offsets_with_native_datetime_raises(self):
],
dtype=object,
)
- tm.assert_series_equal(mixed, expected)
+ tm.assert_series_equal(mixed[:-2], expected)
+ # we'll check mixed[-1] and mixed[-2] match now and today to within
+ # call-timing tolerances
+ assert (now - mixed.iloc[-1]).total_seconds() <= 0.1
+ assert (today - mixed.iloc[-2]).total_seconds() <= 0.1
with pytest.raises(ValueError, match="Tz-aware datetime.datetime"):
to_datetime(mixed)
@@ -2901,7 +2909,9 @@ def test_parsers(self, date_str, expected, warning, cache):
# https://github.com/dateutil/dateutil/issues/217
yearfirst = True
- result1, _ = parsing.parse_time_string(date_str, yearfirst=yearfirst)
+ result1, _ = parsing.parse_datetime_string_with_reso(
+ date_str, yearfirst=yearfirst
+ )
with tm.assert_produces_warning(warning, match="Could not infer format"):
result2 = to_datetime(date_str, yearfirst=yearfirst)
result3 = to_datetime([date_str], yearfirst=yearfirst)
@@ -2937,7 +2947,7 @@ def test_na_values_with_cache(
def test_parsers_nat(self):
# Test that each of several string-accepting methods return pd.NaT
- result1, _ = parsing.parse_time_string("NaT")
+ result1, _ = parsing.parse_datetime_string_with_reso("NaT")
result2 = to_datetime("NaT")
result3 = Timestamp("NaT")
result4 = DatetimeIndex(["NaT"])[0]
@@ -3008,7 +3018,7 @@ def test_parsers_dayfirst_yearfirst(
dateutil_result = parse(date_str, dayfirst=dayfirst, yearfirst=yearfirst)
assert dateutil_result == expected
- result1, _ = parsing.parse_time_string(
+ result1, _ = parsing.parse_datetime_string_with_reso(
date_str, dayfirst=dayfirst, yearfirst=yearfirst
)
@@ -3036,7 +3046,7 @@ def test_parsers_timestring(self, date_str, exp_def):
# must be the same as dateutil result
exp_now = parse(date_str)
- result1, _ = parsing.parse_time_string(date_str)
+ result1, _ = parsing.parse_datetime_string_with_reso(date_str)
with tm.assert_produces_warning(UserWarning, match="Could not infer format"):
result2 = to_datetime(date_str)
result3 = to_datetime([date_str])
diff --git a/pandas/tests/tslibs/test_parsing.py b/pandas/tests/tslibs/test_parsing.py
index c3a989cee7b02..33fce7b351513 100644
--- a/pandas/tests/tslibs/test_parsing.py
+++ b/pandas/tests/tslibs/test_parsing.py
@@ -12,31 +12,31 @@
parsing,
strptime,
)
-from pandas._libs.tslibs.parsing import parse_time_string
+from pandas._libs.tslibs.parsing import parse_datetime_string_with_reso
import pandas.util._test_decorators as td
import pandas._testing as tm
-def test_parse_time_string():
- (parsed, reso) = parse_time_string("4Q1984")
- (parsed_lower, reso_lower) = parse_time_string("4q1984")
+def test_parse_datetime_string_with_reso():
+ (parsed, reso) = parse_datetime_string_with_reso("4Q1984")
+ (parsed_lower, reso_lower) = parse_datetime_string_with_reso("4q1984")
assert reso == reso_lower
assert parsed == parsed_lower
-def test_parse_time_string_nanosecond_reso():
+def test_parse_datetime_string_with_reso_nanosecond_reso():
# GH#46811
- parsed, reso = parse_time_string("2022-04-20 09:19:19.123456789")
+ parsed, reso = parse_datetime_string_with_reso("2022-04-20 09:19:19.123456789")
assert reso == "nanosecond"
-def test_parse_time_string_invalid_type():
+def test_parse_datetime_string_with_reso_invalid_type():
# Raise on invalid input, don't just return it
- msg = "Argument 'arg' has incorrect type (expected str, got tuple)"
+ msg = "Argument 'date_string' has incorrect type (expected str, got tuple)"
with pytest.raises(TypeError, match=re.escape(msg)):
- parse_time_string((4, 5))
+ parse_datetime_string_with_reso((4, 5))
@pytest.mark.parametrize(
@@ -44,8 +44,8 @@ def test_parse_time_string_invalid_type():
)
def test_parse_time_quarter_with_dash(dashed, normal):
# see gh-9688
- (parsed_dash, reso_dash) = parse_time_string(dashed)
- (parsed, reso) = parse_time_string(normal)
+ (parsed_dash, reso_dash) = parse_datetime_string_with_reso(dashed)
+ (parsed, reso) = parse_datetime_string_with_reso(normal)
assert parsed_dash == parsed
assert reso_dash == reso
@@ -56,7 +56,7 @@ def test_parse_time_quarter_with_dash_error(dashed):
msg = f"Unknown datetime string format, unable to parse: {dashed}"
with pytest.raises(parsing.DateParseError, match=msg):
- parse_time_string(dashed)
+ parse_datetime_string_with_reso(dashed)
@pytest.mark.parametrize(
@@ -103,7 +103,7 @@ def test_does_not_convert_mixed_integer(date_string, expected):
)
def test_parsers_quarterly_with_freq_error(date_str, kwargs, msg):
with pytest.raises(parsing.DateParseError, match=msg):
- parsing.parse_time_string(date_str, **kwargs)
+ parsing.parse_datetime_string_with_reso(date_str, **kwargs)
@pytest.mark.parametrize(
@@ -115,7 +115,7 @@ def test_parsers_quarterly_with_freq_error(date_str, kwargs, msg):
],
)
def test_parsers_quarterly_with_freq(date_str, freq, expected):
- result, _ = parsing.parse_time_string(date_str, freq=freq)
+ result, _ = parsing.parse_datetime_string_with_reso(date_str, freq=freq)
assert result == expected
@@ -132,7 +132,7 @@ def test_parsers_quarter_invalid(date_str):
msg = f"Unknown datetime string format, unable to parse: {date_str}"
with pytest.raises(ValueError, match=msg):
- parsing.parse_time_string(date_str)
+ parsing.parse_datetime_string_with_reso(date_str)
@pytest.mark.parametrize(
@@ -140,7 +140,7 @@ def test_parsers_quarter_invalid(date_str):
[("201101", datetime(2011, 1, 1, 0, 0)), ("200005", datetime(2000, 5, 1, 0, 0))],
)
def test_parsers_month_freq(date_str, expected):
- result, _ = parsing.parse_time_string(date_str, freq="M")
+ result, _ = parsing.parse_datetime_string_with_reso(date_str, freq="M")
assert result == expected
@@ -284,13 +284,13 @@ def test_try_parse_dates():
tm.assert_numpy_array_equal(result, expected)
-def test_parse_time_string_check_instance_type_raise_exception():
+def test_parse_datetime_string_with_reso_check_instance_type_raise_exception():
# issue 20684
- msg = "Argument 'arg' has incorrect type (expected str, got tuple)"
+ msg = "Argument 'date_string' has incorrect type (expected str, got tuple)"
with pytest.raises(TypeError, match=re.escape(msg)):
- parse_time_string((1, 2, 3))
+ parse_datetime_string_with_reso((1, 2, 3))
- result = parse_time_string("2019")
+ result = parse_datetime_string_with_reso("2019")
expected = (datetime(2019, 1, 1), "year")
assert result == expected
| Trying to move towards having fewer different string parsing paths. | https://api.github.com/repos/pandas-dev/pandas/pulls/50722 | 2023-01-13T00:46:23Z | 2023-01-13T21:38:02Z | 2023-01-13T21:38:02Z | 2023-01-13T21:38:08Z |
DOC: improve Index docstrings | diff --git a/pandas/core/base.py b/pandas/core/base.py
index 826583fd26f5d..3f32f3cff8607 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -784,6 +784,10 @@ def hasnans(self) -> bool:
Return True if there are any NaNs.
Enables various performance speedups.
+
+ Returns
+ -------
+ bool
"""
# error: Item "bool" of "Union[bool, ndarray[Any, dtype[bool_]], NDFrame]"
# has no attribute "any"
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 59af8f2bbcd51..f0d8a83219bbf 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -2084,13 +2084,21 @@ def is_monotonic_increasing(self) -> bool:
"""
Return a boolean if the values are equal or increasing.
+ Returns
+ -------
+ bool
+
+ See Also
+ --------
+ Index.is_monotonic_decreasing : Check if the values are equal or decreasing.
+
Examples
--------
- >>> Index([1, 2, 3]).is_monotonic_increasing
+ >>> pd.Index([1, 2, 3]).is_monotonic_increasing
True
- >>> Index([1, 2, 2]).is_monotonic_increasing
+ >>> pd.Index([1, 2, 2]).is_monotonic_increasing
True
- >>> Index([1, 3, 2]).is_monotonic_increasing
+ >>> pd.Index([1, 3, 2]).is_monotonic_increasing
False
"""
return self._engine.is_monotonic_increasing
@@ -2100,13 +2108,21 @@ def is_monotonic_decreasing(self) -> bool:
"""
Return a boolean if the values are equal or decreasing.
+ Returns
+ -------
+ bool
+
+ See Also
+ --------
+ Index.is_monotonic_increasing : Check if the values are equal or increasing.
+
Examples
--------
- >>> Index([3, 2, 1]).is_monotonic_decreasing
+ >>> pd.Index([3, 2, 1]).is_monotonic_decreasing
True
- >>> Index([3, 2, 2]).is_monotonic_decreasing
+ >>> pd.Index([3, 2, 2]).is_monotonic_decreasing
True
- >>> Index([3, 1, 2]).is_monotonic_decreasing
+ >>> pd.Index([3, 1, 2]).is_monotonic_decreasing
False
"""
return self._engine.is_monotonic_decreasing
@@ -2151,6 +2167,34 @@ def _is_strictly_monotonic_decreasing(self) -> bool:
def is_unique(self) -> bool:
"""
Return if the index has unique values.
+
+ Returns
+ -------
+ bool
+
+ See Also
+ --------
+ Index.has_duplicates : Inverse method that checks if it has duplicate values.
+
+ Examples
+ --------
+ >>> idx = pd.Index([1, 5, 7, 7])
+ >>> idx.is_unique
+ False
+
+ >>> idx = pd.Index([1, 5, 7])
+ >>> idx.is_unique
+ True
+
+ >>> idx = pd.Index(["Watermelon", "Orange", "Apple",
+ ... "Watermelon"]).astype("category")
+ >>> idx.is_unique
+ False
+
+ >>> idx = pd.Index(["Orange", "Apple",
+ ... "Watermelon"]).astype("category")
+ >>> idx.is_unique
+ True
"""
return self._engine.is_unique
@@ -2165,6 +2209,10 @@ def has_duplicates(self) -> bool:
bool
Whether or not the Index has duplicate values.
+ See Also
+ --------
+ Index.is_unique : Inverse method that checks if it has unique values.
+
Examples
--------
>>> idx = pd.Index([1, 5, 7, 7])
@@ -2564,6 +2612,10 @@ def hasnans(self) -> bool:
Return True if there are any NaNs.
Enables various performance speedups.
+
+ Returns
+ -------
+ bool
"""
if self._can_hold_na:
return bool(self._isnan.any())
| - [X] xref #37875 and #27977
- ~~[Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature~~
- [X] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- ~~Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.~~
- ~~Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.~~
Improve docstring of the following methods:
`Index.is_monotonic_increasing`
<details>
<summary>output of scripts/validate_docstrings.py</summary>
```
################################################################################
############### Docstring (pandas.Index.is_monotonic_increasing) ###############
################################################################################
Return a boolean if the values are equal or increasing.
Returns
-------
bool
See Also
--------
Index.is_monotonic_decreasing : Check if the values are equal or decreasing.
Examples
--------
>>> pd.Index([1, 2, 3]).is_monotonic_increasing
True
>>> pd.Index([1, 2, 2]).is_monotonic_increasing
True
>>> pd.Index([1, 3, 2]).is_monotonic_increasing
False
################################################################################
################################## Validation ##################################
################################################################################
1 Errors found:
No extended summary found
```
</details>
`Index.is_monotonic_decreasing`
<details>
<summary>output of scripts/validate_docstrings.py</summary>
```
################################################################################
############### Docstring (pandas.Index.is_monotonic_decreasing) ###############
################################################################################
Return a boolean if the values are equal or decreasing.
Returns
-------
bool
See Also
--------
Index.is_monotonic_increasing : Check if the values are equal or increasing.
Examples
--------
>>> pd.Index([3, 2, 1]).is_monotonic_decreasing
True
>>> pd.Index([3, 2, 2]).is_monotonic_decreasing
True
>>> pd.Index([3, 1, 2]).is_monotonic_decreasing
False
################################################################################
################################## Validation ##################################
################################################################################
1 Errors found:
No extended summary found
```
</details>
`Index.hasnans`
<details>
<summary>output of scripts/validate_docstrings.py</summary>
```
################################################################################
####################### Docstring (pandas.Index.hasnans) #######################
################################################################################
Return True if there are any NaNs.
Enables various performance speedups.
Returns
-------
bool
################################################################################
################################## Validation ##################################
################################################################################
2 Errors found:
See Also section not found
No examples section found
```
</details>
`Index.has_duplicates`
<details>
<summary>output of scripts/validate_docstrings.py</summary>
```
################################################################################
################### Docstring (pandas.Index.has_duplicates) ###################
################################################################################
Check if the Index has duplicate values.
Returns
-------
bool
Whether or not the Index has duplicate values.
See Also
--------
Index.is_unique : Inverse method that checks if it has unique values.
Examples
--------
>>> idx = pd.Index([1, 5, 7, 7])
>>> idx.has_duplicates
True
>>> idx = pd.Index([1, 5, 7])
>>> idx.has_duplicates
False
>>> idx = pd.Index(["Watermelon", "Orange", "Apple",
... "Watermelon"]).astype("category")
>>> idx.has_duplicates
True
>>> idx = pd.Index(["Orange", "Apple",
... "Watermelon"]).astype("category")
>>> idx.has_duplicates
False
################################################################################
################################## Validation ##################################
################################################################################
1 Errors found:
No extended summary found
```
</details>
`Index.is_unique`
<details>
<summary>output of scripts/validate_docstrings.py</summary>
```
################################################################################
###################### Docstring (pandas.Index.is_unique) ######################
################################################################################
Return if the index has unique values.
Returns
-------
bool
See Also
--------
Index.has_duplicates : Inverse method that checks if it has duplicate values.
Examples
--------
>>> idx = pd.Index([1, 5, 7, 7])
>>> idx.is_unique
False
>>> idx = pd.Index([1, 5, 7])
>>> idx.is_unique
True
>>> idx = pd.Index(["Watermelon", "Orange", "Apple",
... "Watermelon"]).astype("category")
>>> idx.is_unique
False
>>> idx = pd.Index(["Orange", "Apple",
... "Watermelon"]).astype("category")
>>> idx.is_unique
True
################################################################################
################################## Validation ##################################
################################################################################
1 Errors found:
No extended summary found
```
</details>
| https://api.github.com/repos/pandas-dev/pandas/pulls/50720 | 2023-01-12T23:22:34Z | 2023-01-16T18:28:20Z | 2023-01-16T18:28:20Z | 2023-01-16T18:28:28Z |
BUG: .max() gives wrong answer for non-nanosecond datetimeindex | diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index b8e2b1fafe326..f9c6465cd948e 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -370,9 +370,9 @@ def _wrap_results(result, dtype: np.dtype, fill_value=None):
result = np.nan
if isna(result):
- result = np.datetime64("NaT", "ns")
+ result = np.datetime64("NaT", "ns").astype(dtype)
else:
- result = np.int64(result).view("datetime64[ns]")
+ result = np.int64(result).view(dtype)
# retain original unit
result = result.astype(dtype, copy=False)
else:
diff --git a/pandas/tests/arrays/datetimes/test_reductions.py b/pandas/tests/arrays/datetimes/test_reductions.py
index d0553f9608f25..59a4443ac9e19 100644
--- a/pandas/tests/arrays/datetimes/test_reductions.py
+++ b/pandas/tests/arrays/datetimes/test_reductions.py
@@ -10,6 +10,10 @@
class TestReductions:
+ @pytest.fixture(params=["s", "ms", "us", "ns"])
+ def unit(self, request):
+ return request.param
+
@pytest.fixture
def arr1d(self, tz_naive_fixture):
"""Fixture returning DatetimeArray with parametrized timezones"""
@@ -28,17 +32,20 @@ def arr1d(self, tz_naive_fixture):
)
return arr
- def test_min_max(self, arr1d):
+ def test_min_max(self, arr1d, unit):
arr = arr1d
+ arr = arr.as_unit(unit)
tz = arr.tz
result = arr.min()
- expected = pd.Timestamp("2000-01-02", tz=tz)
+ expected = pd.Timestamp("2000-01-02", tz=tz).as_unit(unit)
assert result == expected
+ assert result.unit == expected.unit
result = arr.max()
- expected = pd.Timestamp("2000-01-05", tz=tz)
+ expected = pd.Timestamp("2000-01-05", tz=tz).as_unit(unit)
assert result == expected
+ assert result.unit == expected.unit
result = arr.min(skipna=False)
assert result is NaT
diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py
index ae8791a774ed5..d6deafb9012ff 100644
--- a/pandas/tests/test_nanops.py
+++ b/pandas/tests/test_nanops.py
@@ -1157,10 +1157,14 @@ def prng(self):
class TestDatetime64NaNOps:
+ @pytest.fixture(params=["s", "ms", "us", "ns"])
+ def unit(self, request):
+ return request.param
+
# Enabling mean changes the behavior of DataFrame.mean
# See https://github.com/pandas-dev/pandas/issues/24752
- def test_nanmean(self):
- dti = pd.date_range("2016-01-01", periods=3)
+ def test_nanmean(self, unit):
+ dti = pd.date_range("2016-01-01", periods=3).as_unit(unit)
expected = dti[1]
for obj in [dti, DatetimeArray(dti), Series(dti)]:
@@ -1173,8 +1177,9 @@ def test_nanmean(self):
result = nanops.nanmean(obj)
assert result == expected
- @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
- def test_nanmean_skipna_false(self, dtype):
+ @pytest.mark.parametrize("constructor", ["M8", "m8"])
+ def test_nanmean_skipna_false(self, constructor, unit):
+ dtype = f"{constructor}[{unit}]"
arr = np.arange(12).astype(np.int64).view(dtype).reshape(4, 3)
arr[-1, -1] = "NaT"
| - [ ] closes #50716 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Does this need a whatsnew? I wouldn't have thought so, as this wasn't available in 1.5.x | https://api.github.com/repos/pandas-dev/pandas/pulls/50719 | 2023-01-12T21:39:17Z | 2023-01-13T16:44:27Z | 2023-01-13T16:44:27Z | 2023-01-13T16:44:27Z |
Backport PR #50685 on branch 1.5.x (BUG: Series.quantile emitting RuntimeWarning for all NA case) | diff --git a/doc/source/whatsnew/v1.5.3.rst b/doc/source/whatsnew/v1.5.3.rst
index b2039abe9f715..81f399233d824 100644
--- a/doc/source/whatsnew/v1.5.3.rst
+++ b/doc/source/whatsnew/v1.5.3.rst
@@ -27,6 +27,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
- Bug in :meth:`.Styler.to_excel` leading to error when unrecognized ``border-style`` (e.g. ``"hair"``) provided to Excel writers (:issue:`48649`)
+- Bug in :meth:`Series.quantile` emitting warning from NumPy when :class:`Series` has only ``NA`` values (:issue:`50681`)
- Bug when chaining several :meth:`.Styler.concat` calls, only the last styler was concatenated (:issue:`49207`)
- Fixed bug when instantiating a :class:`DataFrame` subclass inheriting from ``typing.Generic`` that triggered a ``UserWarning`` on python 3.11 (:issue:`49649`)
-
diff --git a/pandas/core/array_algos/quantile.py b/pandas/core/array_algos/quantile.py
index 217fbafce719c..d3d9cb1b29b9a 100644
--- a/pandas/core/array_algos/quantile.py
+++ b/pandas/core/array_algos/quantile.py
@@ -204,8 +204,10 @@ def _nanpercentile(
result = np.array(result, copy=False).T
if (
result.dtype != values.dtype
+ and not mask.all()
and (result == result.astype(values.dtype, copy=False)).all()
):
+ # mask.all() will never get cast back to int
# e.g. values id integer dtype and result is floating dtype,
# only cast back to integer dtype if result values are all-integer.
result = result.astype(values.dtype, copy=False)
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 7fd4f55940f23..5cdd632d39b3c 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -1026,6 +1026,11 @@ def _quantile(
raise NotImplementedError
elif self.isna().all():
out_mask = np.ones(res.shape, dtype=bool)
+
+ if is_integer_dtype(self.dtype):
+ # We try to maintain int dtype if possible for not all-na case
+ # as well
+ res = np.zeros(res.shape, dtype=self.dtype.numpy_dtype)
else:
out_mask = np.zeros(res.shape, dtype=bool)
else:
diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py
index 14b416011b956..139360d332916 100644
--- a/pandas/tests/frame/methods/test_quantile.py
+++ b/pandas/tests/frame/methods/test_quantile.py
@@ -929,15 +929,8 @@ def test_quantile_ea_all_na(self, request, obj, index):
qs = [0.5, 0, 1]
result = self.compute_quantile(obj, qs)
- if np_version_under1p21 and index.dtype == "timedelta64[ns]":
- msg = "failed on Numpy 1.20.3; TypeError: data type 'Int64' not understood"
- mark = pytest.mark.xfail(reason=msg, raises=TypeError)
- request.node.add_marker(mark)
-
expected = index.take([-1, -1, -1], allow_fill=True, fill_value=index._na_value)
expected = Series(expected, index=qs, name="A")
- if expected.dtype == "Int64":
- expected = expected.astype("Float64")
expected = type(obj)(expected)
tm.assert_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_quantile.py b/pandas/tests/series/methods/test_quantile.py
index aeff5b3adfe56..e740f569506ff 100644
--- a/pandas/tests/series/methods/test_quantile.py
+++ b/pandas/tests/series/methods/test_quantile.py
@@ -225,3 +225,18 @@ def test_quantile_dtypes(self, dtype):
if dtype == "Int64":
expected = expected.astype("Float64")
tm.assert_series_equal(result, expected)
+
+ def test_quantile_all_na(self, any_int_ea_dtype):
+ # GH#50681
+ ser = Series([pd.NA, pd.NA], dtype=any_int_ea_dtype)
+ with tm.assert_produces_warning(None):
+ result = ser.quantile([0.1, 0.5])
+ expected = Series([pd.NA, pd.NA], dtype=any_int_ea_dtype, index=[0.1, 0.5])
+ tm.assert_series_equal(result, expected)
+
+ def test_quantile_dtype_size(self, any_int_ea_dtype):
+ # GH#50681
+ ser = Series([pd.NA, pd.NA, 1], dtype=any_int_ea_dtype)
+ result = ser.quantile([0.1, 0.5])
+ expected = Series([1, 1], dtype=any_int_ea_dtype, index=[0.1, 0.5])
+ tm.assert_series_equal(result, expected)
| Backport PR #50685: BUG: Series.quantile emitting RuntimeWarning for all NA case | https://api.github.com/repos/pandas-dev/pandas/pulls/50718 | 2023-01-12T20:29:08Z | 2023-01-13T08:27:23Z | 2023-01-13T08:27:23Z | 2023-01-13T08:27:23Z |
ENH: support any/all for pyarrow numeric and duration dtypes | diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index e2a74ea6f5351..ddb2f01898ec7 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -1012,6 +1012,26 @@ def _reduce(self, name: str, *, skipna: bool = True, **kwargs):
------
TypeError : subclass does not define reductions
"""
+ pa_type = self._data.type
+
+ data_to_reduce = self._data
+
+ if name in ["any", "all"] and (
+ pa.types.is_integer(pa_type)
+ or pa.types.is_floating(pa_type)
+ or pa.types.is_duration(pa_type)
+ ):
+ # pyarrow only supports any/all for boolean dtype, we allow
+ # for other dtypes, matching our non-pyarrow behavior
+
+ if pa.types.is_duration(pa_type):
+ data_to_cmp = self._data.cast(pa.int64())
+ else:
+ data_to_cmp = self._data
+
+ not_eq = pc.not_equal(data_to_cmp, 0)
+ data_to_reduce = not_eq
+
if name == "sem":
def pyarrow_meth(data, skip_nulls, **kwargs):
@@ -1033,8 +1053,9 @@ def pyarrow_meth(data, skip_nulls, **kwargs):
if pyarrow_meth is None:
# Let ExtensionArray._reduce raise the TypeError
return super()._reduce(name, skipna=skipna, **kwargs)
+
try:
- result = pyarrow_meth(self._data, skip_nulls=skipna, **kwargs)
+ result = pyarrow_meth(data_to_reduce, skip_nulls=skipna, **kwargs)
except (AttributeError, NotImplementedError, TypeError) as err:
msg = (
f"'{type(self).__name__}' with dtype {self.dtype} "
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index a7c243cdfe74f..af3952a532113 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -566,10 +566,24 @@ def test_reduce_series(
f"pyarrow={pa.__version__} for {pa_dtype}"
),
)
- if not pa.types.is_boolean(pa_dtype):
+ if pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype):
+ # We *might* want to make this behave like the non-pyarrow cases,
+ # but have not yet decided.
request.node.add_marker(xfail_mark)
+
op_name = all_boolean_reductions
ser = pd.Series(data)
+
+ if pa.types.is_temporal(pa_dtype) and not pa.types.is_duration(pa_dtype):
+ # xref GH#34479 we support this in our non-pyarrow datetime64 dtypes,
+ # but it isn't obvious we _should_. For now, we keep the pyarrow
+ # behavior which does not support this.
+
+ with pytest.raises(TypeError, match="does not support reduction"):
+ getattr(ser, op_name)(skipna=skipna)
+
+ return
+
result = getattr(ser, op_name)(skipna=skipna)
assert result is (op_name == "any")
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Cuts the runtime for `pytest pandas/tests/extension/test_arrow.py::TestBaseBooleanReduce::test_reduce_series` from 39.8s to 2.3s. | https://api.github.com/repos/pandas-dev/pandas/pulls/50717 | 2023-01-12T20:00:48Z | 2023-01-24T18:21:34Z | 2023-01-24T18:21:34Z | 2023-01-24T18:24:01Z |
Backport PR #50706 on branch 1.5.x (Revert "CI temporarily pin numpy") | diff --git a/asv_bench/asv.conf.json b/asv_bench/asv.conf.json
index aef542e8c9f16..b1ea2682b7ea7 100644
--- a/asv_bench/asv.conf.json
+++ b/asv_bench/asv.conf.json
@@ -41,7 +41,7 @@
// pip (with all the conda available packages installed first,
// followed by the pip installed packages).
"matrix": {
- "numpy": ["1.23.5"], // https://github.com/pandas-dev/pandas/pull/50356
+ "numpy": [],
"Cython": ["0.29.32"],
"matplotlib": [],
"sqlalchemy": [],
diff --git a/ci/deps/actions-310-numpydev.yaml b/ci/deps/actions-310-numpydev.yaml
index 066ac7f013654..ef20c2aa889b9 100644
--- a/ci/deps/actions-310-numpydev.yaml
+++ b/ci/deps/actions-310-numpydev.yaml
@@ -19,5 +19,5 @@ dependencies:
- "cython"
- "--extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple"
- "--pre"
- - "numpy<1.24"
+ - "numpy"
- "scipy"
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml
index 397b5d8139336..deb23d435bddf 100644
--- a/ci/deps/actions-310.yaml
+++ b/ci/deps/actions-310.yaml
@@ -15,7 +15,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-38-downstream_compat.yaml
index a19f5bd8af878..06ffafeb70570 100644
--- a/ci/deps/actions-38-downstream_compat.yaml
+++ b/ci/deps/actions-38-downstream_compat.yaml
@@ -16,7 +16,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml
index 4d6e228cf21ab..222da40ea9eea 100644
--- a/ci/deps/actions-38.yaml
+++ b/ci/deps/actions-38.yaml
@@ -15,7 +15,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml
index 8e27f71ba0c01..1c60e8ad6d78a 100644
--- a/ci/deps/actions-39.yaml
+++ b/ci/deps/actions-39.yaml
@@ -15,7 +15,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-pypy-38.yaml b/ci/deps/actions-pypy-38.yaml
index c4f45f32a5f4c..e06b992acc191 100644
--- a/ci/deps/actions-pypy-38.yaml
+++ b/ci/deps/actions-pypy-38.yaml
@@ -16,6 +16,6 @@ dependencies:
- hypothesis>=5.5.3
# required
- - numpy<1.24
+ - numpy
- python-dateutil
- pytz
diff --git a/ci/deps/circle-38-arm64.yaml b/ci/deps/circle-38-arm64.yaml
index b65162c0c0f6e..263521fb74879 100644
--- a/ci/deps/circle-38-arm64.yaml
+++ b/ci/deps/circle-38-arm64.yaml
@@ -15,7 +15,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/environment.yml b/environment.yml
index a8951e056005c..20f839db9ad60 100644
--- a/environment.yml
+++ b/environment.yml
@@ -16,7 +16,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index 4a4f27f6c7906..dc49dc6adf378 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -94,6 +94,13 @@ def safe_import(mod_name: str, min_version: str | None = None):
mod = __import__(mod_name)
except ImportError:
return False
+ except SystemError:
+ # TODO: numba is incompatible with numpy 1.24+.
+ # Once that's fixed, this block should be removed.
+ if mod_name == "numba":
+ return False
+ else:
+ raise
if not min_version:
return mod
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 9c45bb2d6e766..95291e4ab5452 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -9,7 +9,7 @@ psutil
pytest-asyncio>=0.17
boto3
python-dateutil
-numpy<1.24
+numpy
pytz
beautifulsoup4
blosc
| Backport PR #50706: Revert "CI temporarily pin numpy" | https://api.github.com/repos/pandas-dev/pandas/pulls/50715 | 2023-01-12T18:56:16Z | 2023-01-13T16:45:57Z | 2023-01-13T16:45:56Z | 2023-01-13T16:45:57Z |
PERF: Fix reference leak in read_hdf | diff --git a/asv_bench/benchmarks/io/hdf.py b/asv_bench/benchmarks/io/hdf.py
index 12bc65f9e7bf5..e44a59114b30d 100644
--- a/asv_bench/benchmarks/io/hdf.py
+++ b/asv_bench/benchmarks/io/hdf.py
@@ -128,9 +128,17 @@ def setup(self, format):
self.df["object"] = tm.makeStringIndex(N)
self.df.to_hdf(self.fname, "df", format=format)
+ # Numeric df
+ self.df1 = self.df.copy()
+ self.df1 = self.df1.reset_index()
+ self.df1.to_hdf(self.fname, "df1", format=format)
+
def time_read_hdf(self, format):
read_hdf(self.fname, "df")
+ def peakmem_read_hdf(self, format):
+ read_hdf(self.fname, "df")
+
def time_write_hdf(self, format):
self.df.to_hdf(self.fname, "df", format=format)
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index 1c99ba0b8e412..2e1be0623441a 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -857,6 +857,7 @@ Performance improvements
- Performance improvement in :func:`to_datetime` when format is given or can be inferred (:issue:`50465`)
- Performance improvement in :func:`read_csv` when passing :func:`to_datetime` lambda-function to ``date_parser`` and inputs have mixed timezone offsetes (:issue:`35296`)
- Performance improvement in :meth:`.SeriesGroupBy.value_counts` with categorical dtype (:issue:`46202`)
+- Fixed a reference leak in :func:`read_hdf` (:issue:`37441`)
.. ---------------------------------------------------------------------------
.. _whatsnew_200.bug_fixes:
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 8c0d5c3da385c..eedcf46fd063e 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2057,7 +2057,9 @@ def convert(
# values is a recarray
if values.dtype.fields is not None:
- values = values[self.cname]
+ # Copy, otherwise values will be a view
+ # preventing the original recarry from being free'ed
+ values = values[self.cname].copy()
val_kind = _ensure_decoded(self.kind)
values = _maybe_convert(values, val_kind, encoding, errors)
diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py
index 6d92c15f1ea10..cb0c1ce35c7c7 100644
--- a/pandas/tests/io/pytables/test_read.py
+++ b/pandas/tests/io/pytables/test_read.py
@@ -214,6 +214,20 @@ def test_read_hdf_open_store(tmp_path, setup_path):
assert store.is_open
+def test_read_hdf_index_not_view(tmp_path, setup_path):
+ # GH 37441
+ # Ensure that the index of the DataFrame is not a view
+ # into the original recarray that pytables reads in
+ df = DataFrame(np.random.rand(4, 5), index=[0, 1, 2, 3], columns=list("ABCDE"))
+
+ path = tmp_path / setup_path
+ df.to_hdf(path, "df", mode="w", format="table")
+
+ df2 = read_hdf(path, "df")
+ assert df2.index._data.base is None
+ tm.assert_frame_equal(df, df2)
+
+
def test_read_hdf_iterator(tmp_path, setup_path):
df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE"))
df.index.name = "letters"
| - [ ] closes #37441 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
With my really hacky benchmark, I get,
```
before after ratio
[bb18847e] [b5ddc810]
<main> <fix-hdf-memusage>
- 6.6M 0 0.00 io.hdf.HDF.mem_read_hdf_index('table')
SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.
PERFORMANCE INCREASED.
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/50714 | 2023-01-12T18:44:41Z | 2023-01-16T19:21:07Z | 2023-01-16T19:21:07Z | 2023-03-14T12:16:08Z |
BUG: Fix style.background_gradient() for nullable dtype (ex: Int64) series with pd.NA values | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index 033f47f0c994d..d073c2b126227 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -1079,7 +1079,7 @@ ExtensionArray
Styler
^^^^^^
--
+- Fix :meth:`~pandas.io.formats.style.Styler.background_gradient` for nullable dtype :class:`Series` with ``NA`` values (:issue:`50712`)
-
Metadata
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 0d2aca8b78112..7f1775c53ce9e 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -3619,7 +3619,7 @@ def _background_gradient(
Color background in a range according to the data or a gradient map
"""
if gmap is None: # the data is used the gmap
- gmap = data.to_numpy(dtype=float)
+ gmap = data.to_numpy(dtype=float, na_value=np.nan)
else: # else validate gmap against the underlying data
gmap = _validate_apply_axis_arg(gmap, "gmap", float, data)
diff --git a/pandas/tests/io/formats/style/test_matplotlib.py b/pandas/tests/io/formats/style/test_matplotlib.py
index c19f27dc064d1..591fa7f72050e 100644
--- a/pandas/tests/io/formats/style/test_matplotlib.py
+++ b/pandas/tests/io/formats/style/test_matplotlib.py
@@ -260,6 +260,16 @@ def test_background_gradient_gmap_wrong_series(styler_blank):
styler_blank.background_gradient(gmap=gmap, axis=None)._compute()
+def test_background_gradient_nullable_dtypes():
+ # GH 50712
+ df1 = DataFrame([[1], [0], [np.nan]], dtype=float)
+ df2 = DataFrame([[1], [0], [None]], dtype="Int64")
+
+ ctx1 = df1.style.background_gradient()._compute().ctx
+ ctx2 = df2.style.background_gradient()._compute().ctx
+ assert ctx1 == ctx2
+
+
@pytest.mark.parametrize(
"cmap",
["PuBu", mpl.colormaps["PuBu"]],
| - [x] closes #50712
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50713 | 2023-01-12T18:31:37Z | 2023-01-16T17:46:12Z | 2023-01-16T17:46:12Z | 2023-01-16T17:46:19Z |
DOC: added installation instructions for nightly build | diff --git a/.github/ISSUE_TEMPLATE/bug_report.yaml b/.github/ISSUE_TEMPLATE/bug_report.yaml
index 36bc8dcf02bae..d9330e396ed12 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yaml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yaml
@@ -17,7 +17,9 @@ body:
[latest version](https://pandas.pydata.org/docs/whatsnew/index.html) of pandas.
required: true
- label: >
- I have confirmed this bug exists on the main branch of pandas.
+ I have confirmed this bug exists on the [main branch]
+ (https://pandas.pydata.org/docs/dev/getting_started/install.html#installing-the-development-version-of-pandas)
+ of pandas.
- type: textarea
id: example
attributes:
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index 70a27a84a7592..687f00a3dffd9 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -201,6 +201,22 @@ Installing from source
See the :ref:`contributing guide <contributing>` for complete instructions on building from the git source tree. Further, see :ref:`creating a development environment <contributing_environment>` if you wish to create a pandas development environment.
+Installing the development version of pandas
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Installing a nightly build is the quickest way to:
+
+* Try a new feature that will be shipped in the next release (that is, a feature from a pull-request that was recently merged to the main branch).
+* Check whether a bug you encountered has been fixed since the last release.
+
+You can install the nightly build of pandas using the scipy-wheels-nightly index from the PyPI registry of anaconda.org with the following command::
+
+ pip install --pre --extra-index https://pypi.anaconda.org/scipy-wheels-nightly/simple pandas
+
+Note that first uninstalling pandas might be required to be able to install nightly builds::
+
+ pip uninstall pandas -y
+
Running the test suite
----------------------
| - [x] closes #50703
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50707 | 2023-01-12T15:27:02Z | 2023-01-13T23:01:19Z | 2023-01-13T23:01:19Z | 2023-01-13T23:01:26Z |
Revert "CI temporarily pin numpy" | diff --git a/asv_bench/asv.conf.json b/asv_bench/asv.conf.json
index 6e548bf9d9e8a..16f8f28b66d31 100644
--- a/asv_bench/asv.conf.json
+++ b/asv_bench/asv.conf.json
@@ -41,7 +41,7 @@
// pip (with all the conda available packages installed first,
// followed by the pip installed packages).
"matrix": {
- "numpy": ["1.23.5"], // https://github.com/pandas-dev/pandas/pull/50356
+ "numpy": [],
"Cython": ["0.29.32"],
"matplotlib": [],
"sqlalchemy": [],
diff --git a/ci/deps/actions-310-numpydev.yaml b/ci/deps/actions-310-numpydev.yaml
index 863c231b18c4f..44acae877bdf8 100644
--- a/ci/deps/actions-310-numpydev.yaml
+++ b/ci/deps/actions-310-numpydev.yaml
@@ -22,5 +22,5 @@ dependencies:
- "cython"
- "--extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple"
- "--pre"
- - "numpy<1.24"
+ - "numpy"
- "scipy"
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml
index 79457cd503876..d957f3a516e2f 100644
--- a/ci/deps/actions-310.yaml
+++ b/ci/deps/actions-310.yaml
@@ -18,7 +18,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-38-downstream_compat.yaml
index 6955baa282274..37036cc3f3c89 100644
--- a/ci/deps/actions-38-downstream_compat.yaml
+++ b/ci/deps/actions-38-downstream_compat.yaml
@@ -19,7 +19,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml
index 004ef93606457..9ac0fa6c764df 100644
--- a/ci/deps/actions-38.yaml
+++ b/ci/deps/actions-38.yaml
@@ -18,7 +18,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml
index ec7ffebde964f..b91c5298d4a5d 100644
--- a/ci/deps/actions-39.yaml
+++ b/ci/deps/actions-39.yaml
@@ -18,7 +18,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/ci/deps/actions-pypy-38.yaml b/ci/deps/actions-pypy-38.yaml
index 054129c4198a1..17d39a4c53ac3 100644
--- a/ci/deps/actions-pypy-38.yaml
+++ b/ci/deps/actions-pypy-38.yaml
@@ -19,6 +19,6 @@ dependencies:
- hypothesis>=5.5.3
# required
- - numpy<1.24
+ - numpy
- python-dateutil
- pytz
diff --git a/ci/deps/circle-38-arm64.yaml b/ci/deps/circle-38-arm64.yaml
index b4171710564bf..9af198b37d648 100644
--- a/ci/deps/circle-38-arm64.yaml
+++ b/ci/deps/circle-38-arm64.yaml
@@ -18,7 +18,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/environment.yml b/environment.yml
index 9e4c6db82b2ce..5be4cd89f1e86 100644
--- a/environment.yml
+++ b/environment.yml
@@ -20,7 +20,7 @@ dependencies:
# required dependencies
- python-dateutil
- - numpy<1.24
+ - numpy
- pytz
# optional dependencies
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index 33830e96342f3..59d5d6649c2a5 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -95,6 +95,13 @@ def safe_import(mod_name: str, min_version: str | None = None):
mod = __import__(mod_name)
except ImportError:
return False
+ except SystemError:
+ # TODO: numba is incompatible with numpy 1.24+.
+ # Once that's fixed, this block should be removed.
+ if mod_name == "numba":
+ return False
+ else:
+ raise
if not min_version:
return mod
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 1a2e39bb47786..09d32872dad0d 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -11,7 +11,7 @@ psutil
pytest-asyncio>=0.17
coverage
python-dateutil
-numpy<1.24
+numpy
pytz
beautifulsoup4
blosc
| Reverts pandas-dev/pandas#50356 | https://api.github.com/repos/pandas-dev/pandas/pulls/50706 | 2023-01-12T14:36:28Z | 2023-01-12T18:56:04Z | 2023-01-12T18:56:04Z | 2023-01-12T18:59:04Z |
Backport PR #50698 on branch 1.5.x (CI capture error in numpy dev, fix python-dev build) | diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index ef16a4fb3fa33..c07a101cc433b 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -73,7 +73,7 @@ jobs:
run: |
python --version
python -m pip install --upgrade pip setuptools wheel
- python -m pip install -i https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
+ python -m pip install --extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
python -m pip install git+https://github.com/nedbat/coveragepy.git
python -m pip install python-dateutil pytz cython hypothesis==6.52.1 pytest>=6.2.5 pytest-xdist pytest-cov pytest-asyncio>=0.17
python -m pip list
diff --git a/pandas/tests/frame/test_unary.py b/pandas/tests/frame/test_unary.py
index a69ca0fef7f8b..9caadd0998a26 100644
--- a/pandas/tests/frame/test_unary.py
+++ b/pandas/tests/frame/test_unary.py
@@ -3,6 +3,8 @@
import numpy as np
import pytest
+from pandas.compat import is_numpy_dev
+
import pandas as pd
import pandas._testing as tm
@@ -98,11 +100,6 @@ def test_pos_numeric(self, df):
@pytest.mark.parametrize(
"df",
[
- # numpy changing behavior in the future
- pytest.param(
- pd.DataFrame({"a": ["a", "b"]}),
- marks=[pytest.mark.filterwarnings("ignore")],
- ),
pd.DataFrame({"a": np.array([-1, 2], dtype=object)}),
pd.DataFrame({"a": [Decimal("-1.0"), Decimal("2.0")]}),
],
@@ -112,6 +109,25 @@ def test_pos_object(self, df):
tm.assert_frame_equal(+df, df)
tm.assert_series_equal(+df["a"], df["a"])
+ @pytest.mark.parametrize(
+ "df",
+ [
+ pytest.param(
+ pd.DataFrame({"a": ["a", "b"]}),
+ marks=[pytest.mark.filterwarnings("ignore")],
+ ),
+ ],
+ )
+ def test_pos_object_raises(self, df):
+ # GH#21380
+ if is_numpy_dev:
+ with pytest.raises(
+ TypeError, match=r"^bad operand type for unary \+: \'str\'$"
+ ):
+ tm.assert_frame_equal(+df, df)
+ else:
+ tm.assert_series_equal(+df["a"], df["a"])
+
@pytest.mark.parametrize(
"df", [pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])})]
)
| Backport PR #50698: CI capture error in numpy dev, fix python-dev build | https://api.github.com/repos/pandas-dev/pandas/pulls/50705 | 2023-01-12T14:25:10Z | 2023-01-12T16:31:09Z | 2023-01-12T16:31:09Z | 2023-01-12T16:35:29Z |
Backport PR #49386 on branch 1.5.x (DOC: add name parameter to the IntervalIndex for #48911) | diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 8f01dfaf867e7..ea5c6d52f29ba 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -383,7 +383,8 @@ def _from_factorized(
Left and right bounds for each interval.
closed : {'left', 'right', 'both', 'neither'}, default 'right'
Whether the intervals are closed on the left-side, right-side, both
- or neither.
+ or neither.\
+ %(name)s
copy : bool, default False
Copy the data.
dtype : dtype or None, default None
@@ -408,6 +409,7 @@ def _from_factorized(
_interval_shared_docs["from_breaks"]
% {
"klass": "IntervalArray",
+ "name": "",
"examples": textwrap.dedent(
"""\
Examples
@@ -443,7 +445,8 @@ def from_breaks(
Right bounds for each interval.
closed : {'left', 'right', 'both', 'neither'}, default 'right'
Whether the intervals are closed on the left-side, right-side, both
- or neither.
+ or neither.\
+ %(name)s
copy : bool, default False
Copy the data.
dtype : dtype, optional
@@ -485,6 +488,7 @@ def from_breaks(
_interval_shared_docs["from_arrays"]
% {
"klass": "IntervalArray",
+ "name": "",
"examples": textwrap.dedent(
"""\
>>> pd.arrays.IntervalArray.from_arrays([0, 1, 2], [1, 2, 3])
@@ -520,7 +524,8 @@ def from_arrays(
Array of tuples.
closed : {'left', 'right', 'both', 'neither'}, default 'right'
Whether the intervals are closed on the left-side, right-side, both
- or neither.
+ or neither.\
+ %(name)s
copy : bool, default False
By-default copy the data, this is compat only and ignored.
dtype : dtype or None, default None
@@ -547,6 +552,7 @@ def from_arrays(
_interval_shared_docs["from_tuples"]
% {
"klass": "IntervalArray",
+ "name": "",
"examples": textwrap.dedent(
"""\
Examples
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 92331c9777abb..b18db8b6cb9b9 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -236,6 +236,11 @@ def __new__(
_interval_shared_docs["from_breaks"]
% {
"klass": "IntervalIndex",
+ "name": textwrap.dedent(
+ """
+ name : str, optional
+ Name of the resulting IntervalIndex."""
+ ),
"examples": textwrap.dedent(
"""\
Examples
@@ -266,6 +271,11 @@ def from_breaks(
_interval_shared_docs["from_arrays"]
% {
"klass": "IntervalIndex",
+ "name": textwrap.dedent(
+ """
+ name : str, optional
+ Name of the resulting IntervalIndex."""
+ ),
"examples": textwrap.dedent(
"""\
Examples
@@ -297,6 +307,11 @@ def from_arrays(
_interval_shared_docs["from_tuples"]
% {
"klass": "IntervalIndex",
+ "name": textwrap.dedent(
+ """
+ name : str, optional
+ Name of the resulting IntervalIndex."""
+ ),
"examples": textwrap.dedent(
"""\
Examples
| …#48911
Backport PR #49386
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50700 | 2023-01-12T12:31:04Z | 2023-01-12T14:10:15Z | 2023-01-12T14:10:15Z | 2023-01-12T14:10:16Z |
CI capture error in numpy dev, fix python-dev build | diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index 220c1e464742e..9076b66683a29 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -73,7 +73,7 @@ jobs:
run: |
python --version
python -m pip install --upgrade pip setuptools wheel
- python -m pip install -i https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
+ python -m pip install --extra-index-url https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
python -m pip install git+https://github.com/nedbat/coveragepy.git
python -m pip install versioneer[toml]
python -m pip install python-dateutil pytz cython hypothesis==6.52.1 pytest>=6.2.5 pytest-xdist pytest-cov pytest-asyncio>=0.17
diff --git a/pandas/tests/frame/test_unary.py b/pandas/tests/frame/test_unary.py
index a69ca0fef7f8b..9caadd0998a26 100644
--- a/pandas/tests/frame/test_unary.py
+++ b/pandas/tests/frame/test_unary.py
@@ -3,6 +3,8 @@
import numpy as np
import pytest
+from pandas.compat import is_numpy_dev
+
import pandas as pd
import pandas._testing as tm
@@ -98,11 +100,6 @@ def test_pos_numeric(self, df):
@pytest.mark.parametrize(
"df",
[
- # numpy changing behavior in the future
- pytest.param(
- pd.DataFrame({"a": ["a", "b"]}),
- marks=[pytest.mark.filterwarnings("ignore")],
- ),
pd.DataFrame({"a": np.array([-1, 2], dtype=object)}),
pd.DataFrame({"a": [Decimal("-1.0"), Decimal("2.0")]}),
],
@@ -112,6 +109,25 @@ def test_pos_object(self, df):
tm.assert_frame_equal(+df, df)
tm.assert_series_equal(+df["a"], df["a"])
+ @pytest.mark.parametrize(
+ "df",
+ [
+ pytest.param(
+ pd.DataFrame({"a": ["a", "b"]}),
+ marks=[pytest.mark.filterwarnings("ignore")],
+ ),
+ ],
+ )
+ def test_pos_object_raises(self, df):
+ # GH#21380
+ if is_numpy_dev:
+ with pytest.raises(
+ TypeError, match=r"^bad operand type for unary \+: \'str\'$"
+ ):
+ tm.assert_frame_equal(+df, df)
+ else:
+ tm.assert_series_equal(+df["a"], df["a"])
+
@pytest.mark.parametrize(
"df", [pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])})]
)
| - [ ] closes #50695 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
the macos job fails during the installation phase: https://github.com/pandas-dev/pandas/issues/50699
| https://api.github.com/repos/pandas-dev/pandas/pulls/50698 | 2023-01-12T11:04:54Z | 2023-01-12T14:24:29Z | 2023-01-12T14:24:29Z | 2023-01-12T16:34:56Z |
add multi index with categories test | diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py
index d0345861d6778..08ccf696d73f3 100644
--- a/pandas/tests/indexes/multi/test_setops.py
+++ b/pandas/tests/indexes/multi/test_setops.py
@@ -692,6 +692,43 @@ def test_intersection_lexsort_depth(levels1, levels2, codes1, codes2, names):
assert mi_int._lexsort_depth == 2
+@pytest.mark.parametrize(
+ "a",
+ [pd.Categorical(["a", "b"], categories=["a", "b"]), ["a", "b"]],
+)
+@pytest.mark.parametrize(
+ "b",
+ [
+ pd.Categorical(["a", "b"], categories=["b", "a"], ordered=True),
+ pd.Categorical(["a", "b"], categories=["b", "a"]),
+ ],
+)
+def test_intersection_with_non_lex_sorted_categories(a, b):
+ # GH#49974
+ other = ["1", "2"]
+
+ df1 = DataFrame({"x": a, "y": other})
+ df2 = DataFrame({"x": b, "y": other})
+
+ expected = MultiIndex.from_arrays([a, other], names=["x", "y"])
+
+ res1 = MultiIndex.from_frame(df1).intersection(
+ MultiIndex.from_frame(df2.sort_values(["x", "y"]))
+ )
+ res2 = MultiIndex.from_frame(df1).intersection(MultiIndex.from_frame(df2))
+ res3 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection(
+ MultiIndex.from_frame(df2)
+ )
+ res4 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection(
+ MultiIndex.from_frame(df2.sort_values(["x", "y"]))
+ )
+
+ tm.assert_index_equal(res1, expected)
+ tm.assert_index_equal(res2, expected)
+ tm.assert_index_equal(res3, expected)
+ tm.assert_index_equal(res4, expected)
+
+
@pytest.mark.parametrize("val", [pd.NA, 100])
def test_intersection_keep_ea_dtypes(val, any_numeric_ea_dtype):
# GH#48604
| Reopening, because https://github.com/pandas-dev/pandas/pull/49975 was closed
closes #49337 | https://api.github.com/repos/pandas-dev/pandas/pulls/50697 | 2023-01-12T09:43:05Z | 2023-01-12T18:58:31Z | 2023-01-12T18:58:31Z | 2023-01-12T18:58:40Z |
CI: Add regular 3.11 pipeline | diff --git a/.github/workflows/macos-windows.yml b/.github/workflows/macos-windows.yml
index d762e20db196a..ac5fd4aa7d4a4 100644
--- a/.github/workflows/macos-windows.yml
+++ b/.github/workflows/macos-windows.yml
@@ -31,7 +31,7 @@ jobs:
strategy:
matrix:
os: [macos-latest, windows-latest]
- env_file: [actions-38.yaml, actions-39.yaml, actions-310.yaml]
+ env_file: [actions-38.yaml, actions-39.yaml, actions-310.yaml, actions-311.yaml]
fail-fast: false
runs-on: ${{ matrix.os }}
name: ${{ format('{0} {1}', matrix.os, matrix.env_file) }}
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index 2ece92dc50b87..4e0a1f98d1c59 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -23,12 +23,14 @@ name: Python Dev
on:
push:
branches:
- - main
- - 1.5.x
+# - main
+# - 1.5.x
+ - None
pull_request:
branches:
- - main
- - 1.5.x
+# - main
+# - 1.5.x
+ - None
paths-ignore:
- "doc/**"
diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml
index 9c93725ea15ec..f7bd5980439e3 100644
--- a/.github/workflows/ubuntu.yml
+++ b/.github/workflows/ubuntu.yml
@@ -27,7 +27,7 @@ jobs:
timeout-minutes: 180
strategy:
matrix:
- env_file: [actions-38.yaml, actions-39.yaml, actions-310.yaml]
+ env_file: [actions-38.yaml, actions-39.yaml, actions-310.yaml, actions-311.yaml]
pattern: ["not single_cpu", "single_cpu"]
pyarrow_version: ["7", "8", "9", "10"]
include:
@@ -92,6 +92,12 @@ jobs:
pyarrow_version: "8"
- env_file: actions-39.yaml
pyarrow_version: "9"
+ - env_file: actions-311.yaml
+ pyarrow_version: "7"
+ - env_file: actions-311.yaml
+ pyarrow_version: "8"
+ - env_file: actions-311.yaml
+ pyarrow_version: "9"
fail-fast: false
name: ${{ matrix.name || format('{0} pyarrow={1} {2}', matrix.env_file, matrix.pyarrow_version, matrix.pattern) }}
env:
diff --git a/ci/deps/actions-311.yaml b/ci/deps/actions-311.yaml
new file mode 100644
index 0000000000000..8e15c7b4740c5
--- /dev/null
+++ b/ci/deps/actions-311.yaml
@@ -0,0 +1,57 @@
+name: pandas-dev
+channels:
+ - conda-forge
+dependencies:
+ - python=3.11
+
+ # build dependencies
+ - versioneer[toml]
+ - cython>=0.29.32
+
+ # test dependencies
+ - pytest>=7.0
+ - pytest-cov
+ - pytest-xdist>=2.2.0
+ - psutil
+ - pytest-asyncio>=0.17
+ - boto3
+
+ # required dependencies
+ - python-dateutil
+ - numpy<1.24.0
+ - pytz
+
+ # optional dependencies
+ - beautifulsoup4
+ - blosc
+ - bottleneck
+ - brotlipy
+ - fastparquet
+ - fsspec
+ - html5lib
+ - hypothesis
+ - gcsfs
+ - jinja2
+ - lxml
+ - matplotlib>=3.6.1
+ # - numba not compatible with 3.11
+ - numexpr
+ - openpyxl
+ - odfpy
+ - pandas-gbq
+ - psycopg2
+ - pymysql
+ # - pytables>=3.8.0 # first version that supports 3.11
+ - pyarrow
+ - pyreadstat
+ - python-snappy
+ - pyxlsb
+ - s3fs>=2021.08.0
+ - scipy
+ - sqlalchemy<1.4.46
+ - tabulate
+ - tzdata>=2022a
+ - xarray
+ - xlrd
+ - xlsxwriter
+ - zstandard
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 523463b9593a2..cc16c4231a2ed 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -26,6 +26,7 @@
import pytest
from pandas.compat import (
+ PY311,
is_ci_environment,
is_platform_windows,
pa_version_under6p0,
@@ -49,7 +50,7 @@
)
from pandas.tests.extension import base
-pa = pytest.importorskip("pyarrow", minversion="1.0.1")
+pa = pytest.importorskip("pyarrow", minversion="6.0.0")
from pandas.core.arrays.arrow.array import ArrowExtensionArray
@@ -287,7 +288,7 @@ def test_from_sequence_pa_array_notimplemented(self, request):
def test_from_sequence_of_strings_pa_array(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
- if pa.types.is_time64(pa_dtype) and pa_dtype.equals("time64[ns]"):
+ if pa.types.is_time64(pa_dtype) and pa_dtype.equals("time64[ns]") and not PY311:
request.node.add_marker(
pytest.mark.xfail(
reason="Nanosecond time parsing not supported.",
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50696 | 2023-01-12T09:39:03Z | 2023-01-16T18:30:01Z | 2023-01-16T18:30:01Z | 2023-02-08T17:43:18Z |
Backport PR on Branch 1.5.x (REV: revert deprecation of Series.__getitem__ slicing with IntegerIndex) | diff --git a/doc/source/whatsnew/v1.5.3.rst b/doc/source/whatsnew/v1.5.3.rst
index 51e36359946e7..3b803af359860 100644
--- a/doc/source/whatsnew/v1.5.3.rst
+++ b/doc/source/whatsnew/v1.5.3.rst
@@ -45,7 +45,7 @@ Other
you may see a ``sqlalchemy.exc.RemovedIn20Warning``. These warnings can be safely ignored for the SQLAlchemy 1.4.x releases
as pandas works toward compatibility with SQLAlchemy 2.0.
--
+- Reverted deprecation (:issue:`45324`) of behavior of :meth:`Series.__getitem__` and :meth:`Series.__setitem__` slicing with an integer :class:`Index`; this will remain positional (:issue:`49612`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 677e1dc1a559a..447ba8d70c73e 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -123,7 +123,6 @@
ABCDatetimeIndex,
ABCMultiIndex,
ABCPeriodIndex,
- ABCRangeIndex,
ABCSeries,
ABCTimedeltaIndex,
)
@@ -4213,7 +4212,7 @@ def _validate_positional_slice(self, key: slice) -> None:
self._validate_indexer("positional", key.stop, "iloc")
self._validate_indexer("positional", key.step, "iloc")
- def _convert_slice_indexer(self, key: slice, kind: str_t, is_frame: bool = False):
+ def _convert_slice_indexer(self, key: slice, kind: str_t):
"""
Convert a slice indexer.
@@ -4224,9 +4223,6 @@ def _convert_slice_indexer(self, key: slice, kind: str_t, is_frame: bool = False
----------
key : label of the slice bound
kind : {'loc', 'getitem'}
- is_frame : bool, default False
- Whether this is a slice called on DataFrame.__getitem__
- as opposed to Series.__getitem__
"""
assert kind in ["loc", "getitem"], kind
@@ -4248,46 +4244,7 @@ def is_int(v):
is_positional = is_index_slice and ints_are_positional
if kind == "getitem":
- """
- called from the getitem slicers, validate that we are in fact
- integers
- """
- if self.is_integer():
- if is_frame:
- # unambiguously positional, no deprecation
- pass
- elif start is None and stop is None:
- # label-based vs positional is irrelevant
- pass
- elif isinstance(self, ABCRangeIndex) and self._range == range(
- len(self)
- ):
- # In this case there is no difference between label-based
- # and positional, so nothing will change.
- pass
- elif (
- self.dtype.kind in ["i", "u"]
- and self._is_strictly_monotonic_increasing
- and len(self) > 0
- and self[0] == 0
- and self[-1] == len(self) - 1
- ):
- # We are range-like, e.g. created with Index(np.arange(N))
- pass
- elif not is_index_slice:
- # we're going to raise, so don't bother warning, e.g.
- # test_integer_positional_indexing
- pass
- else:
- warnings.warn(
- "The behavior of `series[i:j]` with an integer-dtype index "
- "is deprecated. In a future version, this will be treated "
- "as *label-based* indexing, consistent with e.g. `series[i]` "
- "lookups. To retain the old behavior, use `series.iloc[i:j]`. "
- "To get the future behavior, use `series.loc[i:j]`.",
- FutureWarning,
- stacklevel=find_stack_level(),
- )
+ # called from the getitem slicers, validate that we are in fact integers
if self.is_integer() or is_index_slice:
# Note: these checks are redundant if we know is_index_slice
self._validate_indexer("slice", key.start, "getitem")
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index b18db8b6cb9b9..b993af5621923 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -779,7 +779,7 @@ def _index_as_unique(self) -> bool:
"cannot handle overlapping indices; use IntervalIndex.get_indexer_non_unique"
)
- def _convert_slice_indexer(self, key: slice, kind: str, is_frame: bool = False):
+ def _convert_slice_indexer(self, key: slice, kind: str):
if not (key.step is None or key.step == 1):
# GH#31658 if label-based, we require step == 1,
# if positional, we disallow float start/stop
@@ -791,7 +791,7 @@ def _convert_slice_indexer(self, key: slice, kind: str, is_frame: bool = False):
# i.e. this cannot be interpreted as a positional slice
raise ValueError(msg)
- return super()._convert_slice_indexer(key, kind, is_frame=is_frame)
+ return super()._convert_slice_indexer(key, kind)
@cache_readonly
def _should_fallback_to_positional(self) -> bool:
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py
index a597bea0eb724..fe11a02eccb3c 100644
--- a/pandas/core/indexes/numeric.py
+++ b/pandas/core/indexes/numeric.py
@@ -219,7 +219,7 @@ def _should_fallback_to_positional(self) -> bool:
return False
@doc(Index._convert_slice_indexer)
- def _convert_slice_indexer(self, key: slice, kind: str, is_frame: bool = False):
+ def _convert_slice_indexer(self, key: slice, kind: str):
# TODO(2.0): once #45324 deprecation is enforced we should be able
# to simplify this.
if is_float_dtype(self.dtype):
@@ -231,7 +231,7 @@ def _convert_slice_indexer(self, key: slice, kind: str, is_frame: bool = False):
# translate to locations
return self.slice_indexer(key.start, key.stop, key.step)
- return super()._convert_slice_indexer(key, kind=kind, is_frame=is_frame)
+ return super()._convert_slice_indexer(key, kind=kind)
@doc(Index._maybe_cast_slice_bound)
def _maybe_cast_slice_bound(self, label, side: str, kind=lib.no_default):
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 913aa2e5b0e18..198903f5fceff 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -2491,7 +2491,7 @@ def convert_to_index_sliceable(obj: DataFrame, key):
"""
idx = obj.index
if isinstance(key, slice):
- return idx._convert_slice_indexer(key, kind="getitem", is_frame=True)
+ return idx._convert_slice_indexer(key, kind="getitem")
elif isinstance(key, str):
diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py
index e966d4602a02c..cf51d9d693155 100644
--- a/pandas/tests/extension/base/getitem.py
+++ b/pandas/tests/extension/base/getitem.py
@@ -313,8 +313,7 @@ def test_get(self, data):
expected = s.iloc[[2, 3]]
self.assert_series_equal(result, expected)
- with tm.assert_produces_warning(FutureWarning, match="label-based"):
- result = s.get(slice(2))
+ result = s.get(slice(2))
expected = s.iloc[[0, 1]]
self.assert_series_equal(result, expected)
diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py
index 186cba62c138f..afc2def7ba8a1 100644
--- a/pandas/tests/indexing/test_floats.py
+++ b/pandas/tests/indexing/test_floats.py
@@ -340,8 +340,7 @@ def test_integer_positional_indexing(self, idx):
"""
s = Series(range(2, 6), index=range(2, 6))
- with tm.assert_produces_warning(FutureWarning, match="label-based"):
- result = s[2:4]
+ result = s[2:4]
expected = s.iloc[2:4]
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/indexing/test_get.py b/pandas/tests/series/indexing/test_get.py
index 1a54796dbeec3..e8034bd4f7160 100644
--- a/pandas/tests/series/indexing/test_get.py
+++ b/pandas/tests/series/indexing/test_get.py
@@ -167,8 +167,7 @@ def test_get_with_ea(arr):
expected = ser.iloc[[2, 3]]
tm.assert_series_equal(result, expected)
- with tm.assert_produces_warning(FutureWarning, match="label-based"):
- result = ser.get(slice(2))
+ result = ser.get(slice(2))
expected = ser.iloc[[0, 1]]
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py
index cc67dd9caeea9..acdcc03cee92c 100644
--- a/pandas/tests/series/indexing/test_getitem.py
+++ b/pandas/tests/series/indexing/test_getitem.py
@@ -338,8 +338,7 @@ def test_getitem_slice_bug(self):
def test_getitem_slice_integers(self):
ser = Series(np.random.randn(8), index=[2, 4, 6, 8, 10, 12, 14, 16])
- with tm.assert_produces_warning(FutureWarning, match="label-based"):
- result = ser[:4]
+ result = ser[:4]
expected = Series(ser.values[:4], index=[2, 4, 6, 8])
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index 9ab3b6ead017f..500ff2e90adb1 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -220,15 +220,9 @@ def test_setitem_slice(self):
def test_setitem_slice_integers(self):
ser = Series(np.random.randn(8), index=[2, 4, 6, 8, 10, 12, 14, 16])
- msg = r"In a future version, this will be treated as \*label-based\* indexing"
- with tm.assert_produces_warning(FutureWarning, match=msg):
- ser[:4] = 0
- with tm.assert_produces_warning(
- FutureWarning, match=msg, check_stacklevel=False
- ):
- assert (ser[:4] == 0).all()
- with tm.assert_produces_warning(FutureWarning, match=msg):
- assert not (ser[4:] == 0).any()
+ ser[:4] = 0
+ assert (ser[:4] == 0).all()
+ assert not (ser[4:] == 0).any()
def test_setitem_slicestep(self):
# caught this bug when writing tests
| #50283 | https://api.github.com/repos/pandas-dev/pandas/pulls/50694 | 2023-01-12T08:27:12Z | 2023-01-14T18:37:41Z | 2023-01-14T18:37:41Z | 2023-01-14T18:37:44Z |
Backport PR on Branch 1.5.x (DOC: Add note in 1.5.3 about SQLAlchemy warnings) | diff --git a/doc/source/whatsnew/v1.5.3.rst b/doc/source/whatsnew/v1.5.3.rst
index a0c38f1f81538..b2039abe9f715 100644
--- a/doc/source/whatsnew/v1.5.3.rst
+++ b/doc/source/whatsnew/v1.5.3.rst
@@ -36,6 +36,13 @@ Bug fixes
Other
~~~~~
+
+.. note::
+
+ If you are using :meth:`DataFrame.to_sql`, :func:`read_sql`, :func:`read_sql_table`, or :func:`read_sql_query` with SQLAlchemy 1.4.46 or greater,
+ you may see a ``sqlalchemy.exc.RemovedIn20Warning``. These warnings can be safely ignored for the SQLAlchemy 1.4.x releases
+ as pandas works toward compatibility with SQLAlchemy 2.0.
+
-
-
| #50680
| https://api.github.com/repos/pandas-dev/pandas/pulls/50693 | 2023-01-12T08:22:01Z | 2023-01-12T12:34:54Z | 2023-01-12T12:34:54Z | 2023-01-21T01:33:31Z |
TST: CoW with df.isetitem() | diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py
index 2bc4202cce5f5..111073795325b 100644
--- a/pandas/tests/copy_view/test_methods.py
+++ b/pandas/tests/copy_view/test_methods.py
@@ -759,3 +759,25 @@ def test_squeeze(using_copy_on_write):
# Without CoW the original will be modified
assert np.shares_memory(series.values, get_array(df, "a"))
assert df.loc[0, "a"] == 0
+
+
+def test_isetitem(using_copy_on_write):
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]})
+ df_orig = df.copy()
+ df2 = df.copy(deep=None) # Trigger a CoW
+ df2.isetitem(1, np.array([-1, -2, -3])) # This is inplace
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+ assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+ else:
+ assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+ assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
+
+ df2.loc[0, "a"] = 0
+ tm.assert_frame_equal(df, df_orig) # Original is unchanged
+
+ if using_copy_on_write:
+ assert np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
+ else:
+ assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c"))
| xref https://github.com/pandas-dev/pandas/issues/49473
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50692 | 2023-01-12T05:35:19Z | 2023-01-12T21:28:58Z | 2023-01-12T21:28:58Z | 2023-03-14T12:16:09Z |
TST: incorrect pyarrow xfails | diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 78c49ae066288..2dc635f18ffae 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -351,20 +351,15 @@ def check_accumulate(self, s, op_name, skipna):
self.assert_series_equal(result, expected, check_dtype=False)
@pytest.mark.parametrize("skipna", [True, False])
- def test_accumulate_series_raises(
- self, data, all_numeric_accumulations, skipna, request
- ):
+ def test_accumulate_series_raises(self, data, all_numeric_accumulations, skipna):
pa_type = data.dtype.pyarrow_dtype
if (
(pa.types.is_integer(pa_type) or pa.types.is_floating(pa_type))
and all_numeric_accumulations == "cumsum"
and not pa_version_under9p0
):
- request.node.add_marker(
- pytest.mark.xfail(
- reason=f"{all_numeric_accumulations} implemented for {pa_type}"
- )
- )
+ pytest.skip("These work, are tested by test_accumulate_series.")
+
op_name = all_numeric_accumulations
ser = pd.Series(data)
@@ -374,6 +369,26 @@ def test_accumulate_series_raises(
@pytest.mark.parametrize("skipna", [True, False])
def test_accumulate_series(self, data, all_numeric_accumulations, skipna, request):
pa_type = data.dtype.pyarrow_dtype
+ op_name = all_numeric_accumulations
+ ser = pd.Series(data)
+
+ do_skip = False
+ if pa.types.is_string(pa_type) or pa.types.is_binary(pa_type):
+ if op_name in ["cumsum", "cumprod"]:
+ do_skip = True
+ elif pa.types.is_temporal(pa_type) and not pa.types.is_duration(pa_type):
+ if op_name in ["cumsum", "cumprod"]:
+ do_skip = True
+ elif pa.types.is_duration(pa_type):
+ if op_name == "cumprod":
+ do_skip = True
+
+ if do_skip:
+ pytest.skip(
+ "These should *not* work, we test in test_accumulate_series_raises "
+ "that these correctly raise."
+ )
+
if all_numeric_accumulations != "cumsum" or pa_version_under9p0:
request.node.add_marker(
pytest.mark.xfail(
@@ -381,14 +396,16 @@ def test_accumulate_series(self, data, all_numeric_accumulations, skipna, reques
raises=NotImplementedError,
)
)
- elif not (pa.types.is_integer(pa_type) or pa.types.is_floating(pa_type)):
+ elif all_numeric_accumulations == "cumsum" and (
+ pa.types.is_duration(pa_type) or pa.types.is_boolean(pa_type)
+ ):
request.node.add_marker(
pytest.mark.xfail(
- reason=f"{all_numeric_accumulations} not implemented for {pa_type}"
+ reason=f"{all_numeric_accumulations} not implemented for {pa_type}",
+ raises=NotImplementedError,
)
)
- op_name = all_numeric_accumulations
- ser = pd.Series(data)
+
self.check_accumulate(ser, op_name, skipna)
@@ -415,6 +432,47 @@ def check_reduce(self, ser, op_name, skipna):
@pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series(self, data, all_numeric_reductions, skipna, request):
pa_dtype = data.dtype.pyarrow_dtype
+ opname = all_numeric_reductions
+
+ ser = pd.Series(data)
+
+ should_work = True
+ if pa.types.is_temporal(pa_dtype) and opname in [
+ "sum",
+ "var",
+ "skew",
+ "kurt",
+ "prod",
+ ]:
+ if pa.types.is_duration(pa_dtype) and opname in ["sum"]:
+ # summing timedeltas is one case that *is* well-defined
+ pass
+ else:
+ should_work = False
+ elif (
+ pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
+ ) and opname in [
+ "sum",
+ "mean",
+ "median",
+ "prod",
+ "std",
+ "sem",
+ "var",
+ "skew",
+ "kurt",
+ ]:
+ should_work = False
+
+ if not should_work:
+ # matching the non-pyarrow versions, these operations *should* not
+ # work for these dtypes
+ msg = f"does not support reduction '{opname}'"
+ with pytest.raises(TypeError, match=msg):
+ getattr(ser, opname)(skipna=skipna)
+
+ return
+
xfail_mark = pytest.mark.xfail(
raises=TypeError,
reason=(
@@ -446,24 +504,16 @@ def test_reduce_series(self, data, all_numeric_reductions, skipna, request):
),
)
)
- elif (
- not (
- pa.types.is_integer(pa_dtype)
- or pa.types.is_floating(pa_dtype)
- or pa.types.is_boolean(pa_dtype)
- )
- and not (
- all_numeric_reductions in {"min", "max"}
- and (
- (
- pa.types.is_temporal(pa_dtype)
- and not pa.types.is_duration(pa_dtype)
- )
- or pa.types.is_string(pa_dtype)
- or pa.types.is_binary(pa_dtype)
- )
- )
- and not all_numeric_reductions == "count"
+
+ elif all_numeric_reductions in [
+ "mean",
+ "median",
+ "std",
+ "sem",
+ ] and pa.types.is_temporal(pa_dtype):
+ request.node.add_marker(xfail_mark)
+ elif all_numeric_reductions in ["sum", "min", "max"] and pa.types.is_duration(
+ pa_dtype
):
request.node.add_marker(xfail_mark)
elif pa.types.is_boolean(pa_dtype) and all_numeric_reductions in {
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50691 | 2023-01-12T04:02:43Z | 2023-01-17T19:41:58Z | 2023-01-17T19:41:58Z | 2023-01-17T20:31:27Z |
BUG: ArrowDtype.construct_from_string round-trip | diff --git a/pandas/core/arrays/arrow/dtype.py b/pandas/core/arrays/arrow/dtype.py
index 331e66698cc35..fdb9ac877831b 100644
--- a/pandas/core/arrays/arrow/dtype.py
+++ b/pandas/core/arrays/arrow/dtype.py
@@ -203,6 +203,13 @@ def construct_from_string(cls, string: str) -> ArrowDtype:
except ValueError as err:
has_parameters = re.search(r"\[.*\]", base_type)
if has_parameters:
+ # Fallback to try common temporal types
+ try:
+ return cls._parse_temporal_dtype_string(base_type)
+ except (NotImplementedError, ValueError):
+ # Fall through to raise with nice exception message below
+ pass
+
raise NotImplementedError(
"Passing pyarrow type specific parameters "
f"({has_parameters.group()}) in the string is not supported. "
@@ -212,6 +219,35 @@ def construct_from_string(cls, string: str) -> ArrowDtype:
raise TypeError(f"'{base_type}' is not a valid pyarrow data type.") from err
return cls(pa_dtype)
+ # TODO(arrow#33642): This can be removed once supported by pyarrow
+ @classmethod
+ def _parse_temporal_dtype_string(cls, string: str) -> ArrowDtype:
+ """
+ Construct a temporal ArrowDtype from string.
+ """
+ # we assume
+ # 1) "[pyarrow]" has already been stripped from the end of our string.
+ # 2) we know "[" is present
+ head, tail = string.split("[", 1)
+
+ if not tail.endswith("]"):
+ raise ValueError
+ tail = tail[:-1]
+
+ if head == "timestamp":
+ assert "," in tail # otherwise type_for_alias should work
+ unit, tz = tail.split(",", 1)
+ unit = unit.strip()
+ tz = tz.strip()
+ if tz.startswith("tz="):
+ tz = tz[3:]
+
+ pa_type = pa.timestamp(unit, tz=tz)
+ dtype = cls(pa_type)
+ return dtype
+
+ raise NotImplementedError(string)
+
@property
def _is_numeric(self) -> bool:
"""
diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py
index 2635343d73fd7..392a75f8a69a7 100644
--- a/pandas/tests/extension/base/dtype.py
+++ b/pandas/tests/extension/base/dtype.py
@@ -20,14 +20,6 @@ def test_kind(self, dtype):
valid = set("biufcmMOSUV")
assert dtype.kind in valid
- def test_construct_from_string_own_name(self, dtype):
- result = dtype.construct_from_string(dtype.name)
- assert type(result) is type(dtype)
-
- # check OK as classmethod
- result = type(dtype).construct_from_string(dtype.name)
- assert type(result) is type(dtype)
-
def test_is_dtype_from_name(self, dtype):
result = type(dtype).is_dtype(dtype.name)
assert result is True
@@ -97,9 +89,13 @@ def test_eq(self, dtype):
assert dtype == dtype.name
assert dtype != "anonther_type"
- def test_construct_from_string(self, dtype):
- dtype_instance = type(dtype).construct_from_string(dtype.name)
- assert isinstance(dtype_instance, type(dtype))
+ def test_construct_from_string_own_name(self, dtype):
+ result = dtype.construct_from_string(dtype.name)
+ assert type(result) is type(dtype)
+
+ # check OK as classmethod
+ result = type(dtype).construct_from_string(dtype.name)
+ assert type(result) is type(dtype)
def test_construct_from_string_another_type_raises(self, dtype):
msg = f"Cannot construct a '{type(dtype).__name__}' from 'another_type'"
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 2140a2e71eda9..c53b6e6658979 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -250,13 +250,9 @@ def test_astype_str(self, data, request):
class TestConstructors(base.BaseConstructorsTests):
def test_from_dtype(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
- if (pa.types.is_timestamp(pa_dtype) and pa_dtype.tz) or pa.types.is_string(
- pa_dtype
- ):
- if pa.types.is_string(pa_dtype):
- reason = "ArrowDtype(pa.string()) != StringDtype('pyarrow')"
- else:
- reason = f"pyarrow.type_for_alias cannot infer {pa_dtype}"
+
+ if pa.types.is_string(pa_dtype):
+ reason = "ArrowDtype(pa.string()) != StringDtype('pyarrow')"
request.node.add_marker(
pytest.mark.xfail(
reason=reason,
@@ -604,65 +600,24 @@ def test_in_numeric_groupby(self, data_for_grouping):
class TestBaseDtype(base.BaseDtypeTests):
def test_construct_from_string_own_name(self, dtype, request):
pa_dtype = dtype.pyarrow_dtype
- if pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None:
- request.node.add_marker(
- pytest.mark.xfail(
- raises=NotImplementedError,
- reason=f"pyarrow.type_for_alias cannot infer {pa_dtype}",
- )
- )
- elif pa.types.is_string(pa_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- raises=TypeError,
- reason=(
- "Still support StringDtype('pyarrow') "
- "over ArrowDtype(pa.string())"
- ),
- )
- )
+
+ if pa.types.is_string(pa_dtype):
+ # We still support StringDtype('pyarrow') over ArrowDtype(pa.string())
+ msg = r"string\[pyarrow\] should be constructed by StringDtype"
+ with pytest.raises(TypeError, match=msg):
+ dtype.construct_from_string(dtype.name)
+
+ return
+
super().test_construct_from_string_own_name(dtype)
def test_is_dtype_from_name(self, dtype, request):
pa_dtype = dtype.pyarrow_dtype
- if pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None:
- request.node.add_marker(
- pytest.mark.xfail(
- raises=NotImplementedError,
- reason=f"pyarrow.type_for_alias cannot infer {pa_dtype}",
- )
- )
- elif pa.types.is_string(pa_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason=(
- "Still support StringDtype('pyarrow') "
- "over ArrowDtype(pa.string())"
- ),
- )
- )
- super().test_is_dtype_from_name(dtype)
-
- def test_construct_from_string(self, dtype, request):
- pa_dtype = dtype.pyarrow_dtype
- if pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None:
- request.node.add_marker(
- pytest.mark.xfail(
- raises=NotImplementedError,
- reason=f"pyarrow.type_for_alias cannot infer {pa_dtype}",
- )
- )
- elif pa.types.is_string(pa_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- raises=TypeError,
- reason=(
- "Still support StringDtype('pyarrow') "
- "over ArrowDtype(pa.string())"
- ),
- )
- )
- super().test_construct_from_string(dtype)
+ if pa.types.is_string(pa_dtype):
+ # We still support StringDtype('pyarrow') over ArrowDtype(pa.string())
+ assert not type(dtype).is_dtype(dtype.name)
+ else:
+ super().test_is_dtype_from_name(dtype)
def test_construct_from_string_another_type_raises(self, dtype):
msg = r"'another_type' must end with '\[pyarrow\]'"
@@ -753,13 +708,6 @@ def test_EA_types(self, engine, data, request):
request.node.add_marker(
pytest.mark.xfail(raises=TypeError, reason="GH 47534")
)
- elif pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None:
- request.node.add_marker(
- pytest.mark.xfail(
- raises=NotImplementedError,
- reason=f"Parameterized types with tz={pa_dtype.tz} not supported.",
- )
- )
elif pa.types.is_timestamp(pa_dtype) and pa_dtype.unit in ("us", "ns"):
request.node.add_marker(
pytest.mark.xfail(
@@ -1266,7 +1214,12 @@ def test_invalid_other_comp(self, data, comparison_op):
def test_arrowdtype_construct_from_string_type_with_unsupported_parameters():
with pytest.raises(NotImplementedError, match="Passing pyarrow type"):
- ArrowDtype.construct_from_string("timestamp[s, tz=UTC][pyarrow]")
+ ArrowDtype.construct_from_string("not_a_real_dype[s, tz=UTC][pyarrow]")
+
+ # but as of GH#50689, timestamptz is supported
+ dtype = ArrowDtype.construct_from_string("timestamp[s, tz=UTC][pyarrow]")
+ expected = ArrowDtype(pa.timestamp("s", "UTC"))
+ assert dtype == expected
@pytest.mark.parametrize(
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50689 | 2023-01-12T03:17:46Z | 2023-02-18T17:38:28Z | 2023-02-18T17:38:28Z | 2023-02-18T17:38:43Z |
TST: simplify pyarrow tests, make mode work with temporal dtypes | diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 641eb7b01f0b6..d7faf00113609 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -657,12 +657,11 @@ def factorize(
pa_type = self._data.type
if pa.types.is_duration(pa_type):
# https://github.com/apache/arrow/issues/15226#issuecomment-1376578323
- arr = cast(ArrowExtensionArray, self.astype("int64[pyarrow]"))
- indices, uniques = arr.factorize(use_na_sentinel=use_na_sentinel)
- uniques = uniques.astype(self.dtype)
- return indices, uniques
+ data = self._data.cast(pa.int64())
+ else:
+ data = self._data
- encoded = self._data.dictionary_encode(null_encoding=null_encoding)
+ encoded = data.dictionary_encode(null_encoding=null_encoding)
if encoded.length() == 0:
indices = np.array([], dtype=np.intp)
uniques = type(self)(pa.chunked_array([], type=encoded.type.value_type))
@@ -674,6 +673,9 @@ def factorize(
np.intp, copy=False
)
uniques = type(self)(encoded.chunk(0).dictionary)
+
+ if pa.types.is_duration(pa_type):
+ uniques = cast(ArrowExtensionArray, uniques.astype(self.dtype))
return indices, uniques
def reshape(self, *args, **kwargs):
@@ -858,13 +860,20 @@ def unique(self: ArrowExtensionArrayT) -> ArrowExtensionArrayT:
-------
ArrowExtensionArray
"""
- if pa.types.is_duration(self._data.type):
+ pa_type = self._data.type
+
+ if pa.types.is_duration(pa_type):
# https://github.com/apache/arrow/issues/15226#issuecomment-1376578323
- arr = cast(ArrowExtensionArrayT, self.astype("int64[pyarrow]"))
- result = arr.unique()
- return cast(ArrowExtensionArrayT, result.astype(self.dtype))
+ data = self._data.cast(pa.int64())
+ else:
+ data = self._data
+
+ pa_result = pc.unique(data)
- return type(self)(pc.unique(self._data))
+ if pa.types.is_duration(pa_type):
+ pa_result = pa_result.cast(pa_type)
+
+ return type(self)(pa_result)
def value_counts(self, dropna: bool = True) -> Series:
"""
@@ -883,27 +892,30 @@ def value_counts(self, dropna: bool = True) -> Series:
--------
Series.value_counts
"""
- if pa.types.is_duration(self._data.type):
+ pa_type = self._data.type
+ if pa.types.is_duration(pa_type):
# https://github.com/apache/arrow/issues/15226#issuecomment-1376578323
- arr = cast(ArrowExtensionArray, self.astype("int64[pyarrow]"))
- result = arr.value_counts()
- result.index = result.index.astype(self.dtype)
- return result
+ data = self._data.cast(pa.int64())
+ else:
+ data = self._data
from pandas import (
Index,
Series,
)
- vc = self._data.value_counts()
+ vc = data.value_counts()
values = vc.field(0)
counts = vc.field(1)
- if dropna and self._data.null_count > 0:
+ if dropna and data.null_count > 0:
mask = values.is_valid()
values = values.filter(mask)
counts = counts.filter(mask)
+ if pa.types.is_duration(pa_type):
+ values = values.cast(pa_type)
+
# No missing values so we can adhere to the interface and return a numpy array.
counts = np.array(counts)
@@ -1231,12 +1243,29 @@ def _mode(self: ArrowExtensionArrayT, dropna: bool = True) -> ArrowExtensionArra
"""
if pa_version_under6p0:
raise NotImplementedError("mode only supported for pyarrow version >= 6.0")
- modes = pc.mode(self._data, pc.count_distinct(self._data).as_py())
+
+ pa_type = self._data.type
+ if pa.types.is_temporal(pa_type):
+ nbits = pa_type.bit_width
+ if nbits == 32:
+ data = self._data.cast(pa.int32())
+ elif nbits == 64:
+ data = self._data.cast(pa.int64())
+ else:
+ raise NotImplementedError(pa_type)
+ else:
+ data = self._data
+
+ modes = pc.mode(data, pc.count_distinct(data).as_py())
values = modes.field(0)
counts = modes.field(1)
# counts sorted descending i.e counts[0] = max
mask = pc.equal(counts, counts[0])
most_common = values.filter(mask)
+
+ if pa.types.is_temporal(pa_type):
+ most_common = most_common.cast(pa_type)
+
return type(self)(most_common)
def _maybe_convert_setitem_value(self, value):
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 889df3fee15c7..d643582e98095 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -336,15 +336,39 @@ def test_from_sequence_of_strings_pa_array(self, data, request):
class TestGetitemTests(base.BaseGetitemTests):
- @pytest.mark.xfail(
- reason=(
- "data.dtype.type return pyarrow.DataType "
- "but this (intentionally) returns "
- "Python scalars or pd.NA"
- )
- )
def test_getitem_scalar(self, data):
- super().test_getitem_scalar(data)
+ # In the base class we expect data.dtype.type; but this (intentionally)
+ # returns Python scalars or pd.NA
+ pa_type = data._data.type
+ if pa.types.is_integer(pa_type):
+ exp_type = int
+ elif pa.types.is_floating(pa_type):
+ exp_type = float
+ elif pa.types.is_string(pa_type):
+ exp_type = str
+ elif pa.types.is_binary(pa_type):
+ exp_type = bytes
+ elif pa.types.is_boolean(pa_type):
+ exp_type = bool
+ elif pa.types.is_duration(pa_type):
+ exp_type = timedelta
+ elif pa.types.is_timestamp(pa_type):
+ if pa_type.unit == "ns":
+ exp_type = pd.Timestamp
+ else:
+ exp_type = datetime
+ elif pa.types.is_date(pa_type):
+ exp_type = date
+ elif pa.types.is_time(pa_type):
+ exp_type = time
+ else:
+ raise NotImplementedError(data.dtype)
+
+ result = data[0]
+ assert isinstance(result, exp_type), type(result)
+
+ result = pd.Series(data)[0]
+ assert isinstance(result, exp_type), type(result)
class TestBaseAccumulateTests(base.BaseAccumulateTests):
@@ -1011,70 +1035,83 @@ def _patch_combine(self, obj, other, op):
expected = pd.Series(pd_array)
return expected
- def test_arith_series_with_scalar(
- self, data, all_arithmetic_operators, request, monkeypatch
- ):
- pa_dtype = data.dtype.pyarrow_dtype
-
- arrow_temporal_supported = not pa_version_under8p0 and (
- all_arithmetic_operators in ("__add__", "__radd__")
+ def _is_temporal_supported(self, opname, pa_dtype):
+ return not pa_version_under8p0 and (
+ opname in ("__add__", "__radd__")
and pa.types.is_duration(pa_dtype)
- or all_arithmetic_operators in ("__sub__", "__rsub__")
+ or opname in ("__sub__", "__rsub__")
and pa.types.is_temporal(pa_dtype)
)
- if all_arithmetic_operators == "__rmod__" and (
- pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
- ):
- pytest.skip("Skip testing Python string formatting")
- elif all_arithmetic_operators in {
+
+ def _get_scalar_exception(self, opname, pa_dtype):
+ arrow_temporal_supported = self._is_temporal_supported(opname, pa_dtype)
+ if opname in {
"__mod__",
"__rmod__",
}:
- self.series_scalar_exc = NotImplementedError
+ exc = NotImplementedError
elif arrow_temporal_supported:
- self.series_scalar_exc = None
- elif not (
- pa.types.is_floating(pa_dtype)
- or pa.types.is_integer(pa_dtype)
- or arrow_temporal_supported
- ):
- self.series_scalar_exc = pa.ArrowNotImplementedError
+ exc = None
+ elif not (pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype)):
+ exc = pa.ArrowNotImplementedError
else:
- self.series_scalar_exc = None
+ exc = None
+ return exc
+
+ def _get_arith_xfail_marker(self, opname, pa_dtype):
+ mark = None
+
+ arrow_temporal_supported = self._is_temporal_supported(opname, pa_dtype)
+
if (
- all_arithmetic_operators == "__rpow__"
+ opname == "__rpow__"
and (pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype))
and not pa_version_under6p0
):
- request.node.add_marker(
- pytest.mark.xfail(
- reason=(
- f"GH 29997: 1**pandas.NA == 1 while 1**pyarrow.NA == NULL "
- f"for {pa_dtype}"
- )
+ mark = pytest.mark.xfail(
+ reason=(
+ f"GH#29997: 1**pandas.NA == 1 while 1**pyarrow.NA == NULL "
+ f"for {pa_dtype}"
)
)
elif arrow_temporal_supported:
- request.node.add_marker(
- pytest.mark.xfail(
- raises=TypeError,
- reason=(
- f"{all_arithmetic_operators} not supported between"
- f"pd.NA and {pa_dtype} Python scalar"
- ),
- )
+ mark = pytest.mark.xfail(
+ raises=TypeError,
+ reason=(
+ f"{opname} not supported between"
+ f"pd.NA and {pa_dtype} Python scalar"
+ ),
)
elif (
- all_arithmetic_operators in {"__rtruediv__", "__rfloordiv__"}
+ opname in {"__rtruediv__", "__rfloordiv__"}
and (pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype))
and not pa_version_under6p0
):
- request.node.add_marker(
- pytest.mark.xfail(
- raises=pa.ArrowInvalid,
- reason="divide by 0",
- )
+ mark = pytest.mark.xfail(
+ raises=pa.ArrowInvalid,
+ reason="divide by 0",
)
+
+ return mark
+
+ def test_arith_series_with_scalar(
+ self, data, all_arithmetic_operators, request, monkeypatch
+ ):
+ pa_dtype = data.dtype.pyarrow_dtype
+
+ if all_arithmetic_operators == "__rmod__" and (
+ pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
+ ):
+ pytest.skip("Skip testing Python string formatting")
+
+ self.series_scalar_exc = self._get_scalar_exception(
+ all_arithmetic_operators, pa_dtype
+ )
+
+ mark = self._get_arith_xfail_marker(all_arithmetic_operators, pa_dtype)
+ if mark is not None:
+ request.node.add_marker(mark)
+
if all_arithmetic_operators == "__floordiv__" and pa.types.is_integer(pa_dtype):
# BaseOpsUtil._combine always returns int64, while ArrowExtensionArray does
# not upcast
@@ -1086,61 +1123,19 @@ def test_arith_frame_with_scalar(
):
pa_dtype = data.dtype.pyarrow_dtype
- arrow_temporal_supported = not pa_version_under8p0 and (
- all_arithmetic_operators in ("__add__", "__radd__")
- and pa.types.is_duration(pa_dtype)
- or all_arithmetic_operators in ("__sub__", "__rsub__")
- and pa.types.is_temporal(pa_dtype)
- )
if all_arithmetic_operators == "__rmod__" and (
pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
):
pytest.skip("Skip testing Python string formatting")
- elif all_arithmetic_operators in {
- "__mod__",
- "__rmod__",
- }:
- self.frame_scalar_exc = NotImplementedError
- elif arrow_temporal_supported:
- self.frame_scalar_exc = None
- elif not (pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype)):
- self.frame_scalar_exc = pa.ArrowNotImplementedError
- else:
- self.frame_scalar_exc = None
- if (
- all_arithmetic_operators == "__rpow__"
- and (pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype))
- and not pa_version_under6p0
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason=(
- f"GH 29997: 1**pandas.NA == 1 while 1**pyarrow.NA == NULL "
- f"for {pa_dtype}"
- )
- )
- )
- elif arrow_temporal_supported:
- request.node.add_marker(
- pytest.mark.xfail(
- raises=TypeError,
- reason=(
- f"{all_arithmetic_operators} not supported between"
- f"pd.NA and {pa_dtype} Python scalar"
- ),
- )
- )
- elif (
- all_arithmetic_operators in {"__rtruediv__", "__rfloordiv__"}
- and (pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype))
- and not pa_version_under6p0
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- raises=pa.ArrowInvalid,
- reason="divide by 0",
- )
- )
+
+ self.frame_scalar_exc = self._get_scalar_exception(
+ all_arithmetic_operators, pa_dtype
+ )
+
+ mark = self._get_arith_xfail_marker(all_arithmetic_operators, pa_dtype)
+ if mark is not None:
+ request.node.add_marker(mark)
+
if all_arithmetic_operators == "__floordiv__" and pa.types.is_integer(pa_dtype):
# BaseOpsUtil._combine always returns int64, while ArrowExtensionArray does
# not upcast
@@ -1152,37 +1147,11 @@ def test_arith_series_with_array(
):
pa_dtype = data.dtype.pyarrow_dtype
- arrow_temporal_supported = not pa_version_under8p0 and (
- all_arithmetic_operators in ("__add__", "__radd__")
- and pa.types.is_duration(pa_dtype)
- or all_arithmetic_operators in ("__sub__", "__rsub__")
- and pa.types.is_temporal(pa_dtype)
+ self.series_array_exc = self._get_scalar_exception(
+ all_arithmetic_operators, pa_dtype
)
- if all_arithmetic_operators in {
- "__mod__",
- "__rmod__",
- }:
- self.series_array_exc = NotImplementedError
- elif arrow_temporal_supported:
- self.series_array_exc = None
- elif not (pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype)):
- self.series_array_exc = pa.ArrowNotImplementedError
- else:
- self.series_array_exc = None
+
if (
- all_arithmetic_operators == "__rpow__"
- and (pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype))
- and not pa_version_under6p0
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason=(
- f"GH 29997: 1**pandas.NA == 1 while 1**pyarrow.NA == NULL "
- f"for {pa_dtype}"
- )
- )
- )
- elif (
all_arithmetic_operators
in (
"__sub__",
@@ -1200,32 +1169,17 @@ def test_arith_series_with_array(
),
)
)
- elif arrow_temporal_supported:
- request.node.add_marker(
- pytest.mark.xfail(
- raises=TypeError,
- reason=(
- f"{all_arithmetic_operators} not supported between"
- f"pd.NA and {pa_dtype} Python scalar"
- ),
- )
- )
- elif (
- all_arithmetic_operators in {"__rtruediv__", "__rfloordiv__"}
- and (pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype))
- and not pa_version_under6p0
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- raises=pa.ArrowInvalid,
- reason="divide by 0",
- )
- )
+
+ mark = self._get_arith_xfail_marker(all_arithmetic_operators, pa_dtype)
+ if mark is not None:
+ request.node.add_marker(mark)
+
op_name = all_arithmetic_operators
ser = pd.Series(data)
# pd.Series([ser.iloc[0]] * len(ser)) may not return ArrowExtensionArray
# since ser.iloc[0] is a python scalar
other = pd.Series(pd.array([ser.iloc[0]] * len(ser), dtype=data.dtype))
+
if pa.types.is_floating(pa_dtype) or (
pa.types.is_integer(pa_dtype) and all_arithmetic_operators != "__truediv__"
):
@@ -1321,6 +1275,25 @@ def test_arrowdtype_construct_from_string_type_with_unsupported_parameters():
@pytest.mark.parametrize("quantile", [0.5, [0.5, 0.5]])
def test_quantile(data, interpolation, quantile, request):
pa_dtype = data.dtype.pyarrow_dtype
+
+ data = data.take([0, 0, 0])
+ ser = pd.Series(data)
+
+ if (
+ pa.types.is_string(pa_dtype)
+ or pa.types.is_binary(pa_dtype)
+ or pa.types.is_boolean(pa_dtype)
+ ):
+ # For string, bytes, and bool, we don't *expect* to have quantile work
+ # Note this matches the non-pyarrow behavior
+ if pa_version_under7p0:
+ msg = r"Function quantile has no kernel matching input types \(.*\)"
+ else:
+ msg = r"Function 'quantile' has no kernel matching input types \(.*\)"
+ with pytest.raises(pa.ArrowNotImplementedError, match=msg):
+ ser.quantile(q=quantile, interpolation=interpolation)
+ return
+
if not (pa.types.is_integer(pa_dtype) or pa.types.is_floating(pa_dtype)):
request.node.add_marker(
pytest.mark.xfail(
@@ -1355,11 +1328,7 @@ def test_quantile(data, interpolation, quantile, request):
)
def test_mode(data_for_grouping, dropna, take_idx, exp_idx, request):
pa_dtype = data_for_grouping.dtype.pyarrow_dtype
- if (
- pa.types.is_temporal(pa_dtype)
- or pa.types.is_string(pa_dtype)
- or pa.types.is_binary(pa_dtype)
- ):
+ if pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype):
request.node.add_marker(
pytest.mark.xfail(
raises=pa.ArrowNotImplementedError,
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50688 | 2023-01-12T01:22:40Z | 2023-01-18T20:07:38Z | 2023-01-18T20:07:37Z | 2023-01-18T20:27:31Z |
TST: Fix test_constructor_signed_int_overflow_deprecation w/ multiple warnings | diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index e4ab5ef596440..bc26158f40416 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -13,10 +13,7 @@
iNaT,
lib,
)
-from pandas.compat import (
- IS64,
- is_numpy_dev,
-)
+from pandas.compat import is_numpy_dev
from pandas.compat.numpy import np_version_gte1p24
import pandas.util._test_decorators as td
@@ -736,22 +733,21 @@ def test_constructor_cast(self):
with pytest.raises(ValueError, match=msg):
Series(["a", "b", "c"], dtype=float)
- @pytest.mark.xfail(np_version_gte1p24 and not IS64, reason="GH49777")
def test_constructor_signed_int_overflow_deprecation(self):
# GH#41734 disallow silent overflow
msg = "Values are too large to be losslessly cast"
- numpy_warning = DeprecationWarning if is_numpy_dev else None
- with tm.assert_produces_warning(
- (FutureWarning, numpy_warning), match=msg, check_stacklevel=False
- ):
+ warns = (
+ (FutureWarning, DeprecationWarning)
+ if is_numpy_dev or np_version_gte1p24
+ else FutureWarning
+ )
+ with tm.assert_produces_warning(warns, match=msg, check_stacklevel=False):
ser = Series([1, 200, 923442], dtype="int8")
expected = Series([1, -56, 50], dtype="int8")
tm.assert_series_equal(ser, expected)
- with tm.assert_produces_warning(
- (FutureWarning, numpy_warning), match=msg, check_stacklevel=False
- ):
+ with tm.assert_produces_warning(warns, match=msg, check_stacklevel=False):
ser = Series([1, 200, 923442], dtype="uint8")
expected = Series([1, 200, 50], dtype="uint8")
| - closes #50710
Would raise
```
2023-01-07T01:45:49.8230480Z FAILED ../lib/python3.10/site-packages/pandas/tests/series/test_constructors.py::TestSeriesConstructors::test_constructor_signed_int_overflow_deprecation - TypeError: issubclass() arg 2 must be a class, a tuple of classes, or a union
```
because tuple would contain (FutureWarning, None) which is not supported
xref https://github.com/conda-forge/pandas-feedstock/issues/150 | https://api.github.com/repos/pandas-dev/pandas/pulls/50686 | 2023-01-12T00:04:05Z | 2023-01-12T20:30:22Z | 2023-01-12T20:30:22Z | 2023-01-12T20:30:26Z |
BUG: Series.quantile emitting RuntimeWarning for all NA case | diff --git a/doc/source/whatsnew/v1.5.3.rst b/doc/source/whatsnew/v1.5.3.rst
index 2141f672462ef..92577c48b865b 100644
--- a/doc/source/whatsnew/v1.5.3.rst
+++ b/doc/source/whatsnew/v1.5.3.rst
@@ -28,6 +28,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
- Bug in :meth:`.Styler.to_excel` leading to error when unrecognized ``border-style`` (e.g. ``"hair"``) provided to Excel writers (:issue:`48649`)
+- Bug in :meth:`Series.quantile` emitting warning from NumPy when :class:`Series` has only ``NA`` values (:issue:`50681`)
- Bug when chaining several :meth:`.Styler.concat` calls, only the last styler was concatenated (:issue:`49207`)
- Fixed bug when instantiating a :class:`DataFrame` subclass inheriting from ``typing.Generic`` that triggered a ``UserWarning`` on python 3.11 (:issue:`49649`)
-
diff --git a/pandas/core/array_algos/quantile.py b/pandas/core/array_algos/quantile.py
index 217fbafce719c..d3d9cb1b29b9a 100644
--- a/pandas/core/array_algos/quantile.py
+++ b/pandas/core/array_algos/quantile.py
@@ -204,8 +204,10 @@ def _nanpercentile(
result = np.array(result, copy=False).T
if (
result.dtype != values.dtype
+ and not mask.all()
and (result == result.astype(values.dtype, copy=False)).all()
):
+ # mask.all() will never get cast back to int
# e.g. values id integer dtype and result is floating dtype,
# only cast back to integer dtype if result values are all-integer.
result = result.astype(values.dtype, copy=False)
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index ec3fdc6db9dc9..aaa7c706d95bb 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -1039,6 +1039,11 @@ def _quantile(
raise NotImplementedError
if self.isna().all():
out_mask = np.ones(res.shape, dtype=bool)
+
+ if is_integer_dtype(self.dtype):
+ # We try to maintain int dtype if possible for not all-na case
+ # as well
+ res = np.zeros(res.shape, dtype=self.dtype.numpy_dtype)
else:
out_mask = np.zeros(res.shape, dtype=bool)
else:
diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py
index 93e1bcc113765..c4b9873449424 100644
--- a/pandas/tests/frame/methods/test_quantile.py
+++ b/pandas/tests/frame/methods/test_quantile.py
@@ -897,15 +897,8 @@ def test_quantile_ea_all_na(self, request, obj, index):
qs = [0.5, 0, 1]
result = self.compute_quantile(obj, qs)
- if np_version_under1p21 and index.dtype == "timedelta64[ns]":
- msg = "failed on Numpy 1.20.3; TypeError: data type 'Int64' not understood"
- mark = pytest.mark.xfail(reason=msg, raises=TypeError)
- request.node.add_marker(mark)
-
expected = index.take([-1, -1, -1], allow_fill=True, fill_value=index._na_value)
expected = Series(expected, index=qs, name="A")
- if expected.dtype == "Int64":
- expected = expected.astype("Float64")
expected = type(obj)(expected)
tm.assert_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_quantile.py b/pandas/tests/series/methods/test_quantile.py
index 6326d50b20ab8..0ef1e63f742db 100644
--- a/pandas/tests/series/methods/test_quantile.py
+++ b/pandas/tests/series/methods/test_quantile.py
@@ -225,3 +225,18 @@ def test_quantile_dtypes(self, dtype):
if dtype == "Int64":
expected = expected.astype("Float64")
tm.assert_series_equal(result, expected)
+
+ def test_quantile_all_na(self, any_int_ea_dtype):
+ # GH#50681
+ ser = Series([pd.NA, pd.NA], dtype=any_int_ea_dtype)
+ with tm.assert_produces_warning(None):
+ result = ser.quantile([0.1, 0.5])
+ expected = Series([pd.NA, pd.NA], dtype=any_int_ea_dtype, index=[0.1, 0.5])
+ tm.assert_series_equal(result, expected)
+
+ def test_quantile_dtype_size(self, any_int_ea_dtype):
+ # GH#50681
+ ser = Series([pd.NA, pd.NA, 1], dtype=any_int_ea_dtype)
+ result = ser.quantile([0.1, 0.5])
+ expected = Series([1, 1], dtype=any_int_ea_dtype, index=[0.1, 0.5])
+ tm.assert_series_equal(result, expected)
| - [x] closes #50681 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
I am not totally sure that we should backport since technically this also fixes a bug.
Edit: Could probably avoid the bug fix I guess | https://api.github.com/repos/pandas-dev/pandas/pulls/50685 | 2023-01-12T00:03:45Z | 2023-01-12T20:28:56Z | 2023-01-12T20:28:56Z | 2023-01-12T21:26:14Z |
BUG: is_any_int_dtype not recognizing arrow integers | diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 4a8f1292ecdef..aa3cdcd65b344 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -638,7 +638,11 @@ def is_any_int_dtype(arr_or_dtype) -> bool:
>>> is_any_int_dtype(pd.Index([1, 2.])) # float
False
"""
- return _is_dtype_type(arr_or_dtype, classes(np.integer, np.timedelta64))
+ return _is_dtype_type(
+ arr_or_dtype, classes(np.integer, np.timedelta64)
+ ) or _is_dtype(
+ arr_or_dtype, lambda typ: isinstance(typ, ExtensionDtype) and typ.kind in "iu"
+ )
def is_integer_dtype(arr_or_dtype) -> bool:
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 78c49ae066288..0a7303ea239ed 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -35,6 +35,8 @@
)
from pandas.errors import PerformanceWarning
+from pandas.core.dtypes.common import is_any_int_dtype
+
import pandas as pd
import pandas._testing as tm
from pandas.api.types import (
@@ -1459,6 +1461,15 @@ def test_is_integer_dtype(data):
assert not is_integer_dtype(data)
+def test_is_any_integer_dtype(data):
+ # GH 50667
+ pa_type = data.dtype.pyarrow_dtype
+ if pa.types.is_integer(pa_type):
+ assert is_any_int_dtype(data)
+ else:
+ assert not is_any_int_dtype(data)
+
+
def test_is_signed_integer_dtype(data):
pa_type = data.dtype.pyarrow_dtype
if pa.types.is_signed_integer(pa_type):
| - [x] xref #50667 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
internal, so no whatsnew
cc @mroeschke Did you leave this out intentionally? | https://api.github.com/repos/pandas-dev/pandas/pulls/50683 | 2023-01-11T22:56:27Z | 2023-01-12T08:14:05Z | 2023-01-12T08:14:05Z | 2023-01-12T08:14:10Z |
BUG: pivot_table with nested elements and numpy 1.24 | diff --git a/doc/source/whatsnew/v1.5.3.rst b/doc/source/whatsnew/v1.5.3.rst
index b395dbc0b6c69..176f713df61d3 100644
--- a/doc/source/whatsnew/v1.5.3.rst
+++ b/doc/source/whatsnew/v1.5.3.rst
@@ -32,8 +32,8 @@ Bug fixes
- Bug in :meth:`Series.quantile` emitting warning from NumPy when :class:`Series` has only ``NA`` values (:issue:`50681`)
- Bug when chaining several :meth:`.Styler.concat` calls, only the last styler was concatenated (:issue:`49207`)
- Fixed bug when instantiating a :class:`DataFrame` subclass inheriting from ``typing.Generic`` that triggered a ``UserWarning`` on python 3.11 (:issue:`49649`)
+- Bug in :func:`pivot_table` with NumPy 1.24 or greater when the :class:`DataFrame` columns has nested elements (:issue:`50342`)
- Bug in :func:`pandas.testing.assert_series_equal` (and equivalent ``assert_`` functions) when having nested data and using numpy >= 1.25 (:issue:`50360`)
--
.. ---------------------------------------------------------------------------
.. _whatsnew_153.other:
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 8764ee0ea6ed7..aaa5134ed1aaa 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -25,6 +25,7 @@
cast,
overload,
)
+import warnings
import numpy as np
@@ -235,7 +236,17 @@ def asarray_tuplesafe(values: Iterable, dtype: NpDtype | None = None) -> ArrayLi
if isinstance(values, list) and dtype in [np.object_, object]:
return construct_1d_object_array_from_listlike(values)
- result = np.asarray(values, dtype=dtype)
+ try:
+ with warnings.catch_warnings():
+ # Can remove warning filter once NumPy 1.24 is min version
+ warnings.simplefilter("ignore", np.VisibleDeprecationWarning)
+ result = np.asarray(values, dtype=dtype)
+ except ValueError:
+ # Using try/except since it's more performant than checking is_list_like
+ # over each element
+ # error: Argument 1 to "construct_1d_object_array_from_listlike"
+ # has incompatible type "Iterable[Any]"; expected "Sized"
+ return construct_1d_object_array_from_listlike(values) # type: ignore[arg-type]
if issubclass(result.dtype.type, str):
result = np.asarray(values, dtype=object)
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index 3655d4cf1b28a..2406379892834 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -2312,6 +2312,75 @@ def test_pivot_table_datetime_warning(self):
)
tm.assert_frame_equal(result, expected)
+ def test_pivot_table_with_mixed_nested_tuples(self, using_array_manager):
+ # GH 50342
+ df = DataFrame(
+ {
+ "A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"],
+ "B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"],
+ "C": [
+ "small",
+ "large",
+ "large",
+ "small",
+ "small",
+ "large",
+ "small",
+ "small",
+ "large",
+ ],
+ "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
+ "E": [2, 4, 5, 5, 6, 6, 8, 9, 9],
+ ("col5",): [
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "foo",
+ "bar",
+ "bar",
+ "bar",
+ "bar",
+ ],
+ ("col6", 6): [
+ "one",
+ "one",
+ "one",
+ "two",
+ "two",
+ "one",
+ "one",
+ "two",
+ "two",
+ ],
+ (7, "seven"): [
+ "small",
+ "large",
+ "large",
+ "small",
+ "small",
+ "large",
+ "small",
+ "small",
+ "large",
+ ],
+ }
+ )
+ result = pivot_table(
+ df, values="D", index=["A", "B"], columns=[(7, "seven")], aggfunc=np.sum
+ )
+ expected = DataFrame(
+ [[4.0, 5.0], [7.0, 6.0], [4.0, 1.0], [np.nan, 6.0]],
+ columns=Index(["large", "small"], name=(7, "seven")),
+ index=MultiIndex.from_arrays(
+ [["bar", "bar", "foo", "foo"], ["one", "two"] * 2], names=["A", "B"]
+ ),
+ )
+ if using_array_manager:
+ # INFO(ArrayManager) column without NaNs can preserve int dtype
+ expected["small"] = expected["small"].astype("int64")
+ tm.assert_frame_equal(result, expected)
+
class TestPivot:
def test_pivot(self):
| - [ ] closes #50342 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
I think we have still pinned numpy in our 1.5.x branch but confirmed this still works locally
```
% conda list numpy
# packages in environment at /opt/miniconda3/envs/pandas-dev:
#
# Name Version Build Channel
numpy 1.24.1 py38hc2f29e8_0 conda-forge
numpydoc 1.5.0 pyhd8ed1ab_0 conda-forge
% pytest pandas/tests/reshape/test_pivot.py -k test_pivot_table_with_mixed_nested_tuples
================================================================================== test session starts ===================================================================================
platform darwin -- Python 3.8.15, pytest-7.2.0, pluggy-1.0.0
rootdir: , configfile: pyproject.toml
plugins: asyncio-0.20.2, cython-0.2.0, hypothesis-6.58.1, xdist-3.0.2, cov-4.0.0, anyio-3.6.2
asyncio: mode=strict
collected 539 items / 538 deselected / 1 selected
pandas/tests/reshape/test_pivot.py .
------------------------------------------------------- generated xml file: /test-data.xml --------------------------------------------------------
================================================================================== slowest 30 durations ==================================================================================
0.01s call pandas/tests/reshape/test_pivot.py::TestPivotTable::test_pivot_table_with_mixed_nested_tuples
(2 durations < 0.005s hidden. Use -vv to show these durations.)
=========================================================================== 1 passed, 538 deselected in 0.48s ============================================================================
```
EDIT: Numpy is no longer pinned on main so this should run in the CI | https://api.github.com/repos/pandas-dev/pandas/pulls/50682 | 2023-01-11T22:43:42Z | 2023-01-17T17:35:22Z | 2023-01-17T17:35:22Z | 2023-01-17T17:35:26Z |
DOC: Add note in 1.5.3 about SQLAlchemy warnings | diff --git a/doc/source/whatsnew/v1.5.3.rst b/doc/source/whatsnew/v1.5.3.rst
index 0cb8796e3fb5d..2141f672462ef 100644
--- a/doc/source/whatsnew/v1.5.3.rst
+++ b/doc/source/whatsnew/v1.5.3.rst
@@ -37,6 +37,13 @@ Bug fixes
Other
~~~~~
+
+.. note::
+
+ If you are using :meth:`DataFrame.to_sql`, :func:`read_sql`, :func:`read_sql_table`, or :func:`read_sql_query` with SQLAlchemy 1.4.46 or greater,
+ you may see a ``sqlalchemy.exc.RemovedIn20Warning``. These warnings can be safely ignored for the SQLAlchemy 1.4.x releases
+ as pandas works toward compatibility with SQLAlchemy 2.0.
+
- Reverted deprecation (:issue:`45324`) of behavior of :meth:`Series.__getitem__` and :meth:`Series.__setitem__` slicing with an integer :class:`Index`; this will remain positional (:issue:`49612`)
-
| xref #50558
As discussed in todays dev call, for 1.5.3 the decision was to document that SQLAlchemy warnings can be expected but not addressed. | https://api.github.com/repos/pandas-dev/pandas/pulls/50680 | 2023-01-11T21:38:01Z | 2023-01-12T08:13:18Z | 2023-01-12T08:13:18Z | 2023-01-12T15:58:39Z |
Update eval_performance.py | diff --git a/doc/scripts/eval_performance.py b/doc/scripts/eval_performance.py
index f6087e02a9330..559689ef5915b 100644
--- a/doc/scripts/eval_performance.py
+++ b/doc/scripts/eval_performance.py
@@ -6,6 +6,7 @@
from pandas import DataFrame
setup_common = """from pandas import DataFrame
+import numpy as np
df = DataFrame(np.random.randn(%d, 3), columns=list('abc'))
%s"""
| I think there is someone has forgotten or maybe delete this by mistaken : import numpy as np
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50679 | 2023-01-11T19:49:06Z | 2023-01-12T01:45:07Z | 2023-01-12T01:45:07Z | 2023-01-12T01:45:13Z |
TEST: added test case for issue 41800 | diff --git a/pandas/tests/series/methods/test_combine_first.py b/pandas/tests/series/methods/test_combine_first.py
index 1d104b12ce7d2..bd8f9df026e19 100644
--- a/pandas/tests/series/methods/test_combine_first.py
+++ b/pandas/tests/series/methods/test_combine_first.py
@@ -100,3 +100,16 @@ def test_combine_first_dt_tz_values(self, tz_naive_fixture):
)
exp = Series(exp_vals, name="ser1")
tm.assert_series_equal(exp, result)
+
+ def test_combine_first_timezone_series_with_empty_series(self):
+ # GH 41800
+ time_index = date_range(
+ datetime(2021, 1, 1, 1),
+ datetime(2021, 1, 1, 10),
+ freq="H",
+ tz="Europe/Rome",
+ )
+ s1 = Series(range(10), index=time_index)
+ s2 = Series(index=time_index)
+ result = s1.combine_first(s2)
+ tm.assert_series_equal(result, s1)
| - [x] Addresses #41800
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50677 | 2023-01-11T16:45:49Z | 2023-01-12T18:50:52Z | 2023-01-12T18:50:52Z | 2023-01-12T18:50:59Z |
DEPR: ADD FutureWarning for pandas.io.execute | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index 9a99dbad30708..39a93304bfe5a 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -556,9 +556,10 @@ Other API changes
Deprecations
~~~~~~~~~~~~
- Deprecated argument ``infer_datetime_format`` in :func:`to_datetime` and :func:`read_csv`, as a strict version of it is now the default (:issue:`48621`)
+- Deprecated :func:`pandas.io.sql.execute`(:issue:`50185`)
+-
.. ---------------------------------------------------------------------------
-
.. _whatsnew_200.prior_deprecations:
Removal of prior version deprecations/changes
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 2b845786b0366..eea97fc0d9760 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -201,6 +201,12 @@ def execute(sql, con, params=None):
-------
Results Iterable
"""
+ warnings.warn(
+ "`pandas.io.sql.execute` is deprecated and "
+ "will be removed in the future version.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ ) # GH50185
sqlalchemy = import_optional_dependency("sqlalchemy", errors="ignore")
if sqlalchemy is not None and isinstance(con, (str, sqlalchemy.engine.Engine)):
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 31ca060e36ad1..f83b6b0373a87 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -668,6 +668,16 @@ def test_execute_typeerror(sqlite_iris_engine):
sql.execute("select * from iris", sqlite_iris_engine)
+def test_execute_deprecated(sqlite_buildin_iris):
+ # GH50185
+ with tm.assert_produces_warning(
+ FutureWarning,
+ match="`pandas.io.sql.execute` is deprecated and "
+ "will be removed in the future version.",
+ ):
+ sql.execute("select * from iris", sqlite_buildin_iris)
+
+
class MixInBase:
def teardown_method(self):
# if setup fails, there may not be a connection to close.
| reopen for [DEPR: Add FutureWarning for pandas.io.sql.execute Pull Request #50638](https://github.com/pandas-dev/pandas/pull/50638)
- [x] closes #50185
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/50676 | 2023-01-11T15:29:58Z | 2023-01-12T16:02:53Z | 2023-01-12T16:02:53Z | 2023-01-12T16:41:25Z |
CLN: fix and move using_copy_on_write() helper out of internals | diff --git a/pandas/_config/__init__.py b/pandas/_config/__init__.py
index 929f8a5af6b3f..5219abc697dbd 100644
--- a/pandas/_config/__init__.py
+++ b/pandas/_config/__init__.py
@@ -14,10 +14,12 @@
"describe_option",
"option_context",
"options",
+ "using_copy_on_write",
]
from pandas._config import config
from pandas._config import dates # pyright: ignore # noqa:F401
from pandas._config.config import (
+ _global_config,
describe_option,
get_option,
option_context,
@@ -26,3 +28,8 @@
set_option,
)
from pandas._config.display import detect_console_encoding
+
+
+def using_copy_on_write():
+ _mode_options = _global_config["mode"]
+ return _mode_options["copy_on_write"] and _mode_options["data_manager"] == "block"
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index baf2ae82a365e..8980fe0249193 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -29,7 +29,10 @@
import numpy as np
-from pandas._config import config
+from pandas._config import (
+ config,
+ using_copy_on_write,
+)
from pandas._libs import lib
from pandas._libs.tslibs import (
@@ -158,7 +161,6 @@
SingleArrayManager,
)
from pandas.core.internals.construction import mgr_to_mgr
-from pandas.core.internals.managers import using_copy_on_write
from pandas.core.methods.describe import describe_ndframe
from pandas.core.missing import (
clean_fill_method,
@@ -4023,10 +4025,7 @@ def _check_setitem_copy(self, t: str = "setting", force: bool_t = False):
df.iloc[0:5]['group'] = 'a'
"""
- if (
- config.get_option("mode.copy_on_write")
- and config.get_option("mode.data_manager") == "block"
- ):
+ if using_copy_on_write():
return
# return early if the check is not needed
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index c90787ee24277..ac0d614dfea89 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -15,7 +15,7 @@
import numpy as np
-from pandas._config import config
+from pandas._config import using_copy_on_write
from pandas._libs import (
algos as libalgos,
@@ -2362,10 +2362,3 @@ def _preprocess_slice_or_indexer(
if not allow_fill:
indexer = maybe_convert_indices(indexer, length)
return "fancy", indexer, len(indexer)
-
-
-_mode_options = config._global_config["mode"]
-
-
-def using_copy_on_write():
- return _mode_options["copy_on_write"]
diff --git a/pandas/core/series.py b/pandas/core/series.py
index b5d73373f061e..23982d90d693b 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -22,7 +22,10 @@
import numpy as np
-from pandas._config import get_option
+from pandas._config import (
+ get_option,
+ using_copy_on_write,
+)
from pandas._libs import (
lib,
@@ -1263,10 +1266,7 @@ def _maybe_update_cacher(
# for CoW, we never want to update the parent DataFrame cache
# if the Series changed, and always pop the cached item
elif (
- not (
- get_option("mode.copy_on_write")
- and get_option("mode.data_manager") == "block"
- )
+ not using_copy_on_write()
and len(self) == len(ref)
and self.name in ref.columns
):
diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py
index 036ddd40ae137..68a376956429b 100755
--- a/scripts/validate_unwanted_patterns.py
+++ b/scripts/validate_unwanted_patterns.py
@@ -52,6 +52,7 @@
"_test_decorators",
"__version__", # check np.__version__ in compat.numpy.function
"_arrow_dtype_mapping",
+ "_global_config",
}
| I initially added this helper function just to the BlockManager internals in https://github.com/pandas-dev/pandas/pull/49771, but since then it seems we also started to use it outside of the internals. Which I think is a good change for a check that we will have to do often on the short term (it makes it more convenient to do this check, see the improvement in the diff where I changed existing `get_option(..)` calls).
But, 1) the current function was only meant for internal usage and was incorrect for usage outside of the BlockManager (it also needs to check for the manager option) -> fixed that, and 2) moved it outside of the internals, so we don't have to import it from the internals in other parts of pandas. | https://api.github.com/repos/pandas-dev/pandas/pulls/50675 | 2023-01-11T10:52:21Z | 2023-01-11T13:44:28Z | 2023-01-11T13:44:28Z | 2023-01-11T14:18:35Z |
CLN: Remove 3rd party warning filters | diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py
index 67e00dde5498b..cb66d1a422811 100644
--- a/pandas/io/parquet.py
+++ b/pandas/io/parquet.py
@@ -285,9 +285,6 @@ def write(
**kwargs,
) -> None:
self.validate_dataframe(df)
- # thriftpy/protocol/compact.py:339:
- # DeprecationWarning: tostring() is deprecated.
- # Use tobytes() instead.
if "partition_on" in kwargs and partition_cols is not None:
raise ValueError(
diff --git a/pandas/tests/frame/test_unary.py b/pandas/tests/frame/test_unary.py
index 9caadd0998a26..9d38f621c0505 100644
--- a/pandas/tests/frame/test_unary.py
+++ b/pandas/tests/frame/test_unary.py
@@ -114,7 +114,10 @@ def test_pos_object(self, df):
[
pytest.param(
pd.DataFrame({"a": ["a", "b"]}),
- marks=[pytest.mark.filterwarnings("ignore")],
+ # filterwarnings removable once min numpy version is 1.25
+ marks=[
+ pytest.mark.filterwarnings("ignore:Applying:DeprecationWarning")
+ ],
),
],
)
diff --git a/pandas/tests/io/__init__.py b/pandas/tests/io/__init__.py
index 15294fd0cabbc..e69de29bb2d1d 100644
--- a/pandas/tests/io/__init__.py
+++ b/pandas/tests/io/__init__.py
@@ -1,20 +0,0 @@
-import pytest
-
-pytestmark = [
- # fastparquet
- pytest.mark.filterwarnings(
- "ignore:PY_SSIZE_T_CLEAN will be required.*:DeprecationWarning"
- ),
- pytest.mark.filterwarnings(
- r"ignore:`np\.bool` is a deprecated alias:DeprecationWarning"
- ),
- # xlrd
- pytest.mark.filterwarnings(
- "ignore:This method will be removed in future versions:DeprecationWarning"
- ),
- pytest.mark.filterwarnings(
- "ignore:This method will be removed in future versions. "
- r"Use 'tree.iter\(\)' or 'list\(tree.iter\(\)\)' instead."
- ":PendingDeprecationWarning"
- ),
-]
diff --git a/pandas/tests/io/excel/__init__.py b/pandas/tests/io/excel/__init__.py
index 419761cbe1d6d..e69de29bb2d1d 100644
--- a/pandas/tests/io/excel/__init__.py
+++ b/pandas/tests/io/excel/__init__.py
@@ -1,12 +0,0 @@
-import pytest
-
-pytestmark = [
- pytest.mark.filterwarnings(
- # Looks like tree.getiterator is deprecated in favor of tree.iter
- "ignore:This method will be removed in future versions:"
- "PendingDeprecationWarning"
- ),
- pytest.mark.filterwarnings(
- "ignore:This method will be removed in future versions:DeprecationWarning"
- ),
-]
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 430f8b4fd5d69..5899125ca2904 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -42,7 +42,6 @@
"openpyxl",
marks=[
td.skip_if_no("openpyxl"),
- pytest.mark.filterwarnings("ignore:.*html argument"),
],
),
pytest.param(
diff --git a/pandas/tests/io/pytables/__init__.py b/pandas/tests/io/pytables/__init__.py
index 68c89658c137f..e69de29bb2d1d 100644
--- a/pandas/tests/io/pytables/__init__.py
+++ b/pandas/tests/io/pytables/__init__.py
@@ -1,14 +0,0 @@
-import pytest
-
-pytestmark = [
- # pytables https://github.com/PyTables/PyTables/issues/822
- pytest.mark.filterwarnings(
- "ignore:a closed node found in the registry:UserWarning"
- ),
- pytest.mark.filterwarnings(
- r"ignore:`np\.object` is a deprecated alias.*:DeprecationWarning"
- ),
- pytest.mark.filterwarnings(
- r"ignore:`np\.bool` is a deprecated alias.*:DeprecationWarning"
- ),
-]
diff --git a/pandas/tests/io/pytables/test_categorical.py b/pandas/tests/io/pytables/test_categorical.py
index c70e49cfb0bde..7c2ab9b4f6ec0 100644
--- a/pandas/tests/io/pytables/test_categorical.py
+++ b/pandas/tests/io/pytables/test_categorical.py
@@ -16,10 +16,6 @@
pytestmark = [
pytest.mark.single_cpu,
- # pytables https://github.com/PyTables/PyTables/issues/822
- pytest.mark.filterwarnings(
- "ignore:a closed node found in the registry:UserWarning"
- ),
]
diff --git a/pandas/tests/io/pytables/test_subclass.py b/pandas/tests/io/pytables/test_subclass.py
index 27843415f367e..823d2875c5417 100644
--- a/pandas/tests/io/pytables/test_subclass.py
+++ b/pandas/tests/io/pytables/test_subclass.py
@@ -13,9 +13,6 @@
)
pytest.importorskip("tables")
-pytestmark = pytest.mark.filterwarnings(
- "ignore:`np.object` is a deprecated alias:DeprecationWarning"
-)
class TestHDFStoreSubclass:
diff --git a/pandas/tests/io/sas/test_sas7bdat.py b/pandas/tests/io/sas/test_sas7bdat.py
index 325397d096745..348d2382976c3 100644
--- a/pandas/tests/io/sas/test_sas7bdat.py
+++ b/pandas/tests/io/sas/test_sas7bdat.py
@@ -38,7 +38,6 @@ def data_test_ix(request, dirpath):
# https://github.com/cython/cython/issues/1720
-@pytest.mark.filterwarnings("ignore:can't resolve package:ImportWarning")
class TestSAS7BDAT:
@pytest.mark.slow
def test_from_file(self, dirpath, data_test_ix):
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
index 2172a4bf839fb..5ade1e0913804 100644
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -50,7 +50,6 @@ def __fspath__(self):
# https://github.com/cython/cython/issues/1720
-@pytest.mark.filterwarnings("ignore:can't resolve package:ImportWarning")
class TestCommonIOCapabilities:
data1 = """index,A,B,C,D
foo,2,3,4,5
@@ -317,9 +316,6 @@ def test_read_expands_user_home_dir(
),
],
)
- @pytest.mark.filterwarnings( # pytables np.object_ usage
- "ignore:`np.object` is a deprecated alias:DeprecationWarning"
- )
def test_read_fspath_all(self, reader, module, path, datapath):
pytest.importorskip(module)
path = datapath(*path)
@@ -372,9 +368,6 @@ def test_write_fspath_all(self, writer_name, writer_kwargs, module):
expected = f_path.read()
assert result == expected
- @pytest.mark.filterwarnings( # pytables np.object_ usage
- "ignore:`np.object` is a deprecated alias:DeprecationWarning"
- )
def test_write_fspath_hdf5(self):
# Same test as write_fspath_all, except HDF5 files aren't
# necessarily byte-for-byte identical for a given dataframe, so we'll
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index 398e2ccb09df2..12a3801ef1344 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -3,10 +3,7 @@
from io import BytesIO
import os
import pathlib
-from warnings import (
- catch_warnings,
- filterwarnings,
-)
+from warnings import catch_warnings
import numpy as np
import pytest
@@ -40,13 +37,7 @@
_HAVE_PYARROW = False
try:
- with catch_warnings():
- # `np.bool` is a deprecated alias...
- filterwarnings("ignore", "`np.bool`", category=DeprecationWarning)
- # accessing pd.Int64Index in pd namespace
- filterwarnings("ignore", ".*Int64Index.*", category=FutureWarning)
-
- import fastparquet
+ import fastparquet
_HAVE_FASTPARQUET = True
except ImportError:
diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py
index 07a028a19d7f9..2c3617b7f3995 100644
--- a/pandas/tests/io/test_pickle.py
+++ b/pandas/tests/io/test_pickle.py
@@ -24,10 +24,7 @@
import shutil
import tarfile
import uuid
-from warnings import (
- catch_warnings,
- simplefilter,
-)
+from warnings import catch_warnings
import zipfile
import numpy as np
@@ -132,49 +129,46 @@ def test_pickles(legacy_pickle):
if not is_platform_little_endian():
pytest.skip("known failure on non-little endian")
- with catch_warnings(record=True):
- simplefilter("ignore")
-
- data = pd.read_pickle(legacy_pickle)
-
- for typ, dv in data.items():
- for dt, result in dv.items():
- expected = data[typ][dt]
-
- if typ == "series" and dt == "ts":
- # GH 7748
- tm.assert_series_equal(result, expected)
- assert result.index.freq == expected.index.freq
- assert not result.index.freq.normalize
- tm.assert_series_equal(result > 0, expected > 0)
-
- # GH 9291
- freq = result.index.freq
- assert freq + Day(1) == Day(2)
-
- res = freq + pd.Timedelta(hours=1)
- assert isinstance(res, pd.Timedelta)
- assert res == pd.Timedelta(days=1, hours=1)
-
- res = freq + pd.Timedelta(nanoseconds=1)
- assert isinstance(res, pd.Timedelta)
- assert res == pd.Timedelta(days=1, nanoseconds=1)
- elif typ == "index" and dt == "period":
- tm.assert_index_equal(result, expected)
- assert isinstance(result.freq, MonthEnd)
- assert result.freq == MonthEnd()
- assert result.freqstr == "M"
- tm.assert_index_equal(result.shift(2), expected.shift(2))
- elif typ == "series" and dt in ("dt_tz", "cat"):
- tm.assert_series_equal(result, expected)
- elif typ == "frame" and dt in (
- "dt_mixed_tzs",
- "cat_onecol",
- "cat_and_float",
- ):
- tm.assert_frame_equal(result, expected)
- else:
- compare_element(result, expected, typ)
+ data = pd.read_pickle(legacy_pickle)
+
+ for typ, dv in data.items():
+ for dt, result in dv.items():
+ expected = data[typ][dt]
+
+ if typ == "series" and dt == "ts":
+ # GH 7748
+ tm.assert_series_equal(result, expected)
+ assert result.index.freq == expected.index.freq
+ assert not result.index.freq.normalize
+ tm.assert_series_equal(result > 0, expected > 0)
+
+ # GH 9291
+ freq = result.index.freq
+ assert freq + Day(1) == Day(2)
+
+ res = freq + pd.Timedelta(hours=1)
+ assert isinstance(res, pd.Timedelta)
+ assert res == pd.Timedelta(days=1, hours=1)
+
+ res = freq + pd.Timedelta(nanoseconds=1)
+ assert isinstance(res, pd.Timedelta)
+ assert res == pd.Timedelta(days=1, nanoseconds=1)
+ elif typ == "index" and dt == "period":
+ tm.assert_index_equal(result, expected)
+ assert isinstance(result.freq, MonthEnd)
+ assert result.freq == MonthEnd()
+ assert result.freqstr == "M"
+ tm.assert_index_equal(result.shift(2), expected.shift(2))
+ elif typ == "series" and dt in ("dt_tz", "cat"):
+ tm.assert_series_equal(result, expected)
+ elif typ == "frame" and dt in (
+ "dt_mixed_tzs",
+ "cat_onecol",
+ "cat_and_float",
+ ):
+ tm.assert_frame_equal(result, expected)
+ else:
+ compare_element(result, expected, typ)
def python_pickler(obj, path):
diff --git a/pandas/tests/plotting/frame/test_frame_color.py b/pandas/tests/plotting/frame/test_frame_color.py
index 925d9ca9e2fa2..2d8b3b14c8c68 100644
--- a/pandas/tests/plotting/frame/test_frame_color.py
+++ b/pandas/tests/plotting/frame/test_frame_color.py
@@ -1,6 +1,5 @@
""" Test cases for DataFrame.plot """
import re
-import warnings
import numpy as np
import pytest
@@ -18,23 +17,13 @@
@td.skip_if_no_mpl
class TestDataFrameColor(TestPlotBase):
- def test_mpl2_color_cycle_str(self):
+ @pytest.mark.parametrize(
+ "color", ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
+ )
+ def test_mpl2_color_cycle_str(self, color):
# GH 15516
df = DataFrame(np.random.randn(10, 3), columns=["a", "b", "c"])
- colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always", "MatplotlibDeprecationWarning")
-
- for color in colors:
- _check_plot_works(df.plot, color=color)
-
- # if warning is raised, check that it is the exact problematic one
- # GH 36972
- if w:
- match = "Support for uppercase single-letter colors is deprecated"
- warning_message = str(w[0].message)
- msg = "MatplotlibDeprecationWarning related to CN colors was raised"
- assert match not in warning_message, msg
+ _check_plot_works(df.plot, color=color)
def test_color_single_series_list(self):
# GH 3486
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index 5192b3d4cabf8..fea10075a0ace 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -18,11 +18,6 @@
)
import pandas._testing as tm
-# xarray, fsspec, fastparquet all produce these
-pytestmark = pytest.mark.filterwarnings(
- "ignore:distutils Version classes are deprecated.*:DeprecationWarning"
-)
-
def import_module(name):
# we *only* want to skip if the module is truly not available
@@ -148,12 +143,6 @@ def test_oo_optimized_datetime_index_unpickle():
@pytest.mark.network
@tm.network
-# Cython import warning
-@pytest.mark.filterwarnings("ignore:can't:ImportWarning")
-@pytest.mark.filterwarnings(
- # patsy needs to update their imports
- "ignore:Using or importing the ABCs from 'collections:DeprecationWarning"
-)
def test_statsmodels():
statsmodels = import_module("statsmodels") # noqa:F841
@@ -164,8 +153,6 @@ def test_statsmodels():
smf.ols("Lottery ~ Literacy + np.log(Pop1831)", data=df).fit()
-# Cython import warning
-@pytest.mark.filterwarnings("ignore:can't:ImportWarning")
def test_scikit_learn():
sklearn = import_module("sklearn") # noqa:F841
@@ -180,10 +167,8 @@ def test_scikit_learn():
clf.predict(digits.data[-1:])
-# Cython import warning and traitlets
@pytest.mark.network
@tm.network
-@pytest.mark.filterwarnings("ignore")
def test_seaborn():
seaborn = import_module("seaborn")
@@ -210,8 +195,6 @@ def test_pandas_datareader():
pandas_datareader.DataReader("F", "quandl", "2017-01-01", "2017-02-01")
-# Cython import warning
-@pytest.mark.filterwarnings("ignore:can't resolve:ImportWarning")
def test_pyarrow(df):
pyarrow = import_module("pyarrow")
diff --git a/pandas/tests/util/test_show_versions.py b/pandas/tests/util/test_show_versions.py
index 439971084fba8..8ff78cc073acf 100644
--- a/pandas/tests/util/test_show_versions.py
+++ b/pandas/tests/util/test_show_versions.py
@@ -2,8 +2,6 @@
import os
import re
-import pytest
-
from pandas.util._print_versions import (
_get_dependency_info,
_get_sys_info,
@@ -12,19 +10,6 @@
import pandas as pd
-@pytest.mark.filterwarnings(
- # openpyxl
- "ignore:defusedxml.lxml is no longer supported:DeprecationWarning"
-)
-@pytest.mark.filterwarnings(
- # html5lib
- "ignore:Using or importing the ABCs from:DeprecationWarning"
-)
-@pytest.mark.filterwarnings(
- # 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/tests/window/__init__.py b/pandas/tests/window/__init__.py
index 757bdfe755038..e69de29bb2d1d 100644
--- a/pandas/tests/window/__init__.py
+++ b/pandas/tests/window/__init__.py
@@ -1,8 +0,0 @@
-import pytest
-
-pytestmark = [
- # 2021-02-01 needed until numba updates their usage
- pytest.mark.filterwarnings(
- r"ignore:`np\.int` is a deprecated alias:DeprecationWarning"
- ),
-]
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index 59d5d6649c2a5..5bc55ee789fe6 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -32,7 +32,6 @@ def test_foo():
Callable,
Generator,
)
-import warnings
import numpy as np
import pytest
@@ -67,41 +66,17 @@ def safe_import(mod_name: str, min_version: str | None = None):
object
The imported module if successful, or False
"""
- with warnings.catch_warnings():
- # Suppress warnings that we can't do anything about,
- # e.g. from aiohttp
- warnings.filterwarnings(
- "ignore",
- category=DeprecationWarning,
- module="aiohttp",
- message=".*decorator is deprecated since Python 3.8.*",
- )
-
- # fastparquet import accesses pd.Int64Index
- warnings.filterwarnings(
- "ignore",
- category=FutureWarning,
- module="fastparquet",
- message=".*Int64Index.*",
- )
-
- warnings.filterwarnings(
- "ignore",
- category=DeprecationWarning,
- message="distutils Version classes are deprecated.*",
- )
-
- try:
- mod = __import__(mod_name)
- except ImportError:
+ try:
+ mod = __import__(mod_name)
+ except ImportError:
+ return False
+ except SystemError:
+ # TODO: numba is incompatible with numpy 1.24+.
+ # Once that's fixed, this block should be removed.
+ if mod_name == "numba":
return False
- except SystemError:
- # TODO: numba is incompatible with numpy 1.24+.
- # Once that's fixed, this block should be removed.
- if mod_name == "numba":
- return False
- else:
- raise
+ else:
+ raise
if not min_version:
return mod
diff --git a/pyproject.toml b/pyproject.toml
index 9ef722d95c8b3..0308f86beb0d4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -369,6 +369,15 @@ doctest_optionflags = [
filterwarnings = [
# Will be fixed in numba 0.56: https://github.com/numba/numba/issues/7758
"ignore:`np.MachAr` is deprecated:DeprecationWarning:numba",
+ "ignore:.*urllib3:DeprecationWarning:botocore",
+ "ignore:Setuptools is replacing distutils.:UserWarning:_distutils_hack",
+ # https://github.com/PyTables/PyTables/issues/822
+ "ignore:a closed node found in the registry:UserWarning:tables",
+ "ignore:`np.object` is a deprecated:DeprecationWarning:tables",
+ "ignore:tostring:DeprecationWarning:tables",
+ "ignore:distutils Version classes are deprecated:DeprecationWarning:numexpr",
+ "ignore:distutils Version classes are deprecated:DeprecationWarning:fastparquet",
+ "ignore:distutils Version classes are deprecated:DeprecationWarning:fsspec",
]
junit_family = "xunit2"
markers = [
| Checking if any of these are still needed and if so probably moving them to pyproject.toml | https://api.github.com/repos/pandas-dev/pandas/pulls/50674 | 2023-01-11T02:46:34Z | 2023-01-13T00:25:44Z | 2023-01-13T00:25:44Z | 2023-01-13T00:25:48Z |
BUG: is_[int|float]_dtypes functions not recognizing ArrowDtype | diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst
index 3ac004ef335ac..530d5dd00d1b2 100644
--- a/doc/source/whatsnew/v2.0.0.rst
+++ b/doc/source/whatsnew/v2.0.0.rst
@@ -1049,6 +1049,7 @@ ExtensionArray
- Bug when concatenating an empty DataFrame with an ExtensionDtype to another DataFrame with the same ExtensionDtype, the resulting dtype turned into object (:issue:`48510`)
- Bug in :meth:`array.PandasArray.to_numpy` raising with ``NA`` value when ``na_value`` is specified (:issue:`40638`)
- Bug in :meth:`api.types.is_numeric_dtype` where a custom :class:`ExtensionDtype` would not return ``True`` if ``_is_numeric`` returned ``True`` (:issue:`50563`)
+- Bug in :meth:`api.types.is_integer_dtype`, :meth:`api.types.is_unsigned_integer_dtype`, :meth:`api.types.is_signed_integer_dtype`, :meth:`api.types.is_float_dtype` where a custom :class:`ExtensionDtype` would not return ``True`` if ``kind`` returned the corresponding NumPy type (:issue:`50667`)
Styler
^^^^^^
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index aae815bb68e05..4a8f1292ecdef 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -690,7 +690,11 @@ def is_integer_dtype(arr_or_dtype) -> bool:
>>> is_integer_dtype(pd.Index([1, 2.])) # float
False
"""
- return _is_dtype_type(arr_or_dtype, classes_and_not_datetimelike(np.integer))
+ return _is_dtype_type(
+ arr_or_dtype, classes_and_not_datetimelike(np.integer)
+ ) or _is_dtype(
+ arr_or_dtype, lambda typ: isinstance(typ, ExtensionDtype) and typ.kind in "iu"
+ )
def is_signed_integer_dtype(arr_or_dtype) -> bool:
@@ -744,7 +748,11 @@ def is_signed_integer_dtype(arr_or_dtype) -> bool:
>>> is_signed_integer_dtype(np.array([1, 2], dtype=np.uint32)) # unsigned
False
"""
- return _is_dtype_type(arr_or_dtype, classes_and_not_datetimelike(np.signedinteger))
+ return _is_dtype_type(
+ arr_or_dtype, classes_and_not_datetimelike(np.signedinteger)
+ ) or _is_dtype(
+ arr_or_dtype, lambda typ: isinstance(typ, ExtensionDtype) and typ.kind == "i"
+ )
def is_unsigned_integer_dtype(arr_or_dtype) -> bool:
@@ -791,6 +799,8 @@ def is_unsigned_integer_dtype(arr_or_dtype) -> bool:
"""
return _is_dtype_type(
arr_or_dtype, classes_and_not_datetimelike(np.unsignedinteger)
+ ) or _is_dtype(
+ arr_or_dtype, lambda typ: isinstance(typ, ExtensionDtype) and typ.kind == "u"
)
@@ -1234,7 +1244,9 @@ def is_float_dtype(arr_or_dtype) -> bool:
>>> is_float_dtype(pd.Index([1, 2.]))
True
"""
- return _is_dtype_type(arr_or_dtype, classes(np.floating))
+ return _is_dtype_type(arr_or_dtype, classes(np.floating)) or _is_dtype(
+ arr_or_dtype, lambda typ: isinstance(typ, ExtensionDtype) and typ.kind in "f"
+ )
def is_bool_dtype(arr_or_dtype) -> bool:
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index c02fa0aecdacc..78c49ae066288 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -39,7 +39,11 @@
import pandas._testing as tm
from pandas.api.types import (
is_bool_dtype,
+ is_float_dtype,
+ is_integer_dtype,
is_numeric_dtype,
+ is_signed_integer_dtype,
+ is_unsigned_integer_dtype,
)
from pandas.tests.extension import base
@@ -1446,6 +1450,39 @@ def test_is_numeric_dtype(data):
assert not is_numeric_dtype(data)
+def test_is_integer_dtype(data):
+ # GH 50667
+ pa_type = data.dtype.pyarrow_dtype
+ if pa.types.is_integer(pa_type):
+ assert is_integer_dtype(data)
+ else:
+ assert not is_integer_dtype(data)
+
+
+def test_is_signed_integer_dtype(data):
+ pa_type = data.dtype.pyarrow_dtype
+ if pa.types.is_signed_integer(pa_type):
+ assert is_signed_integer_dtype(data)
+ else:
+ assert not is_signed_integer_dtype(data)
+
+
+def test_is_unsigned_integer_dtype(data):
+ pa_type = data.dtype.pyarrow_dtype
+ if pa.types.is_unsigned_integer(pa_type):
+ assert is_unsigned_integer_dtype(data)
+ else:
+ assert not is_unsigned_integer_dtype(data)
+
+
+def test_is_float_dtype(data):
+ pa_type = data.dtype.pyarrow_dtype
+ if pa.types.is_floating(pa_type):
+ assert is_float_dtype(data)
+ else:
+ assert not is_float_dtype(data)
+
+
def test_pickle_roundtrip(data):
# GH 42600
expected = pd.Series(data)
| - [ ] closes #50667 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Went ahead and fixed the other numeric-like dtype checkers
| https://api.github.com/repos/pandas-dev/pandas/pulls/50672 | 2023-01-10T23:59:21Z | 2023-01-11T12:53:03Z | 2023-01-11T12:53:03Z | 2023-01-11T16:27:40Z |
TST: Add a test for fillna in PeriodArray | diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py
index 47703b294c2b1..9fded26c37caf 100644
--- a/pandas/tests/series/methods/test_fillna.py
+++ b/pandas/tests/series/methods/test_fillna.py
@@ -21,6 +21,7 @@
isna,
)
import pandas._testing as tm
+from pandas.core.arrays import period_array
class TestSeriesFillNA:
@@ -946,3 +947,26 @@ def test_datetime64tz_fillna_round_issue(self):
)
tm.assert_series_equal(filled, expected)
+
+ def test_fillna_parr(self):
+ # GH-24537
+ dti = date_range(
+ Timestamp.max - Timedelta(nanoseconds=10), periods=5, freq="ns"
+ )
+ ser = Series(dti.to_period("ns"))
+ ser[2] = NaT
+ arr = period_array(
+ [
+ Timestamp("2262-04-11 23:47:16.854775797"),
+ Timestamp("2262-04-11 23:47:16.854775798"),
+ Timestamp("2262-04-11 23:47:16.854775798"),
+ Timestamp("2262-04-11 23:47:16.854775800"),
+ Timestamp("2262-04-11 23:47:16.854775801"),
+ ],
+ freq="ns",
+ )
+ expected = Series(arr)
+
+ filled = ser.fillna(method="pad")
+
+ tm.assert_series_equal(filled, expected)
| - [x] closes #24537
| https://api.github.com/repos/pandas-dev/pandas/pulls/50671 | 2023-01-10T23:01:43Z | 2023-01-15T21:13:57Z | 2023-01-15T21:13:57Z | 2023-01-15T21:17:49Z |
DOC: Fix name in interpolate plot. | diff --git a/doc/source/missing_data.rst b/doc/source/missing_data.rst
index e7966aa71486c..3e2183b072ac6 100644
--- a/doc/source/missing_data.rst
+++ b/doc/source/missing_data.rst
@@ -375,11 +375,11 @@ Compare several methods:
np.random.seed(2)
ser = Series(np.arange(1, 10.1, .25)**2 + np.random.randn(37))
- bad = np.array([4, 13, 14, 15, 16, 17, 18, 20, 29, 34, 35, 36])
+ bad = np.array([4, 13, 14, 15, 16, 17, 18, 20, 29])
ser[bad] = np.nan
methods = ['linear', 'quadratic', 'cubic']
- df = DataFrame({m: s.interpolate(method=m) for m in methods})
+ df = DataFrame({m: ser.interpolate(method=m) for m in methods})
@savefig compare_interpolations.png
df.plot()
| https://api.github.com/repos/pandas-dev/pandas/pulls/5165 | 2013-10-09T23:03:25Z | 2013-10-09T23:39:21Z | 2013-10-09T23:39:21Z | 2017-04-05T02:05:41Z | |
ENH: add to_frame method to Series | diff --git a/doc/source/api.rst b/doc/source/api.rst
index 8772b858de2cc..dfb562bcc3298 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -438,6 +438,7 @@ Serialization / IO / Conversion
Series.to_pickle
Series.to_csv
Series.to_dict
+ Series.to_frame
Series.to_sparse
Series.to_string
Series.to_clipboard
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index c6a4c280ca4bb..946a45b7dbe7c 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -492,6 +492,8 @@ Enhancements
- DatetimeIndex is now in the API documentation, see :ref:`here<api.datetimeindex>`
- :meth:`~pandas.io.json.json_normalize` is a new method to allow you to create a flat table
from semi-structured JSON data. :ref:`See the docs<io.json_normalize>` (:issue:`1067`)
+ - ``Series`` now supports ``to_frame`` method to convert it to a single-column DataFrame
+ (:issue:`5164`)
.. _whatsnew_0130.experimental:
diff --git a/pandas/core/series.py b/pandas/core/series.py
index d185939d6abc9..34b3634996f4b 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -827,12 +827,7 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False):
raise TypeError('Cannot reset_index inplace on a Series '
'to create a DataFrame')
else:
- from pandas.core.frame import DataFrame
- if name is None:
- df = DataFrame(self)
- else:
- df = DataFrame({name: self})
-
+ df = self.to_frame(name)
return df.reset_index(level=level, drop=drop)
def __unicode__(self):
@@ -1028,6 +1023,27 @@ def to_dict(self):
"""
return dict(compat.iteritems(self))
+ def to_frame(self, name=None):
+ """
+ Convert Series to DataFrame
+
+ Parameters
+ ----------
+ name : object, default None
+ The passed name should substitute for the series name (if it has one).
+
+ Returns
+ -------
+ data_frame : DataFrame
+ """
+ from pandas.core.frame import DataFrame
+ if name is None:
+ df = DataFrame(self)
+ else:
+ df = DataFrame({name: self})
+
+ return df
+
def to_sparse(self, kind='block', fill_value=None):
"""
Convert Series to SparseSeries
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 8abc068fd6d24..22d8d79ecc82f 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -30,6 +30,7 @@
from pandas import compat
from pandas.util.testing import (assert_series_equal,
assert_almost_equal,
+ assert_frame_equal,
ensure_clean)
import pandas.util.testing as tm
@@ -3606,6 +3607,21 @@ def test_tolist(self):
rs = s.tolist()
self.assertEqual(self.ts.index[0], rs[0])
+ def test_to_frame(self):
+ self.ts.name = None
+ rs = self.ts.to_frame()
+ xp = pd.DataFrame(self.ts.values, index=self.ts.index)
+ assert_frame_equal(rs, xp)
+
+ self.ts.name = 'testname'
+ rs = self.ts.to_frame()
+ xp = pd.DataFrame(dict(testname=self.ts.values), index=self.ts.index)
+ assert_frame_equal(rs, xp)
+
+ rs = self.ts.to_frame(name='testdifferent')
+ xp = pd.DataFrame(dict(testdifferent=self.ts.values), index=self.ts.index)
+ assert_frame_equal(rs, xp)
+
def test_to_dict(self):
self.assert_(np.array_equal(Series(self.ts.to_dict()), self.ts))
| Adding a method to Series to promote it to a DataFrame. I've wished this existed so that when a method returns a series, and you could easily promote it to a DataFrame so that it's easier to add columns to it.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5164 | 2013-10-09T20:02:07Z | 2013-10-10T13:00:50Z | 2013-10-10T13:00:50Z | 2014-06-13T06:38:18Z |
DOC: add DataFrame et al class docstring to api docs | diff --git a/doc/source/_templates/autosummary/class.rst b/doc/source/_templates/autosummary/class.rst
new file mode 100644
index 0000000000000..e9af7e8df8bab
--- /dev/null
+++ b/doc/source/_templates/autosummary/class.rst
@@ -0,0 +1,33 @@
+{% extends "!autosummary/class.rst" %}
+
+{% block methods %}
+{% if methods %}
+
+..
+ HACK -- the point here is that we don't want this to appear in the output, but the autosummary should still generate the pages.
+ .. autosummary::
+ :toctree:
+ {% for item in all_methods %}
+ {%- if not item.startswith('_') or item in ['__call__'] %}
+ {{ name }}.{{ item }}
+ {%- endif -%}
+ {%- endfor %}
+
+{% endif %}
+{% endblock %}
+
+{% block attributes %}
+{% if attributes %}
+
+..
+ HACK -- the point here is that we don't want this to appear in the output, but the autosummary should still generate the pages.
+ .. autosummary::
+ :toctree:
+ {% for item in all_attributes %}
+ {%- if not item.startswith('_') %}
+ {{ name }}.{{ item }}
+ {%- endif -%}
+ {%- endfor %}
+
+{% endif %}
+{% endblock %}
diff --git a/doc/source/api.rst b/doc/source/api.rst
index 2e817e9d19c3f..46d77d0dcceb7 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -206,6 +206,13 @@ Exponentially-weighted moving window functions
Series
------
+Constructor
+~~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Series
+
Attributes and underlying data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**Axes**
@@ -219,13 +226,11 @@ Attributes and underlying data
Series.isnull
Series.notnull
-Conversion / Constructors
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
+Conversion
+~~~~~~~~~~
.. autosummary::
:toctree: generated/
- Series.__init__
Series.astype
Series.copy
Series.isnull
@@ -418,6 +423,13 @@ Serialization / IO / Conversion
DataFrame
---------
+Constructor
+~~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ DataFrame
+
Attributes and underlying data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**Axes**
@@ -436,12 +448,11 @@ Attributes and underlying data
DataFrame.ndim
DataFrame.shape
-Conversion / Constructors
-~~~~~~~~~~~~~~~~~~~~~~~~~
+Conversion
+~~~~~~~~~~
.. autosummary::
:toctree: generated/
- DataFrame.__init__
DataFrame.astype
DataFrame.convert_objects
DataFrame.copy
@@ -665,6 +676,13 @@ Serialization / IO / Conversion
Panel
------
+Constructor
+~~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Panel
+
Attributes and underlying data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**Axes**
@@ -681,12 +699,11 @@ Attributes and underlying data
Panel.ndim
Panel.shape
-Conversion / Constructors
-~~~~~~~~~~~~~~~~~~~~~~~~~
+Conversion
+~~~~~~~~~~
.. autosummary::
:toctree: generated/
- Panel.__init__
Panel.astype
Panel.copy
Panel.isnull
@@ -853,6 +870,11 @@ Index
**Many of these methods or variants thereof are available on the objects that contain an index (Series/Dataframe)
and those should most likely be used before calling these methods directly.**
+.. autosummary::
+ :toctree: generated/
+
+ Index
+
Modifying and Computations
~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
@@ -934,6 +956,11 @@ Properties
DatetimeIndex
-------------
+.. autosummary::
+ :toctree: generated/
+
+ DatetimeIndex
+
Time/Date Components
~~~~~~~~~~~~~~~~~~~~
* **year**
diff --git a/doc/source/conf.py b/doc/source/conf.py
index 99d1703b9ca34..a500289b27ab1 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -51,7 +51,7 @@
]
# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates', '_templates/autosummary']
+templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
diff --git a/doc/sphinxext/docscrape.py b/doc/sphinxext/docscrape.py
index 9a8ac59b32714..a8323c2c74361 100755
--- a/doc/sphinxext/docscrape.py
+++ b/doc/sphinxext/docscrape.py
@@ -8,7 +8,7 @@
import pydoc
from StringIO import StringIO
from warnings import warn
-
+import collections
class Reader(object):
@@ -473,6 +473,8 @@ def __str__(self):
class ClassDoc(NumpyDocString):
+ extra_public_methods = ['__call__']
+
def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,
config={}):
if not inspect.isclass(cls) and cls is not None:
@@ -502,12 +504,16 @@ def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,
def methods(self):
if self._cls is None:
return []
- return [name for name, func in inspect.getmembers(self._cls)
- if not name.startswith('_') and callable(func)]
+ return [name for name,func in inspect.getmembers(self._cls)
+ if ((not name.startswith('_')
+ or name in self.extra_public_methods)
+ and isinstance(func, collections.Callable))]
@property
def properties(self):
if self._cls is None:
return []
- return [name for name, func in inspect.getmembers(self._cls)
- if not name.startswith('_') and func is None]
+ return [name for name,func in inspect.getmembers(self._cls)
+ if not name.startswith('_') and
+ (func is None or isinstance(func, property) or
+ inspect.isgetsetdescriptor(func))]
\ No newline at end of file
| closes #4790
I copied the approach of numpy: extending the autosummary class template to automatically generate all method stub files:
- https://github.com/numpy/numpy/blob/master/doc/source/_templates/autosummary/class.rst
- example output: http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html
I added `DataFrame`, `Series`, `Panel`, `Index` and `DatetimeIndex`. Others? (eg `Timestamp`) Or too much?
The only issue at the moment is that normally also a list of attributes should be included, which is not the case (only a list of methods)
| https://api.github.com/repos/pandas-dev/pandas/pulls/5160 | 2013-10-08T20:54:57Z | 2013-10-14T18:18:38Z | 2013-10-14T18:18:38Z | 2014-06-18T10:12:24Z |
API/PERF: restore auto-boxing on isnull/notnull for Series (w/o copy) preserves perf gains | diff --git a/pandas/core/common.py b/pandas/core/common.py
index 009de0395f361..a417e00af5d3e 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -202,6 +202,11 @@ def _isnull_ndarraylike(obj):
else:
result = np.isnan(values)
+ # box
+ if isinstance(obj, ABCSeries):
+ from pandas import Series
+ result = Series(result, index=obj.index, name=obj.name, copy=False)
+
return result
@@ -226,6 +231,11 @@ def _isnull_ndarraylike_old(obj):
else:
result = -np.isfinite(values)
+ # box
+ if isinstance(obj, ABCSeries):
+ from pandas import Series
+ result = Series(result, index=obj.index, name=obj.name, copy=False)
+
return result
diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py
index 5efc22ef927d5..68195fb3d6ec5 100644
--- a/pandas/tests/test_common.py
+++ b/pandas/tests/test_common.py
@@ -66,7 +66,7 @@ def test_notnull():
with cf.option_context("mode.use_inf_as_null", False):
for s in [tm.makeFloatSeries(),tm.makeStringSeries(),
tm.makeObjectSeries(),tm.makeTimeSeries(),tm.makePeriodSeries()]:
- assert(isinstance(isnull(s), np.ndarray))
+ assert(isinstance(isnull(s), Series))
def test_isnull():
assert not isnull(1.)
@@ -77,7 +77,7 @@ def test_isnull():
for s in [tm.makeFloatSeries(),tm.makeStringSeries(),
tm.makeObjectSeries(),tm.makeTimeSeries(),tm.makePeriodSeries()]:
- assert(isinstance(isnull(s), np.ndarray))
+ assert(isinstance(isnull(s), Series))
# call on DataFrame
df = DataFrame(np.random.randn(10, 5))
| restore API before #5154
boxing via null/isnull is same as 0.12
(aside from now `isnull/notnull` are now available on `NDFrame` objs as well)
| https://api.github.com/repos/pandas-dev/pandas/pulls/5159 | 2013-10-08T17:05:16Z | 2013-10-08T17:26:45Z | 2013-10-08T17:26:45Z | 2014-07-16T08:33:46Z |
BUG: Fix to_datetime() uncaught error with unparseable inputs #4928 | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 85d9be1295e29..b3668ed80096e 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -575,6 +575,7 @@ Bug Fixes
function (:issue:`5150`).
- Fix a bug with ``NDFrame.replace()`` which made replacement appear as
though it was (incorrectly) using regular expressions (:issue:`5143`).
+ - Fix better error message for to_datetime (:issue:`4928`)
pandas 0.12.0
-------------
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index cda84a99a95db..473ea21da1585 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -931,6 +931,16 @@ def test_to_datetime_types(self):
### expected = to_datetime('2012')
### self.assert_(result == expected)
+ def test_to_datetime_unprocessable_input(self):
+ # GH 4928
+ self.assert_(
+ np.array_equal(
+ to_datetime([1, '1']),
+ np.array([1, '1'], dtype='O')
+ )
+ )
+ self.assertRaises(TypeError, to_datetime, [1, '1'], errors='raise')
+
def test_to_datetime_other_datetime64_units(self):
# 5/25/2012
scalar = np.int64(1337904000000000).view('M8[us]')
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index ff3284b72aecb..3dcfa3621895e 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -1055,7 +1055,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
val = values[i]
if util._checknull(val):
oresult[i] = val
- else:
+ elif util.is_string_object(val):
if len(val) == 0:
# TODO: ??
oresult[i] = 'NaT'
@@ -1069,6 +1069,10 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
raise
return values
# oresult[i] = val
+ else:
+ if raise_:
+ raise
+ return values
return oresult
| closes #4928
| https://api.github.com/repos/pandas-dev/pandas/pulls/5157 | 2013-10-08T14:17:38Z | 2013-10-08T14:30:56Z | 2013-10-08T14:30:56Z | 2014-06-17T13:24:48Z |
PERF: remove auto-boxing on isnull/notnull | diff --git a/doc/source/api.rst b/doc/source/api.rst
index d062512ac3a5b..8772b858de2cc 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -258,6 +258,8 @@ Conversion / Constructors
Series.__init__
Series.astype
Series.copy
+ Series.isnull
+ Series.notnull
Indexing, iteration
~~~~~~~~~~~~~~~~~~~
@@ -472,6 +474,8 @@ Conversion / Constructors
DataFrame.astype
DataFrame.convert_objects
DataFrame.copy
+ DataFrame.isnull
+ DataFrame.notnull
Indexing, iteration
~~~~~~~~~~~~~~~~~~~
@@ -714,6 +718,8 @@ Conversion / Constructors
Panel.__init__
Panel.astype
Panel.copy
+ Panel.isnull
+ Panel.notnull
Getting and setting
~~~~~~~~~~~~~~~~~~~
@@ -976,7 +982,7 @@ Time/Date Components
* **week**: Same as weekofyear
* **dayofweek**: (0=Monday, 6=Sunday)
* **weekday**: (0=Monday, 6=Sunday)
- * **dayofyear**
+ * **dayofyear**
* **quarter**
* **date**: Returns date component of Timestamps
@@ -990,7 +996,7 @@ Selecting
DatetimeIndex.indexer_at_time
DatetimeIndex.indexer_between_time
-
+
Time-specific operations
~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 85d9be1295e29..a1434c0bc927f 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -323,6 +323,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- ``filter`` (also added axis argument to selectively filter on a different axis)
- ``reindex,reindex_axis,take``
- ``truncate`` (moved to become part of ``NDFrame``)
+ - ``isnull/notnull`` now available on ``NDFrame`` objects
- These are API changes which make ``Panel`` more consistent with ``DataFrame``
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 33df305a721a6..009de0395f361 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -182,7 +182,7 @@ def _use_inf_as_null(key):
def _isnull_ndarraylike(obj):
- values = obj
+ values = getattr(obj,'values',obj)
dtype = values.dtype
if dtype.kind in ('O', 'S', 'U'):
@@ -198,22 +198,15 @@ def _isnull_ndarraylike(obj):
elif dtype in _DATELIKE_DTYPES:
# this is the NaT pattern
- v = getattr(values, 'asi8', None)
- if v is None:
- v = values.view('i8')
- result = v == tslib.iNaT
+ result = values.view('i8') == tslib.iNaT
else:
- result = np.isnan(obj)
-
- if isinstance(obj, ABCSeries):
- from pandas import Series
- result = Series(result, index=obj.index, copy=False)
+ result = np.isnan(values)
return result
def _isnull_ndarraylike_old(obj):
- values = obj
+ values = getattr(obj,'values',obj)
dtype = values.dtype
if dtype.kind in ('O', 'S', 'U'):
@@ -229,16 +222,9 @@ def _isnull_ndarraylike_old(obj):
elif dtype in _DATELIKE_DTYPES:
# this is the NaT pattern
- v = getattr(values, 'asi8', None)
- if v is None:
- v = values.view('i8')
- result = v == tslib.iNaT
+ result = values.view('i8') == tslib.iNaT
else:
- result = -np.isfinite(obj)
-
- if isinstance(obj, ABCSeries):
- from pandas import Series
- result = Series(result, index=obj.index, copy=False)
+ result = -np.isfinite(values)
return result
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index bb47709532523..9dadeb4ef6e97 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2019,6 +2019,18 @@ def interpolate(self, to_replace, method='pad', axis=0, inplace=False,
#----------------------------------------------------------------------
# Action Methods
+ def isnull(self):
+ """
+ Return a boolean same-sized object indicating if the values are null
+ """
+ return self.__class__(isnull(self),**self._construct_axes_dict())._propogate_attributes(self)
+
+ def notnull(self):
+ """
+ Return a boolean same-sized object indicating if the values are not null
+ """
+ return self.__class__(notnull(self),**self._construct_axes_dict())._propogate_attributes(self)
+
def clip(self, lower=None, upper=None, out=None):
"""
Trim values at input threshold(s)
diff --git a/pandas/core/ops.py b/pandas/core/ops.py
index a10f3582bfe45..17d524978158b 100644
--- a/pandas/core/ops.py
+++ b/pandas/core/ops.py
@@ -539,7 +539,7 @@ def wrapper(self, other):
# mask out the invalids
if mask.any():
- res[mask.values] = masker
+ res[mask] = masker
return res
return wrapper
diff --git a/pandas/core/series.py b/pandas/core/series.py
index ddbb67cc0c323..d185939d6abc9 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2174,9 +2174,6 @@ def dropna(self):
valid = lambda self: self.dropna()
- isnull = isnull
- notnull = notnull
-
def first_valid_index(self):
"""
Return label for first non-NA/null value
diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py
index 740e3d0821cd7..5efc22ef927d5 100644
--- a/pandas/tests/test_common.py
+++ b/pandas/tests/test_common.py
@@ -64,11 +64,9 @@ def test_notnull():
assert result.sum() == 2
with cf.option_context("mode.use_inf_as_null", False):
- float_series = Series(np.random.randn(5))
- obj_series = Series(np.random.randn(5), dtype=object)
- assert(isinstance(notnull(float_series), Series))
- assert(isinstance(notnull(obj_series), Series))
-
+ for s in [tm.makeFloatSeries(),tm.makeStringSeries(),
+ tm.makeObjectSeries(),tm.makeTimeSeries(),tm.makePeriodSeries()]:
+ assert(isinstance(isnull(s), np.ndarray))
def test_isnull():
assert not isnull(1.)
@@ -77,10 +75,9 @@ def test_isnull():
assert not isnull(np.inf)
assert not isnull(-np.inf)
- float_series = Series(np.random.randn(5))
- obj_series = Series(np.random.randn(5), dtype=object)
- assert(isinstance(isnull(float_series), Series))
- assert(isinstance(isnull(obj_series), Series))
+ for s in [tm.makeFloatSeries(),tm.makeStringSeries(),
+ tm.makeObjectSeries(),tm.makeTimeSeries(),tm.makePeriodSeries()]:
+ assert(isinstance(isnull(s), np.ndarray))
# call on DataFrame
df = DataFrame(np.random.randn(10, 5))
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 2e386a7e2816a..64a45d344f2a9 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -1546,7 +1546,7 @@ def test_set_value_resize(self):
res = self.frame.copy()
res3 = res.set_value('foobar', 'baz', 5)
self.assert_(com.is_float_dtype(res3['baz']))
- self.assert_(isnull(res3['baz'].drop(['foobar'])).values.all())
+ self.assert_(isnull(res3['baz'].drop(['foobar'])).all())
self.assertRaises(ValueError, res3.set_value, 'foobar', 'baz', 'sam')
def test_set_value_with_index_dtype_change(self):
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 7f3ea130259dc..8abc068fd6d24 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -3667,17 +3667,17 @@ def test_valid(self):
def test_isnull(self):
ser = Series([0, 5.4, 3, nan, -0.001])
- assert_series_equal(
- ser.isnull(), Series([False, False, False, True, False]))
+ np.array_equal(
+ ser.isnull(), Series([False, False, False, True, False]).values)
ser = Series(["hi", "", nan])
- assert_series_equal(ser.isnull(), Series([False, False, True]))
+ np.array_equal(ser.isnull(), Series([False, False, True]).values)
def test_notnull(self):
ser = Series([0, 5.4, 3, nan, -0.001])
- assert_series_equal(
- ser.notnull(), Series([True, True, True, False, True]))
+ np.array_equal(
+ ser.notnull(), Series([True, True, True, False, True]).values)
ser = Series(["hi", "", nan])
- assert_series_equal(ser.notnull(), Series([True, True, False]))
+ np.array_equal(ser.notnull(), Series([True, True, False]).values)
def test_shift(self):
shifted = self.ts.shift(1)
| - API/CLN: provide isnull/notnull on NDFrame objects
- PERF: remove auto-boxing on isnull/notnull
related #5135
| https://api.github.com/repos/pandas-dev/pandas/pulls/5154 | 2013-10-08T13:04:26Z | 2013-10-08T13:14:12Z | 2013-10-08T13:14:12Z | 2014-07-16T08:33:41Z |
TST/CI/BUG: fix borked call to read_html testing code | diff --git a/pandas/io/tests/test_html.py b/pandas/io/tests/test_html.py
index 9b0fb1cacfb65..71567fe2e599a 100644
--- a/pandas/io/tests/test_html.py
+++ b/pandas/io/tests/test_html.py
@@ -86,13 +86,14 @@ def test_bs4_version_fails():
class TestReadHtml(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ _skip_if_none_of(('bs4', 'html5lib'))
+
def read_html(self, *args, **kwargs):
kwargs['flavor'] = kwargs.get('flavor', self.flavor)
return read_html(*args, **kwargs)
- def try_skip(self):
- _skip_if_none_of(('bs4', 'html5lib'))
-
def setup_data(self):
self.spam_data = os.path.join(DATA_PATH, 'spam.html')
self.banklist_data = os.path.join(DATA_PATH, 'banklist.html')
@@ -101,7 +102,6 @@ def setup_flavor(self):
self.flavor = 'bs4'
def setUp(self):
- self.try_skip()
self.setup_data()
self.setup_flavor()
@@ -569,32 +569,29 @@ def test_different_number_of_rows(self):
def test_parse_dates_list(self):
df = DataFrame({'date': date_range('1/1/2001', periods=10)})
expected = df.to_html()
- res = read_html(expected, parse_dates=[0], index_col=0)
+ res = self.read_html(expected, parse_dates=[0], index_col=0)
tm.assert_frame_equal(df, res[0])
def test_parse_dates_combine(self):
raw_dates = Series(date_range('1/1/2001', periods=10))
df = DataFrame({'date': raw_dates.map(lambda x: str(x.date())),
'time': raw_dates.map(lambda x: str(x.time()))})
- res = read_html(df.to_html(), parse_dates={'datetime': [1, 2]},
- index_col=1)
+ res = self.read_html(df.to_html(), parse_dates={'datetime': [1, 2]},
+ index_col=1)
newdf = DataFrame({'datetime': raw_dates})
tm.assert_frame_equal(newdf, res[0])
class TestReadHtmlLxml(unittest.TestCase):
- def setUp(self):
- self.try_skip()
+ @classmethod
+ def setUpClass(cls):
+ _skip_if_no('lxml')
def read_html(self, *args, **kwargs):
self.flavor = ['lxml']
- self.try_skip()
kwargs['flavor'] = kwargs.get('flavor', self.flavor)
return read_html(*args, **kwargs)
- def try_skip(self):
- _skip_if_no('lxml')
-
def test_data_fail(self):
from lxml.etree import XMLSyntaxError
spam_data = os.path.join(DATA_PATH, 'spam.html')
@@ -616,8 +613,22 @@ def test_works_on_valid_markup(self):
def test_fallback_success(self):
_skip_if_none_of(('bs4', 'html5lib'))
banklist_data = os.path.join(DATA_PATH, 'banklist.html')
- self.read_html(banklist_data, '.*Water.*', flavor=['lxml',
- 'html5lib'])
+ self.read_html(banklist_data, '.*Water.*', flavor=['lxml', 'html5lib'])
+
+ def test_parse_dates_list(self):
+ df = DataFrame({'date': date_range('1/1/2001', periods=10)})
+ expected = df.to_html()
+ res = self.read_html(expected, parse_dates=[0], index_col=0)
+ tm.assert_frame_equal(df, res[0])
+
+ def test_parse_dates_combine(self):
+ raw_dates = Series(date_range('1/1/2001', periods=10))
+ df = DataFrame({'date': raw_dates.map(lambda x: str(x.date())),
+ 'time': raw_dates.map(lambda x: str(x.time()))})
+ res = self.read_html(df.to_html(), parse_dates={'datetime': [1, 2]},
+ index_col=1)
+ newdf = DataFrame({'datetime': raw_dates})
+ tm.assert_frame_equal(newdf, res[0])
def test_invalid_flavor():
| closes #5150.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5151 | 2013-10-08T03:12:45Z | 2013-10-08T03:41:58Z | 2013-10-08T03:41:58Z | 2014-06-27T22:14:09Z |
TST: use default utf8 encoding when passing encoding to parser as Bytes (GH5141) | diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index ada6ffdc34257..cf0c01c8dff50 100644
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -2147,7 +2147,7 @@ def test_fwf_compression(self):
def test_BytesIO_input(self):
if not compat.PY3:
raise nose.SkipTest("Bytes-related test - only needs to work on Python 3")
- result = pd.read_fwf(BytesIO("שלום\nשלום".encode('utf8')), widths=[2,2])
+ result = pd.read_fwf(BytesIO("שלום\nשלום".encode('utf8')), widths=[2,2], encoding='utf8')
expected = pd.DataFrame([["של", "ום"]], columns=["של", "ום"])
tm.assert_frame_equal(result, expected)
data = BytesIO("שלום::1234\n562::123".encode('cp1255'))
@@ -2319,9 +2319,9 @@ def test_variable_width_unicode(self):
של ום
'''.strip('\r\n')
expected = pd.read_fwf(BytesIO(test.encode('utf8')),
- colspecs=[(0, 4), (5, 9)], header=None)
+ colspecs=[(0, 4), (5, 9)], header=None, encoding='utf8')
tm.assert_frame_equal(expected, read_fwf(BytesIO(test.encode('utf8')),
- header=None))
+ header=None, encoding='utf8'))
class TestCParserHighMemory(ParserTests, unittest.TestCase):
| closes #5141
| https://api.github.com/repos/pandas-dev/pandas/pulls/5149 | 2013-10-08T01:50:52Z | 2013-10-08T02:04:28Z | 2013-10-08T02:04:28Z | 2014-07-16T08:33:38Z |
BUG: allow tuples in recursive call to replace | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 848bd1035fadc..85d9be1295e29 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -573,6 +573,8 @@ Bug Fixes
- Fix bound checking for Timestamp() with datetime64 input (:issue:`4065`)
- Fix a bug where ``TestReadHtml`` wasn't calling the correct ``read_html()``
function (:issue:`5150`).
+ - Fix a bug with ``NDFrame.replace()`` which made replacement appear as
+ though it was (incorrectly) using regular expressions (:issue:`5143`).
pandas 0.12.0
-------------
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 108b82eaf9056..33df305a721a6 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -7,13 +7,8 @@
import numbers
import codecs
import csv
-import sys
import types
-from datetime import timedelta
-
-from distutils.version import LooseVersion
-
from numpy.lib.format import read_array, write_array
import numpy as np
@@ -21,9 +16,7 @@
import pandas.lib as lib
import pandas.tslib as tslib
from pandas import compat
-from pandas.compat import (StringIO, BytesIO, range, long, u, zip, map,
- string_types)
-from datetime import timedelta
+from pandas.compat import StringIO, BytesIO, range, long, u, zip, map
from pandas.core.config import get_option
from pandas.core import array as pa
@@ -36,6 +29,7 @@ class PandasError(Exception):
class AmbiguousIndexError(PandasError, KeyError):
pass
+
_POSSIBLY_CAST_DTYPES = set([np.dtype(t)
for t in ['M8[ns]', 'm8[ns]', 'O', 'int8',
'uint8', 'int16', 'uint16', 'int32',
@@ -101,6 +95,7 @@ class to receive bound method
else:
setattr(cls, name, func)
+
def isnull(obj):
"""Detect missing values (NaN in numeric arrays, None/NaN in object arrays)
@@ -772,6 +767,7 @@ def diff(arr, n, axis=0):
return out_arr
+
def _coerce_to_dtypes(result, dtypes):
""" given a dtypes and a result set, coerce the result elements to the dtypes """
if len(result) != len(dtypes):
@@ -800,6 +796,7 @@ def conv(r,dtype):
return np.array([ conv(r,dtype) for r, dtype in zip(result,dtypes) ])
+
def _infer_dtype_from_scalar(val):
""" interpret the dtype from a scalar, upcast floats and ints
return the new value and the dtype """
@@ -986,6 +983,7 @@ def changeit():
return result, False
+
def _maybe_upcast(values, fill_value=np.nan, dtype=None, copy=False):
""" provide explicty type promotion and coercion
@@ -1166,6 +1164,7 @@ def pad_1d(values, limit=None, mask=None):
_method(values, mask, limit=limit)
return values
+
def backfill_1d(values, limit=None, mask=None):
dtype = values.dtype.name
@@ -1190,6 +1189,7 @@ def backfill_1d(values, limit=None, mask=None):
_method(values, mask, limit=limit)
return values
+
def pad_2d(values, limit=None, mask=None):
dtype = values.dtype.name
@@ -1218,6 +1218,7 @@ def pad_2d(values, limit=None, mask=None):
pass
return values
+
def backfill_2d(values, limit=None, mask=None):
dtype = values.dtype.name
@@ -1246,6 +1247,7 @@ def backfill_2d(values, limit=None, mask=None):
pass
return values
+
def interpolate_2d(values, method='pad', axis=0, limit=None, fill_value=None):
""" perform an actual interpolation of values, values will be make 2-d if needed
fills inplace, returns the result """
@@ -1371,6 +1373,7 @@ def _possibly_convert_platform(values):
return values
+
def _possibly_cast_to_datetime(value, dtype, coerce=False):
""" try to cast the array/value to a datetimelike dtype, converting float nan to iNaT """
@@ -1787,6 +1790,7 @@ def is_datetime64_dtype(arr_or_dtype):
tipo = arr_or_dtype.dtype.type
return issubclass(tipo, np.datetime64)
+
def is_datetime64_ns_dtype(arr_or_dtype):
if isinstance(arr_or_dtype, np.dtype):
tipo = arr_or_dtype
@@ -1796,6 +1800,7 @@ def is_datetime64_ns_dtype(arr_or_dtype):
tipo = arr_or_dtype.dtype
return tipo == _NS_DTYPE
+
def is_timedelta64_dtype(arr_or_dtype):
if isinstance(arr_or_dtype, np.dtype):
tipo = arr_or_dtype.type
@@ -1851,6 +1856,7 @@ def _is_sequence(x):
except (TypeError, AttributeError):
return False
+
_ensure_float64 = algos.ensure_float64
_ensure_float32 = algos.ensure_float32
_ensure_int64 = algos.ensure_int64
@@ -1987,6 +1993,7 @@ def _get_handle(path, mode, encoding=None, compression=None):
return f
+
if compat.PY3: # pragma: no cover
def UnicodeReader(f, dialect=csv.excel, encoding="utf-8", **kwds):
# ignore encoding
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 1bbaeffff77bc..daaf9d9966635 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -12,7 +12,6 @@
# pylint: disable=E1101,E1103
# pylint: disable=W0212,W0231,W0703,W0622
-import operator
import sys
import collections
import warnings
@@ -25,7 +24,7 @@
from pandas.core.common import (isnull, notnull, PandasError, _try_sort,
_default_index, _maybe_upcast, _is_sequence,
_infer_dtype_from_scalar, _values_from_object,
- _coerce_to_dtypes, _DATELIKE_DTYPES, is_list_like)
+ _DATELIKE_DTYPES, is_list_like)
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas.core.indexing import (_maybe_droplevels,
@@ -48,7 +47,6 @@
from pandas.tseries.index import DatetimeIndex
import pandas.core.algorithms as algos
-import pandas.core.datetools as datetools
import pandas.core.common as com
import pandas.core.format as fmt
import pandas.core.nanops as nanops
@@ -4292,6 +4290,7 @@ def combineMult(self, other):
"""
return self.mul(other, fill_value=1.)
+
DataFrame._setup_axes(
['index', 'columns'], info_axis=1, stat_axis=0, axes_are_reversed=True)
DataFrame._add_numeric_operations()
@@ -4552,6 +4551,7 @@ def _masked_rec_array_to_mgr(data, index, columns, dtype, copy):
mgr = mgr.copy()
return mgr
+
def _reorder_arrays(arrays, arr_columns, columns):
# reorder according to the columns
if columns is not None and len(columns) and arr_columns is not None and len(arr_columns):
@@ -4562,6 +4562,7 @@ def _reorder_arrays(arrays, arr_columns, columns):
arrays = [arrays[i] for i in indexer]
return arrays, arr_columns
+
def _list_to_arrays(data, columns, coerce_float=False, dtype=None):
if len(data) > 0 and isinstance(data[0], tuple):
content = list(lib.to_object_array_tuples(data).T)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index d8a03cef16c9e..bb47709532523 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -18,9 +18,7 @@
from pandas import compat, _np_version_under1p7
from pandas.compat import map, zip, lrange, string_types, isidentifier
from pandas.core.common import (isnull, notnull, is_list_like,
- _values_from_object,
- _infer_dtype_from_scalar, _maybe_promote,
- ABCSeries)
+ _values_from_object, _maybe_promote, ABCSeries)
import pandas.core.nanops as nanops
from pandas.util.decorators import Appender, Substitution
@@ -36,6 +34,7 @@
def is_dictlike(x):
return isinstance(x, (dict, com.ABCSeries))
+
def _single_replace(self, to_replace, method, inplace, limit):
orig_dtype = self.dtype
result = self if inplace else self.copy()
@@ -1844,7 +1843,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
self._consolidate_inplace()
if value is None:
- if isinstance(to_replace, list):
+ if isinstance(to_replace, (tuple, list)):
return _single_replace(self, to_replace, method, inplace,
limit)
@@ -1856,7 +1855,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
to_replace = regex
regex = True
- items = to_replace.items()
+ items = list(compat.iteritems(to_replace))
keys, values = zip(*items)
are_mappings = [is_dictlike(v) for v in values]
@@ -1899,7 +1898,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
regex=regex)
# {'A': NA} -> 0
- elif not isinstance(value, (list, np.ndarray)):
+ elif not com.is_list_like(value):
new_data = self._data
for k, src in compat.iteritems(to_replace):
if k in self:
@@ -1911,9 +1910,8 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
raise TypeError('Fill value must be scalar, dict, or '
'Series')
- elif isinstance(to_replace, (list, np.ndarray)):
- # [NA, ''] -> [0, 'missing']
- if isinstance(value, (list, np.ndarray)):
+ elif com.is_list_like(to_replace): # [NA, ''] -> [0, 'missing']
+ if com.is_list_like(value):
if len(to_replace) != len(value):
raise ValueError('Replacement lists must match '
'in length. Expecting %d got %d ' %
@@ -1928,11 +1926,13 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
inplace=inplace, regex=regex)
elif to_replace is None:
if not (com.is_re_compilable(regex) or
- isinstance(regex, (list, np.ndarray)) or is_dictlike(regex)):
+ com.is_list_like(regex) or
+ is_dictlike(regex)):
raise TypeError("'regex' must be a string or a compiled "
"regular expression or a list or dict of "
"strings or regular expressions, you "
- "passed a {0}".format(type(regex)))
+ "passed a"
+ " {0!r}".format(type(regex).__name__))
return self.replace(regex, value, inplace=inplace, limit=limit,
regex=True)
else:
@@ -1948,12 +1948,13 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
inplace=inplace,
regex=regex)
- elif not isinstance(value, (list, np.ndarray)): # NA -> 0
+ elif not com.is_list_like(value): # NA -> 0
new_data = self._data.replace(to_replace, value,
inplace=inplace, regex=regex)
else:
- raise TypeError('Invalid "to_replace" type: '
- '{0}'.format(type(to_replace))) # pragma: no cover
+ msg = ('Invalid "to_replace" type: '
+ '{0!r}').format(type(to_replace).__name__)
+ raise TypeError(msg) # pragma: no cover
new_data = new_data.convert(copy=not inplace, convert_numeric=False)
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 9abcdd8ea4780..070745d73b307 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -992,6 +992,7 @@ class NumericBlock(Block):
is_numeric = True
_can_hold_na = True
+
class FloatBlock(NumericBlock):
is_float = True
_downcast_dtype = 'int64'
@@ -1064,6 +1065,7 @@ def _try_cast(self, element):
def should_store(self, value):
return com.is_integer_dtype(value) and value.dtype == self.dtype
+
class TimeDeltaBlock(IntBlock):
is_timedelta = True
_can_hold_na = True
@@ -1130,6 +1132,7 @@ def to_native_types(self, slicer=None, na_rep=None, **kwargs):
for val in values.ravel()[imask]], dtype=object)
return rvalues.tolist()
+
class BoolBlock(NumericBlock):
is_bool = True
_can_hold_na = False
@@ -1677,6 +1680,7 @@ def split_block_at(self, item):
def _try_cast_result(self, result, dtype=None):
return result
+
def make_block(values, items, ref_items, klass=None, ndim=None, dtype=None, fastpath=False, placement=None):
if klass is None:
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 6f8031538e520..2e386a7e2816a 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -17,10 +17,10 @@
map, zip, range, long, lrange, lmap, lzip,
OrderedDict, cPickle as pickle, u, StringIO
)
-from pandas import compat, _np_version_under1p7
+from pandas import compat
from numpy import random, nan
-from numpy.random import randn, rand
+from numpy.random import randn
import numpy as np
import numpy.ma as ma
from numpy.testing import assert_array_equal
@@ -47,9 +47,6 @@
ensure_clean)
from pandas.core.indexing import IndexingError
from pandas.core.common import PandasError
-from pandas.compat import OrderedDict
-from pandas.computation.expr import Expr
-import pandas.computation as comp
import pandas.util.testing as tm
import pandas.lib as lib
@@ -2367,7 +2364,6 @@ def test_insert_error_msmgs(self):
with assertRaisesRegexp(TypeError, msg):
df['gr'] = df.groupby(['b', 'c']).count()
-
def test_constructor_subclass_dict(self):
# Test for passing dict subclass to constructor
data = {'col1': tm.TestSubDict((x, 10.0 * x) for x in range(10)),
@@ -2498,7 +2494,6 @@ def test_constructor_ndarray(self):
frame = DataFrame(['foo', 'bar'], index=[0, 1], columns=['A'])
self.assertEqual(len(frame), 2)
-
def test_constructor_maskedarray(self):
self._check_basic_constructor(ma.masked_all)
@@ -3052,7 +3047,6 @@ def test_constructor_column_duplicates(self):
[('a', [8]), ('a', [5]), ('b', [6])],
columns=['b', 'a', 'a'])
-
def test_column_dups_operations(self):
def check(result, expected=None):
@@ -6845,7 +6839,7 @@ def test_replace_inplace(self):
self.tsframe['A'][-5:] = nan
tsframe = self.tsframe.copy()
- res = tsframe.replace(nan, 0, inplace=True)
+ tsframe.replace(nan, 0, inplace=True)
assert_frame_equal(tsframe, self.tsframe.fillna(0))
self.assertRaises(TypeError, self.tsframe.replace, nan, inplace=True)
@@ -7618,6 +7612,46 @@ def test_replace_input_formats(self):
def test_replace_limit(self):
pass
+ def test_replace_dict_no_regex(self):
+ answer = Series({0: 'Strongly Agree', 1: 'Agree', 2: 'Neutral', 3:
+ 'Disagree', 4: 'Strongly Disagree'})
+ weights = {'Agree': 4, 'Disagree': 2, 'Neutral': 3, 'Strongly Agree':
+ 5, 'Strongly Disagree': 1}
+ expected = Series({0: 5, 1: 4, 2: 3, 3: 2, 4: 1})
+ result = answer.replace(weights)
+ tm.assert_series_equal(result, expected)
+
+ def test_replace_series_no_regex(self):
+ answer = Series({0: 'Strongly Agree', 1: 'Agree', 2: 'Neutral', 3:
+ 'Disagree', 4: 'Strongly Disagree'})
+ weights = Series({'Agree': 4, 'Disagree': 2, 'Neutral': 3,
+ 'Strongly Agree': 5, 'Strongly Disagree': 1})
+ expected = Series({0: 5, 1: 4, 2: 3, 3: 2, 4: 1})
+ result = answer.replace(weights)
+ tm.assert_series_equal(result, expected)
+
+ def test_replace_dict_tuple_list_ordering_remains_the_same(self):
+ df = DataFrame(dict(A=[nan, 1]))
+ res1 = df.replace(to_replace={nan: 0, 1: -1e8})
+ res2 = df.replace(to_replace=(1, nan), value=[-1e8, 0])
+ res3 = df.replace(to_replace=[1, nan], value=[-1e8, 0])
+
+ expected = DataFrame({'A': [0, -1e8]})
+ tm.assert_frame_equal(res1, res2)
+ tm.assert_frame_equal(res2, res3)
+ tm.assert_frame_equal(res3, expected)
+
+ def test_replace_doesnt_replace_with_no_regex(self):
+ from pandas.compat import StringIO
+ raw = """fol T_opp T_Dir T_Enh
+ 0 1 0 0 vo
+ 1 2 vr 0 0
+ 2 2 0 0 0
+ 3 3 0 bt 0"""
+ df = read_csv(StringIO(raw), sep=r'\s+')
+ res = df.replace({'\D': 1})
+ tm.assert_frame_equal(df, res)
+
def test_combine_multiple_frames_dtypes(self):
from pandas import concat
@@ -8713,7 +8747,6 @@ def test_apply_ignore_failures(self):
expected = self.mixed_frame._get_numeric_data().apply(np.mean)
assert_series_equal(result, expected)
-
def test_apply_mixed_dtype_corner(self):
df = DataFrame({'A': ['foo'],
'B': [1.]})
| This avoids the seeming passage of regular expressions
closes #5143.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5145 | 2013-10-07T23:24:10Z | 2013-10-08T04:35:21Z | 2013-10-08T04:35:21Z | 2014-06-24T07:44:28Z |
TST: fillna(values) equiv of replace(np.nan,values) | diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 8a40c359d99a5..6f8031538e520 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -3744,31 +3744,31 @@ def tuple_generator(length):
for i in range(length):
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
yield (i, letters[i % len(letters)], i/length)
-
+
columns_names = ['Integer', 'String', 'Float']
columns = [[i[j] for i in tuple_generator(10)] for j in range(len(columns_names))]
data = {'Integer': columns[0], 'String': columns[1], 'Float': columns[2]}
expected = DataFrame(data, columns=columns_names)
-
+
generator = tuple_generator(10)
result = DataFrame.from_records(generator, columns=columns_names)
assert_frame_equal(result, expected)
-
+
def test_from_records_lists_generator(self):
def list_generator(length):
for i in range(length):
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
yield [i, letters[i % len(letters)], i/length]
-
+
columns_names = ['Integer', 'String', 'Float']
columns = [[i[j] for i in list_generator(10)] for j in range(len(columns_names))]
data = {'Integer': columns[0], 'String': columns[1], 'Float': columns[2]}
expected = DataFrame(data, columns=columns_names)
-
+
generator = list_generator(10)
result = DataFrame.from_records(generator, columns=columns_names)
assert_frame_equal(result, expected)
-
+
def test_from_records_columns_not_modified(self):
tuples = [(1, 2, 3),
(1, 2, 3),
@@ -6745,6 +6745,13 @@ def test_fillna_dtype_conversion(self):
expected = DataFrame('nan',index=lrange(3),columns=['A','B'])
assert_frame_equal(result, expected)
+ # equiv of replace
+ df = DataFrame(dict(A = [1,np.nan], B = [1.,2.]))
+ for v in ['',1,np.nan,1.0]:
+ expected = df.replace(np.nan,v)
+ result = df.fillna(v)
+ assert_frame_equal(result, expected)
+
def test_ffill(self):
self.tsframe['A'][:5] = nan
self.tsframe['A'][-5:] = nan
| closes #5136 (just tests), as not a bug
| https://api.github.com/repos/pandas-dev/pandas/pulls/5139 | 2013-10-07T12:48:49Z | 2013-10-07T13:00:51Z | 2013-10-07T13:00:51Z | 2014-06-26T11:25:23Z |
ENH: json default_handler param | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 0fabfa7077a95..9a893fb18cc8e 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -1054,8 +1054,9 @@ with optional parameters:
- ``double_precision`` : The number of decimal places to use when encoding floating point values, default 10.
- ``force_ascii`` : force encoded string to be ASCII, default True.
- ``date_unit`` : The time unit to encode to, governs timestamp and ISO8601 precision. One of 's', 'ms', 'us' or 'ns' for seconds, milliseconds, microseconds and nanoseconds respectively. Default 'ms'.
+- ``default_handler`` : The handler to call if an object cannot otherwise be converted to a suitable format for JSON. Takes a single argument, which is the object to convert, and returns a serialisable object.
-Note NaN's, NaT's and None will be converted to null and datetime objects will be converted based on the date_format and date_unit parameters.
+Note ``NaN``'s, ``NaT``'s and ``None`` will be converted to ``null`` and ``datetime`` objects will be converted based on the ``date_format`` and ``date_unit`` parameters.
.. ipython:: python
@@ -1098,6 +1099,48 @@ Writing to a file, with a date index and a date column
dfj2.to_json('test.json')
open('test.json').read()
+If the JSON serialiser cannot handle the container contents directly it will fallback in the following manner:
+
+- if a ``toDict`` method is defined by the unrecognised object then that
+ will be called and its returned ``dict`` will be JSON serialised.
+- if a ``default_handler`` has been passed to ``to_json`` that will
+ be called to convert the object.
+- otherwise an attempt is made to convert the object to a ``dict`` by
+ parsing its contents. However if the object is complex this will often fail
+ with an ``OverflowError``.
+
+Your best bet when encountering ``OverflowError`` during serialisation
+is to specify a ``default_handler``. For example ``timedelta`` can cause
+problems:
+
+.. ipython:: python
+ :suppress:
+
+ from datetime import timedelta
+ dftd = DataFrame([timedelta(23), timedelta(seconds=5), 42])
+
+.. code-block:: ipython
+
+ In [141]: from datetime import timedelta
+
+ In [142]: dftd = DataFrame([timedelta(23), timedelta(seconds=5), 42])
+
+ In [143]: dftd.to_json()
+
+ ---------------------------------------------------------------------------
+ OverflowError Traceback (most recent call last)
+ OverflowError: Maximum recursion level reached
+
+which can be dealt with by specifying a simple ``default_handler``:
+
+.. ipython:: python
+
+ dftd.to_json(default_handler=str)
+
+ def my_handler(obj):
+ return obj.total_seconds()
+ dftd.to_json(default_handler=my_handler)
+
Reading JSON
~~~~~~~~~~~~
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 3e072da164ab2..661e55f21e3ee 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -233,6 +233,8 @@ API Changes
- added ``date_unit`` parameter to specify resolution of timestamps. Options
are seconds, milliseconds, microseconds and nanoseconds. (:issue:`4362`, :issue:`4498`).
+ - added ``default_handler`` parameter to allow a callable to be passed which will be
+ responsible for handling otherwise unserialisable objects.
- ``Index`` and ``MultiIndex`` changes (:issue:`4039`):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 5ac9d12de8a9a..d8a03cef16c9e 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -707,7 +707,8 @@ def __setstate__(self, state):
# I/O Methods
def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
- double_precision=10, force_ascii=True, date_unit='ms'):
+ double_precision=10, force_ascii=True, date_unit='ms',
+ default_handler=None):
"""
Convert the object to a JSON string.
@@ -728,18 +729,21 @@ def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
* DataFrame
- default is 'columns'
- - allowed values are: {'split','records','index','columns','values'}
+ - allowed values are:
+ {'split','records','index','columns','values'}
* The format of the JSON string
- - split : dict like {index -> [index], columns -> [columns], data -> [values]}
- - records : list like [{column -> value}, ... , {column -> value}]
+ - split : dict like
+ {index -> [index], columns -> [columns], data -> [values]}
+ - records : list like
+ [{column -> value}, ... , {column -> value}]
- index : dict like {index -> {column -> value}}
- columns : dict like {column -> {index -> value}}
- values : just the values array
- date_format : type of date conversion (epoch = epoch milliseconds, iso = ISO8601)
- default is epoch
+ date_format : type of date conversion, epoch or iso
+ epoch = epoch milliseconds, iso = ISO8601, default is epoch
double_precision : The number of decimal places to use when encoding
floating point values, default 10.
force_ascii : force encoded string to be ASCII, default True.
@@ -747,6 +751,10 @@ def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
The time unit to encode to, governs timestamp and ISO8601
precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,
microsecond, and nanosecond respectively.
+ default_handler : callable, default None
+ Handler to call if object cannot otherwise be converted to a
+ suitable format for JSON. Should receive a single argument which is
+ the object to convert and return a serialisable object.
Returns
-------
@@ -761,7 +769,8 @@ def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
date_format=date_format,
double_precision=double_precision,
force_ascii=force_ascii,
- date_unit=date_unit)
+ date_unit=date_unit,
+ default_handler=default_handler)
def to_hdf(self, path_or_buf, key, **kwargs):
""" activate the HDFStore
diff --git a/pandas/io/json.py b/pandas/io/json.py
index 497831f597681..c81064d1c0516 100644
--- a/pandas/io/json.py
+++ b/pandas/io/json.py
@@ -17,19 +17,21 @@
dumps = _json.dumps
### interface to/from ###
+
def to_json(path_or_buf, obj, orient=None, date_format='epoch',
- double_precision=10, force_ascii=True, date_unit='ms'):
+ double_precision=10, force_ascii=True, date_unit='ms',
+ default_handler=None):
if isinstance(obj, Series):
s = SeriesWriter(
obj, orient=orient, date_format=date_format,
double_precision=double_precision, ensure_ascii=force_ascii,
- date_unit=date_unit).write()
+ date_unit=date_unit, default_handler=default_handler).write()
elif isinstance(obj, DataFrame):
s = FrameWriter(
obj, orient=orient, date_format=date_format,
double_precision=double_precision, ensure_ascii=force_ascii,
- date_unit=date_unit).write()
+ date_unit=date_unit, default_handler=default_handler).write()
else:
raise NotImplementedError
@@ -45,7 +47,7 @@ def to_json(path_or_buf, obj, orient=None, date_format='epoch',
class Writer(object):
def __init__(self, obj, orient, date_format, double_precision,
- ensure_ascii, date_unit):
+ ensure_ascii, date_unit, default_handler=None):
self.obj = obj
if orient is None:
@@ -56,6 +58,7 @@ def __init__(self, obj, orient, date_format, double_precision,
self.double_precision = double_precision
self.ensure_ascii = ensure_ascii
self.date_unit = date_unit
+ self.default_handler = default_handler
self.is_copy = False
self._format_axes()
@@ -70,7 +73,9 @@ def write(self):
double_precision=self.double_precision,
ensure_ascii=self.ensure_ascii,
date_unit=self.date_unit,
- iso_dates=self.date_format == 'iso')
+ iso_dates=self.date_format == 'iso',
+ default_handler=self.default_handler)
+
class SeriesWriter(Writer):
_default_orient = 'index'
@@ -121,13 +126,17 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
- default is ``'columns'``
- allowed values are: {'split','records','index','columns','values'}
- - The DataFrame index must be unique for orients 'index' and 'columns'.
- - The DataFrame columns must be unique for orients 'index', 'columns', and 'records'.
+ - The DataFrame index must be unique for orients 'index' and
+ 'columns'.
+ - The DataFrame columns must be unique for orients 'index',
+ 'columns', and 'records'.
* The format of the JSON string
- - split : dict like ``{index -> [index], columns -> [columns], data -> [values]}``
- - records : list like ``[{column -> value}, ... , {column -> value}]``
+ - split : dict like
+ ``{index -> [index], columns -> [columns], data -> [values]}``
+ - records : list like
+ ``[{column -> value}, ... , {column -> value}]``
- index : dict like ``{index -> {column -> value}}``
- columns : dict like ``{column -> {index -> value}}``
- values : just the values array
@@ -384,7 +393,6 @@ class SeriesParser(Parser):
_default_orient = 'index'
_split_keys = ('name', 'index', 'data')
-
def _parse_no_numpy(self):
json = self.json
@@ -542,7 +550,7 @@ def is_ok(col):
#----------------------------------------------------------------------
# JSON normalization routines
-def nested_to_record(ds,prefix="",level=0):
+def nested_to_record(ds, prefix="", level=0):
"""a simplified json_normalize
converts a nested dict into a flat dict ("record"), unlike json_normalize,
@@ -557,7 +565,8 @@ def nested_to_record(ds,prefix="",level=0):
d - dict or list of dicts, matching `ds`
Example:
- IN[52]: nested_to_record(dict(flat1=1,dict1=dict(c=1,d=2),nested=dict(e=dict(c=1,d=2),d=2)))
+ 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,
@@ -567,7 +576,7 @@ def nested_to_record(ds,prefix="",level=0):
'nested.e.d': 2}
"""
singleton = False
- if isinstance(ds,dict):
+ if isinstance(ds, dict):
ds = [ds]
singleton = True
@@ -575,23 +584,23 @@ def nested_to_record(ds,prefix="",level=0):
for d in ds:
new_d = copy.deepcopy(d)
- for k,v in d.items():
+ for k, v in d.items():
# each key gets renamed with prefix
if level == 0:
newkey = str(k)
else:
- newkey = prefix+'.'+ str(k)
+ newkey = prefix + '.' + str(k)
# only dicts gets recurse-flattend
# only at level>1 do we rename the rest of the keys
- if not isinstance(v,dict):
- if level!=0: # so we skip copying for top level, common case
+ if not isinstance(v, dict):
+ if level != 0: # so we skip copying for top level, common case
v = new_d.pop(k)
- new_d[newkey]= v
+ new_d[newkey] = v
continue
else:
v = new_d.pop(k)
- new_d.update(nested_to_record(v,newkey,level+1))
+ new_d.update(nested_to_record(v, newkey, level+1))
new_ds.append(new_d)
if singleton:
@@ -663,13 +672,14 @@ def _pull_field(js, spec):
data = [data]
if record_path is None:
- if any([isinstance(x,dict) for x in compat.itervalues(data[0])]):
+ if any([isinstance(x, dict) for x in compat.itervalues(data[0])]):
# naive normalization, this is idempotent for flat records
# and potentially will inflate the data considerably for
# deeply nested structures:
# {VeryLong: { b: 1,c:2}} -> {VeryLong.b:1 ,VeryLong.c:@}
#
- # TODO: handle record value which are lists, at least error reasonabley
+ # TODO: handle record value which are lists, at least error
+ # reasonably
data = nested_to_record(data)
return DataFrame(data)
elif not isinstance(record_path, list):
diff --git a/pandas/io/tests/test_json/test_pandas.py b/pandas/io/tests/test_json/test_pandas.py
index dea7f2b079cef..8c7d89641bdd4 100644
--- a/pandas/io/tests/test_json/test_pandas.py
+++ b/pandas/io/tests/test_json/test_pandas.py
@@ -575,3 +575,16 @@ def test_url(self):
url = 'http://search.twitter.com/search.json?q=pandas%20python'
result = read_json(url)
+
+ def test_default_handler(self):
+ from datetime import timedelta
+ frame = DataFrame([timedelta(23), timedelta(seconds=5)])
+ self.assertRaises(OverflowError, frame.to_json)
+ expected = DataFrame([str(timedelta(23)), str(timedelta(seconds=5))])
+ assert_frame_equal(
+ expected, pd.read_json(frame.to_json(default_handler=str)))
+
+ def my_handler_raises(obj):
+ raise TypeError
+ self.assertRaises(
+ TypeError, frame.to_json, default_handler=my_handler_raises)
diff --git a/pandas/io/tests/test_json/test_ujson.py b/pandas/io/tests/test_json/test_ujson.py
index 13ccf0bbd1742..4eb5b94ccf091 100644
--- a/pandas/io/tests/test_json/test_ujson.py
+++ b/pandas/io/tests/test_json/test_ujson.py
@@ -836,6 +836,51 @@ def toDict(self):
dec = ujson.decode(output)
self.assertEquals(dec, d)
+ def test_defaultHandler(self):
+
+ class _TestObject(object):
+
+ def __init__(self, val):
+ self.val = val
+
+ @property
+ def recursive_attr(self):
+ return _TestObject("recursive_attr")
+
+ def __str__(self):
+ return str(self.val)
+
+ self.assertRaises(OverflowError, ujson.encode, _TestObject("foo"))
+ self.assertEquals('"foo"', ujson.encode(_TestObject("foo"),
+ default_handler=str))
+
+ def my_handler(obj):
+ return "foobar"
+ self.assertEquals('"foobar"', ujson.encode(_TestObject("foo"),
+ default_handler=my_handler))
+
+ def my_handler_raises(obj):
+ raise TypeError("I raise for anything")
+ with tm.assertRaisesRegexp(TypeError, "I raise for anything"):
+ ujson.encode(_TestObject("foo"), default_handler=my_handler_raises)
+
+ def my_int_handler(obj):
+ return 42
+ self.assertEquals(
+ 42, ujson.decode(ujson.encode(_TestObject("foo"),
+ default_handler=my_int_handler)))
+
+ def my_obj_handler(obj):
+ return datetime.datetime(2013, 2, 3)
+ self.assertEquals(
+ ujson.decode(ujson.encode(datetime.datetime(2013, 2, 3))),
+ ujson.decode(ujson.encode(_TestObject("foo"),
+ default_handler=my_obj_handler)))
+
+ l = [_TestObject("foo"), _TestObject("bar")]
+ self.assertEquals(json.loads(json.dumps(l, default=str)),
+ ujson.decode(ujson.encode(l, default_handler=str)))
+
class NumpyJSONTests(TestCase):
diff --git a/pandas/src/ujson/python/objToJSON.c b/pandas/src/ujson/python/objToJSON.c
index aefddd7e47bcb..50010f4e7641a 100644
--- a/pandas/src/ujson/python/objToJSON.c
+++ b/pandas/src/ujson/python/objToJSON.c
@@ -120,6 +120,8 @@ typedef struct __PyObjectEncoder
// output format style for pandas data types
int outputFormat;
int originalOutputFormat;
+
+ PyObject *defaultHandler;
} PyObjectEncoder;
#define GET_TC(__ptrtc) ((TypeContext *)((__ptrtc)->prv))
@@ -256,6 +258,7 @@ static void *PandasDateTimeStructToJSON(pandas_datetimestruct *dts, JSONTypeCont
{
PRINTMARK();
PyErr_SetString(PyExc_ValueError, "Could not convert datetime value to string");
+ ((JSONObjectEncoder*) tc->encoder)->errorMsg = "";
PyObject_Free(GET_TC(tc)->cStr);
return NULL;
}
@@ -1160,7 +1163,7 @@ char** NpyArr_encodeLabels(PyArrayObject* labels, JSONObjectEncoder* enc, npy_in
void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
{
- PyObject *obj, *exc, *toDictFunc;
+ PyObject *obj, *exc, *toDictFunc, *defaultObj;
TypeContext *pc;
PyObjectEncoder *enc;
double val;
@@ -1630,6 +1633,23 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
PyErr_Clear();
+ if (enc->defaultHandler)
+ {
+ PRINTMARK();
+ defaultObj = PyObject_CallFunctionObjArgs(enc->defaultHandler, obj, NULL);
+ if (defaultObj == NULL || PyErr_Occurred())
+ {
+ if (!PyErr_Occurred())
+ {
+ PyErr_SetString(PyExc_TypeError, "Failed to execute default handler");
+ }
+ goto INVALID;
+ }
+ encode (defaultObj, enc, NULL, 0);
+ Py_DECREF(defaultObj);
+ goto INVALID;
+ }
+
PRINTMARK();
tc->type = JT_OBJECT;
pc->iterBegin = Dir_iterBegin;
@@ -1716,7 +1736,7 @@ char *Object_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
{
- static char *kwlist[] = { "obj", "ensure_ascii", "double_precision", "encode_html_chars", "orient", "date_unit", "iso_dates", NULL};
+ static char *kwlist[] = { "obj", "ensure_ascii", "double_precision", "encode_html_chars", "orient", "date_unit", "iso_dates", "default_handler", NULL};
char buffer[65536];
char *ret;
@@ -1728,6 +1748,7 @@ PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
char *sOrient = NULL;
char *sdateFormat = NULL;
PyObject *oisoDates = 0;
+ PyObject *odefHandler = 0;
PyObjectEncoder pyEncoder =
{
@@ -1759,10 +1780,11 @@ PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
pyEncoder.datetimeIso = 0;
pyEncoder.datetimeUnit = PANDAS_FR_ms;
pyEncoder.outputFormat = COLUMNS;
+ pyEncoder.defaultHandler = 0;
PRINTMARK();
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OiOssO", kwlist, &oinput, &oensureAscii, &idoublePrecision, &oencodeHTMLChars, &sOrient, &sdateFormat, &oisoDates))
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OiOssOO", kwlist, &oinput, &oensureAscii, &idoublePrecision, &oencodeHTMLChars, &sOrient, &sdateFormat, &oisoDates, &odefHandler))
{
return NULL;
}
@@ -1851,6 +1873,16 @@ PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
}
+ if (odefHandler != NULL && odefHandler != Py_None)
+ {
+ if (!PyCallable_Check(odefHandler))
+ {
+ PyErr_SetString (PyExc_TypeError, "Default handler is not callable");
+ return NULL;
+ }
+ pyEncoder.defaultHandler = odefHandler;
+ }
+
pyEncoder.originalOutputFormat = pyEncoder.outputFormat;
PRINTMARK();
ret = JSON_EncodeObject (oinput, encoder, buffer, sizeof (buffer));
| This adds a `default_handler` param to `to_json`, which if passed must be a callable which takes one argument (the object to convert) and returns a serialisable object. The `default_handler` will only be used if an object cannot otherwise be serialised.
Note right now the JSON serialiser has direct handling for:
- Python basic types `bool`, `int`, `long`, `float`.
- Python containers `dict`, `list`, `tuple` and `set`.
- Python byte and unicode strings.
- Python decimal.
- Python `datetime` and `date`.
- Python `None`.
- Numpy arrays.
- Numpy scalars
- `NaN` and `NaT`
- Pandas `Index`, `Series`, `DataFrame` and `Timestamp`
- any subclasses of the above.
If an object is not recognised the fallback behaviour with this PR would be:
1. if a `toDict` method is defined by the unrecognised object that
will be called and its returned `dict` will be JSON serialised.
2. if a `default_handler` has been passed to `to_json` that will
be called to convert the object.
3. otherwise an attempt is made to convert the object to a `dict` by
iterating over its attributes.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5138 | 2013-10-07T06:02:37Z | 2013-10-07T12:36:33Z | 2013-10-07T12:36:33Z | 2014-06-15T16:16:36Z |
ENH: Json support for datetime.time | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 3e072da164ab2..e6453e7d7411d 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -97,6 +97,7 @@ Improvements to existing features
overlapping color and style arguments (:issue:`4402`)
- Significant table writing performance improvements in ``HDFStore``
- JSON date serialisation now performed in low-level C code.
+ - JSON support for encoding datetime.time
- Add ``drop_level`` argument to xs (:issue:`4180`)
- Can now resample a DataFrame with ohlc (:issue:`2320`)
- ``Index.copy()`` and ``MultiIndex.copy()`` now accept keyword arguments to
diff --git a/pandas/io/tests/test_json/test_ujson.py b/pandas/io/tests/test_json/test_ujson.py
index 13ccf0bbd1742..632a712af874a 100644
--- a/pandas/io/tests/test_json/test_ujson.py
+++ b/pandas/io/tests/test_json/test_ujson.py
@@ -22,6 +22,7 @@
from numpy.testing import (assert_array_equal,
assert_array_almost_equal_nulp,
assert_approx_equal)
+import pytz
from pandas import DataFrame, Series, Index, NaT, DatetimeIndex
import pandas.util.testing as tm
@@ -356,6 +357,17 @@ def test_encodeDateConversion(self):
self.assertEquals(int(expected), json.loads(output))
self.assertEquals(int(expected), ujson.decode(output))
+ def test_encodeTimeConversion(self):
+ tests = [
+ datetime.time(),
+ datetime.time(1, 2, 3),
+ datetime.time(10, 12, 15, 343243),
+ datetime.time(10, 12, 15, 343243, pytz.utc)]
+ for test in tests:
+ output = ujson.encode(test)
+ expected = '"%s"' % test.isoformat()
+ self.assertEquals(expected, output)
+
def test_nat(self):
input = NaT
assert ujson.encode(input) == 'null', "Expected null"
diff --git a/pandas/src/ujson/python/objToJSON.c b/pandas/src/ujson/python/objToJSON.c
index aefddd7e47bcb..18e4950a8c1b5 100644
--- a/pandas/src/ujson/python/objToJSON.c
+++ b/pandas/src/ujson/python/objToJSON.c
@@ -309,6 +309,30 @@ static void *NpyDatetime64ToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue
return PandasDateTimeStructToJSON(&dts, tc, outValue, _outLen);
}
+static void *PyTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *outLen)
+{
+ PyObject *obj = (PyObject *) _obj;
+ PyObject *str;
+ PyObject *tmp;
+
+ str = PyObject_CallMethod(obj, "isoformat", NULL);
+ if (str == NULL) {
+ PRINTMARK();
+ PyErr_SetString(PyExc_ValueError, "Failed to convert time");
+ return NULL;
+ }
+ if (PyUnicode_Check(str))
+ {
+ tmp = str;
+ str = PyUnicode_AsUTF8String(str);
+ Py_DECREF(tmp);
+ }
+ outValue = (void *) PyString_AS_STRING (str);
+ *outLen = strlen ((char *) outValue);
+ Py_DECREF(str);
+ return outValue;
+}
+
//=============================================================================
// Numpy array iteration functions
//=============================================================================
@@ -1361,6 +1385,13 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
return;
}
else
+ if (PyTime_Check(obj))
+ {
+ PRINTMARK();
+ pc->PyTypeToJSON = PyTimeToJSON; tc->type = JT_UTF8;
+ return;
+ }
+ else
if (obj == Py_None)
{
PRINTMARK();
| Adds `datetime.time` support to JSON serialiser. Note:
- times are encoded to strings and will be decoded to strings.
- `date_unit` and `date_format` params have no affect on `time` serialisation, they are always iso formatted.
Fixes #4873
| https://api.github.com/repos/pandas-dev/pandas/pulls/5137 | 2013-10-07T03:03:53Z | 2013-10-07T12:27:06Z | 2013-10-07T12:27:05Z | 2014-06-12T23:21:59Z |
BUG: Treat a list/ndarray identically for iloc indexing with list-like (GH5006) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 8488d03f97cbd..3e072da164ab2 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -297,7 +297,6 @@ API Changes
(:issue:`4501`)
- Support non-unique axes in a Panel via indexing operations (:issue:`4960`)
-
Internal Refactoring
~~~~~~~~~~~~~~~~~~~~
@@ -566,7 +565,7 @@ Bug Fixes
- Provide automatic conversion of ``object`` dtypes on fillna, related (:issue:`5103`)
- Fixed a bug where default options were being overwritten in the option
parser cleaning (:issue:`5121`).
-
+ - Treat a list/ndarray identically for ``iloc`` indexing with list-like (:issue:`5006`)
pandas 0.12.0
-------------
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 7502b3898d7fb..69114166b3406 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1092,7 +1092,9 @@ def _getitem_axis(self, key, axis=0):
else:
if _is_list_like(key):
- pass
+
+ # force an actual list
+ key = list(key)
else:
key = self._convert_scalar_indexer(key, axis)
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 67c87277647c8..6292c5874772f 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -333,8 +333,15 @@ def test_iloc_getitem_list_int(self):
# list of ints
self.check_result('list int', 'iloc', [0,1,2], 'ix', { 0 : [0,2,4], 1 : [0,3,6], 2: [0,4,8] }, typs = ['ints'])
+ self.check_result('list int', 'iloc', [2], 'ix', { 0 : [4], 1 : [6], 2: [8] }, typs = ['ints'])
self.check_result('list int', 'iloc', [0,1,2], 'indexer', [0,1,2], typs = ['labels','mixed','ts','floats','empty'], fails = IndexError)
+ # array of ints
+ # (GH5006), make sure that a single indexer is returning the correct type
+ self.check_result('array int', 'iloc', np.array([0,1,2]), 'ix', { 0 : [0,2,4], 1 : [0,3,6], 2: [0,4,8] }, typs = ['ints'])
+ self.check_result('array int', 'iloc', np.array([2]), 'ix', { 0 : [4], 1 : [6], 2: [8] }, typs = ['ints'])
+ self.check_result('array int', 'iloc', np.array([0,1,2]), 'indexer', [0,1,2], typs = ['labels','mixed','ts','floats','empty'], fails = IndexError)
+
def test_iloc_getitem_dups(self):
# no dups in panel (bug?)
| closes #5006
| https://api.github.com/repos/pandas-dev/pandas/pulls/5134 | 2013-10-06T23:55:10Z | 2013-10-07T00:10:08Z | 2013-10-07T00:10:08Z | 2014-06-18T14:51:20Z |
BUG: set_names should not change is_ relationship | diff --git a/pandas/core/index.py b/pandas/core/index.py
index c39364d58e205..8e98cc6fb25bb 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -335,7 +335,6 @@ def set_names(self, names, inplace=False):
raise TypeError("Must pass list-like as `names`.")
if inplace:
idx = self
- idx._reset_identity()
else:
idx = self._shallow_copy()
idx._set_names(names)
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index a568b72a9ace6..5404b30af8d1c 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -1887,6 +1887,9 @@ def test_is_(self):
self.assertTrue(mi2.is_(mi))
self.assertTrue(mi.is_(mi2))
self.assertTrue(mi.is_(mi.set_names(["C", "D"])))
+ mi2 = mi.view()
+ mi2.set_names(["E", "F"], inplace=True)
+ self.assertTrue(mi.is_(mi2))
# levels are inherent properties, they change identity
mi3 = mi2.set_levels([lrange(10), lrange(10)])
self.assertFalse(mi3.is_(mi2))
| inplace change shouldn't change identity on set names (my bad)
| https://api.github.com/repos/pandas-dev/pandas/pulls/5132 | 2013-10-06T22:25:20Z | 2013-10-06T23:24:16Z | 2013-10-06T23:24:16Z | 2014-07-16T08:33:25Z |
BUG: Fix segfault on isnull(MultiIndex) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 23f3533500849..3892d5b77a08e 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -584,6 +584,8 @@ Bug Fixes
- Made sure different locales are tested on travis-ci (:issue:`4918`). Also
adds a couple of utilities for getting locales and setting locales with a
context manager.
+ - Fixed segfault on ``isnull(MultiIndex)`` (now raises an error instead)
+ (:issue:`5123`, :issue:`5125`)
pandas 0.12.0
-------------
diff --git a/pandas/core/common.py b/pandas/core/common.py
index c87bea2abc2c2..c34dfedc7130c 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -12,6 +12,7 @@
from numpy.lib.format import read_array, write_array
import numpy as np
+import pandas as pd
import pandas.algos as algos
import pandas.lib as lib
import pandas.tslib as tslib
@@ -116,8 +117,10 @@ def isnull(obj):
def _isnull_new(obj):
if lib.isscalar(obj):
return lib.checknull(obj)
-
- if isinstance(obj, (ABCSeries, np.ndarray)):
+ # hack (for now) because MI registers as ndarray
+ elif isinstance(obj, pd.MultiIndex):
+ raise NotImplementedError("isnull is not defined for MultiIndex")
+ elif isinstance(obj, (ABCSeries, np.ndarray)):
return _isnull_ndarraylike(obj)
elif isinstance(obj, ABCGeneric):
return obj.apply(isnull)
@@ -141,8 +144,10 @@ def _isnull_old(obj):
'''
if lib.isscalar(obj):
return lib.checknull_old(obj)
-
- if isinstance(obj, (ABCSeries, np.ndarray)):
+ # hack (for now) because MI registers as ndarray
+ elif isinstance(obj, pd.MultiIndex):
+ raise NotImplementedError("isnull is not defined for MultiIndex")
+ elif isinstance(obj, (ABCSeries, np.ndarray)):
return _isnull_ndarraylike_old(obj)
elif isinstance(obj, ABCGeneric):
return obj.apply(_isnull_old)
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 7e801c0a202db..11538ae8b3ab8 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -2314,6 +2314,13 @@ def test_slice_keep_name(self):
names=['x', 'y'])
self.assertEqual(x[1:].names, x.names)
+ def test_isnull_behavior(self):
+ # should not segfault GH5123
+ # NOTE: if MI representation changes, may make sense to allow
+ # isnull(MI)
+ with tm.assertRaises(NotImplementedError):
+ pd.isnull(self.index)
+
def test_get_combined_index():
from pandas.core.index import _get_combined_index
| Now raises NotImplementedError b/c not yet clear what it should return.
Fixes #5123.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5125 | 2013-10-06T17:25:14Z | 2013-10-11T12:01:34Z | 2013-10-11T12:01:34Z | 2014-06-13T10:01:30Z |
Add indexer and str to API documentation | diff --git a/doc/make.py b/doc/make.py
index dbce5aaa7a1b4..532395b41ce95 100755
--- a/doc/make.py
+++ b/doc/make.py
@@ -72,7 +72,12 @@ def upload_prev(ver, doc_root='./'):
if os.system(pdf_cmd):
raise SystemExit('Upload PDF to %s from %s failed' % (ver, doc_root))
-
+def build_pandas():
+ os.chdir('..')
+ os.system('python setup.py clean')
+ os.system('python setup.py build_ext --inplace')
+ os.chdir('doc')
+
def build_prev(ver):
if os.system('git checkout v%s' % ver) != 1:
os.chdir('..')
@@ -238,6 +243,7 @@ def _get_config():
'clean': clean,
'auto_dev': auto_dev_build,
'auto_debug': lambda: auto_dev_build(True),
+ 'build_pandas': build_pandas,
'all': all,
}
diff --git a/doc/source/api.rst b/doc/source/api.rst
index 5706fa7864ed5..d73a8d3ad7489 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -153,6 +153,7 @@ Top-level dealing with datetimes
:toctree: generated/
to_datetime
+ to_timedelta
Top-level evaluation
~~~~~~~~~~~~~~~~~~~~
@@ -253,10 +254,17 @@ Indexing, iteration
:toctree: generated/
Series.get
+ Series.at
+ Series.iat
Series.ix
+ Series.loc
+ Series.iloc
Series.__iter__
Series.iteritems
+For more information on ``.at``, ``.iat``, ``.ix``, ``.loc``, and
+``.iloc``, see the :ref:`indexing documentation <indexing>`.
+
Binary operator functions
~~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
@@ -407,8 +415,49 @@ Time series-related
Series.tz_convert
Series.tz_localize
+String handling
+~~~~~~~~~~~~~~~~~~~
+``Series.str`` can be used to access the values of the series as
+strings and apply several methods to it. Due to implementation
+details the methods show up here as methods of the
+``StringMethods`` class.
+
+.. currentmodule:: pandas.core.strings
+
+.. autosummary::
+ :toctree: generated/
+
+ StringMethods.cat
+ StringMethods.center
+ StringMethods.contains
+ StringMethods.count
+ StringMethods.decode
+ StringMethods.encode
+ StringMethods.endswith
+ StringMethods.extract
+ StringMethods.findall
+ StringMethods.get
+ StringMethods.join
+ StringMethods.len
+ StringMethods.lower
+ StringMethods.lstrip
+ StringMethods.match
+ StringMethods.pad
+ StringMethods.repeat
+ StringMethods.replace
+ StringMethods.rstrip
+ StringMethods.slice
+ StringMethods.slice_replace
+ StringMethods.split
+ StringMethods.startswith
+ StringMethods.strip
+ StringMethods.title
+ StringMethods.upper
+
Plotting
~~~~~~~~
+.. currentmodule:: pandas
+
.. autosummary::
:toctree: generated/
@@ -476,7 +525,11 @@ Indexing, iteration
:toctree: generated/
DataFrame.head
+ DataFrame.at
+ DataFrame.iat
DataFrame.ix
+ DataFrame.loc
+ DataFrame.iloc
DataFrame.insert
DataFrame.__iter__
DataFrame.iteritems
@@ -489,6 +542,10 @@ Indexing, iteration
DataFrame.isin
DataFrame.query
+For more information on ``.at``, ``.iat``, ``.ix``, ``.loc``, and
+``.iloc``, see the :ref:`indexing documentation <indexing>`.
+
+
Binary operator functions
~~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
@@ -733,7 +790,11 @@ Indexing, iteration, slicing
.. autosummary::
:toctree: generated/
+ Panel.at
+ Panel.iat
Panel.ix
+ Panel.loc
+ Panel.iloc
Panel.__iter__
Panel.iteritems
Panel.pop
@@ -741,6 +802,9 @@ Indexing, iteration, slicing
Panel.major_xs
Panel.minor_xs
+For more information on ``.at``, ``.iat``, ``.ix``, ``.loc``, and
+``.iloc``, see the :ref:`indexing documentation <indexing>`.
+
Binary operator functions
~~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
@@ -878,8 +942,9 @@ Serialization / IO / Conversion
Index
-----
-**Many of these methods or variants thereof are available on the objects that contain an index (Series/Dataframe)
-and those should most likely be used before calling these methods directly.**
+**Many of these methods or variants thereof are available on the objects
+that contain an index (Series/Dataframe) and those should most likely be
+used before calling these methods directly.**
.. autosummary::
:toctree: generated/
@@ -1026,7 +1091,7 @@ Conversion
..
HACK - see github issue #4539. To ensure old links remain valid, include
- here the autosummaries with previous currentmodules as a comment and add
+ here the autosummaries with previous currentmodules as a comment and add
them to a hidden toctree (to avoid warnings):
.. toctree::
| closes https://github.com/pydata/pandas/issues/5068
| https://api.github.com/repos/pandas-dev/pandas/pulls/5124 | 2013-10-06T16:58:05Z | 2013-10-15T18:40:49Z | 2013-10-15T18:40:49Z | 2014-09-03T22:59:19Z |
TST: Tests and fix for unhandled data types in Excel writers. | diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index 6b83fada19001..44b323abf45c2 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -16,6 +16,7 @@
from pandas.core import config
from pandas.core.common import pprint_thing
import pandas.compat as compat
+import pandas.core.common as com
from warnings import warn
__all__ = ["read_excel", "ExcelWriter", "ExcelFile"]
@@ -290,7 +291,6 @@ def __enter__(self):
def __exit__(self, exc_type, exc_value, traceback):
self.close()
-
def _trim_excel_header(row):
# trim header row so auto-index inference works
# xlrd uses '' , openpyxl None
@@ -298,12 +298,13 @@ def _trim_excel_header(row):
row = row[1:]
return row
-
def _conv_value(val):
- # convert value for excel dump
- if isinstance(val, np.int64):
+ # Convert numpy types to Python types for the Excel writers.
+ if com.is_integer(val):
val = int(val)
- elif isinstance(val, np.bool8):
+ elif com.is_float(val):
+ val = float(val)
+ elif com.is_bool(val):
val = bool(val)
elif isinstance(val, Period):
val = "%s" % val
@@ -686,8 +687,6 @@ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0):
style_dict = {}
for cell in cells:
- val = _conv_value(cell.val)
-
num_format_str = None
if isinstance(cell.val, datetime.datetime):
num_format_str = "YYYY-MM-DD HH:MM:SS"
@@ -709,11 +708,11 @@ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0):
startrow + cell.mergestart,
startcol + cell.col,
startcol + cell.mergeend,
- val, style)
+ cell.val, style)
else:
wks.write(startrow + cell.row,
startcol + cell.col,
- val, style)
+ cell.val, style)
def _convert_to_style(self, style_dict, num_format_str=None):
"""
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 38b3ee192ab7a..b279c7ffd2892 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -221,7 +221,6 @@ def test_excel_table_sheet_by_index(self):
(self.xlsx1, self.csv1)]:
self.check_excel_table_sheet_by_index(filename, csvfile)
-
def test_excel_table(self):
_skip_if_no_xlrd()
@@ -405,7 +404,6 @@ def test_mixed(self):
recons = reader.parse('test1', index_col=0)
tm.assert_frame_equal(self.mixed_frame, recons)
-
def test_tsframe(self):
_skip_if_no_xlrd()
ext = self.ext
@@ -419,45 +417,70 @@ def test_tsframe(self):
recons = reader.parse('test1')
tm.assert_frame_equal(df, recons)
- def test_int64(self):
+ def test_int_types(self):
_skip_if_no_xlrd()
ext = self.ext
- path = '__tmp_to_excel_from_excel_int64__.' + ext
-
- with ensure_clean(path) as path:
- self.frame['A'][:5] = nan
-
- self.frame.to_excel(path, 'test1')
- self.frame.to_excel(path, 'test1', cols=['A', 'B'])
- self.frame.to_excel(path, 'test1', header=False)
- self.frame.to_excel(path, 'test1', index=False)
+ path = '__tmp_to_excel_from_excel_int_types__.' + ext
- # Test np.int64, values read come back as float
- frame = DataFrame(np.random.randint(-10, 10, size=(10, 2)), dtype=np.int64)
- frame.to_excel(path, 'test1')
- reader = ExcelFile(path)
- recons = reader.parse('test1').astype(np.int64)
- tm.assert_frame_equal(frame, recons, check_dtype=False)
+ for np_type in (np.int8, np.int16, np.int32, np.int64):
- def test_bool(self):
+ with ensure_clean(path) as path:
+ self.frame['A'][:5] = nan
+
+ self.frame.to_excel(path, 'test1')
+ self.frame.to_excel(path, 'test1', cols=['A', 'B'])
+ self.frame.to_excel(path, 'test1', header=False)
+ self.frame.to_excel(path, 'test1', index=False)
+
+ # Test np.int values read come back as float.
+ frame = DataFrame(np.random.randint(-10, 10, size=(10, 2)),
+ dtype=np_type)
+ frame.to_excel(path, 'test1')
+ reader = ExcelFile(path)
+ recons = reader.parse('test1').astype(np_type)
+ tm.assert_frame_equal(frame, recons, check_dtype=False)
+
+ def test_float_types(self):
_skip_if_no_xlrd()
ext = self.ext
- path = '__tmp_to_excel_from_excel_bool__.' + ext
+ path = '__tmp_to_excel_from_excel_float_types__.' + ext
- with ensure_clean(path) as path:
- self.frame['A'][:5] = nan
+ for np_type in (np.float16, np.float32, np.float64):
+ with ensure_clean(path) as path:
+ self.frame['A'][:5] = nan
- self.frame.to_excel(path, 'test1')
- self.frame.to_excel(path, 'test1', cols=['A', 'B'])
- self.frame.to_excel(path, 'test1', header=False)
- self.frame.to_excel(path, 'test1', index=False)
+ self.frame.to_excel(path, 'test1')
+ self.frame.to_excel(path, 'test1', cols=['A', 'B'])
+ self.frame.to_excel(path, 'test1', header=False)
+ self.frame.to_excel(path, 'test1', index=False)
- # Test reading/writing np.bool8, roundtrip only works for xlsx
- frame = (DataFrame(np.random.randn(10, 2)) >= 0)
- frame.to_excel(path, 'test1')
- reader = ExcelFile(path)
- recons = reader.parse('test1').astype(np.bool8)
- tm.assert_frame_equal(frame, recons)
+ # Test np.float values read come back as float.
+ frame = DataFrame(np.random.random_sample(10), dtype=np_type)
+ frame.to_excel(path, 'test1')
+ reader = ExcelFile(path)
+ recons = reader.parse('test1').astype(np_type)
+ tm.assert_frame_equal(frame, recons, check_dtype=False)
+
+ def test_bool_types(self):
+ _skip_if_no_xlrd()
+ ext = self.ext
+ path = '__tmp_to_excel_from_excel_bool_types__.' + ext
+
+ for np_type in (np.bool8, np.bool_):
+ with ensure_clean(path) as path:
+ self.frame['A'][:5] = nan
+
+ self.frame.to_excel(path, 'test1')
+ self.frame.to_excel(path, 'test1', cols=['A', 'B'])
+ self.frame.to_excel(path, 'test1', header=False)
+ self.frame.to_excel(path, 'test1', index=False)
+
+ # Test np.bool values read come back as float.
+ frame = (DataFrame([1, 0, True, False], dtype=np_type))
+ frame.to_excel(path, 'test1')
+ reader = ExcelFile(path)
+ recons = reader.parse('test1').astype(np_type)
+ tm.assert_frame_equal(frame, recons)
def test_sheets(self):
_skip_if_no_xlrd()
| Added tests and a fix for unhandled numpy data types in the
Excel writers. Issue #3122.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5122 | 2013-10-06T08:18:32Z | 2013-10-14T01:40:48Z | 2013-10-14T01:40:48Z | 2014-06-16T01:40:59Z |
CLN: clean up parser options | diff --git a/doc/source/release.rst b/doc/source/release.rst
index a3908ab01903d..8488d03f97cbd 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -564,6 +564,8 @@ Bug Fixes
- Fixed a bug where ``groupby.plot()`` and friends were duplicating figures
multiple times (:issue:`5102`).
- Provide automatic conversion of ``object`` dtypes on fillna, related (:issue:`5103`)
+ - Fixed a bug where default options were being overwritten in the option
+ parser cleaning (:issue:`5121`).
pandas 0.12.0
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 8a2f249f6af06..76d6a3909f89f 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -2,11 +2,10 @@
Module contains tools for processing files into DataFrames or other objects
"""
from __future__ import print_function
-from pandas.compat import range, lrange, StringIO, lzip, zip, string_types
+from pandas.compat import range, lrange, StringIO, lzip, zip, string_types, map
from pandas import compat
import re
import csv
-from warnings import warn
import numpy as np
@@ -266,7 +265,6 @@ def _read(filepath_or_buffer, kwds):
'buffer_lines': None,
'error_bad_lines': True,
'warn_bad_lines': True,
- 'factorize': True,
'dtype': None,
'decimal': b'.'
}
@@ -340,8 +338,7 @@ def parser_f(filepath_or_buffer,
encoding=None,
squeeze=False,
mangle_dupe_cols=True,
- tupleize_cols=False,
- ):
+ tupleize_cols=False):
# Alias sep -> delimiter.
if delimiter is None:
@@ -400,8 +397,7 @@ def parser_f(filepath_or_buffer,
low_memory=low_memory,
buffer_lines=buffer_lines,
mangle_dupe_cols=mangle_dupe_cols,
- tupleize_cols=tupleize_cols,
- )
+ tupleize_cols=tupleize_cols)
return _read(filepath_or_buffer, kwds)
@@ -490,27 +486,24 @@ def _get_options_with_defaults(self, engine):
kwds = self.orig_options
options = {}
- for argname, default in compat.iteritems(_parser_defaults):
- if argname in kwds:
- value = kwds[argname]
- else:
- value = default
- options[argname] = value
+ for argname, default in compat.iteritems(_parser_defaults):
+ options[argname] = kwds.get(argname, default)
for argname, default in compat.iteritems(_c_parser_defaults):
if argname in kwds:
value = kwds[argname]
+
if engine != 'c' and value != default:
- raise ValueError('%s is not supported with %s parser' %
- (argname, engine))
+ raise ValueError('The %r option is not supported with the'
+ ' %r engine' % (argname, engine))
+ else:
+ value = default
options[argname] = value
if engine == 'python-fwf':
for argname, default in compat.iteritems(_fwf_defaults):
- if argname in kwds:
- value = kwds[argname]
- options[argname] = value
+ options[argname] = kwds.get(argname, default)
return options
@@ -518,7 +511,9 @@ def _clean_options(self, options, engine):
result = options.copy()
sep = options['delimiter']
- if (sep is None and not options['delim_whitespace']):
+ delim_whitespace = options['delim_whitespace']
+
+ if sep is None and not delim_whitespace:
if engine == 'c':
print('Using Python parser to sniff delimiter')
engine = 'python'
@@ -667,21 +662,24 @@ def __init__(self, kwds):
self.header = kwds.get('header')
if isinstance(self.header,(list,tuple,np.ndarray)):
if kwds.get('as_recarray'):
- raise Exception("cannot specify as_recarray when "
- "specifying a multi-index header")
+ raise ValueError("cannot specify as_recarray when "
+ "specifying a multi-index header")
if kwds.get('usecols'):
- raise Exception("cannot specify usecols when "
- "specifying a multi-index header")
+ raise ValueError("cannot specify usecols when "
+ "specifying a multi-index header")
if kwds.get('names'):
- raise Exception("cannot specify names when "
- "specifying a multi-index header")
+ raise ValueError("cannot specify names when "
+ "specifying a multi-index header")
# validate index_col that only contains integers
if self.index_col is not None:
- if not (isinstance(self.index_col,(list,tuple,np.ndarray)) and all(
- [ com.is_integer(i) for i in self.index_col ]) or com.is_integer(self.index_col)):
- raise Exception("index_col must only contain row numbers "
- "when specifying a multi-index header")
+ is_sequence = isinstance(self.index_col, (list, tuple,
+ np.ndarray))
+ if not (is_sequence and
+ all(map(com.is_integer, self.index_col)) or
+ com.is_integer(self.index_col)):
+ raise ValueError("index_col must only contain row numbers "
+ "when specifying a multi-index header")
self._name_processed = False
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index 44e40dc34ff25..ada6ffdc34257 100644
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -1230,17 +1230,17 @@ def test_header_multi_index(self):
#### invalid options ####
# no as_recarray
- self.assertRaises(Exception, read_csv, StringIO(data), header=[0,1,2,3],
+ self.assertRaises(ValueError, read_csv, StringIO(data), header=[0,1,2,3],
index_col=[0,1], as_recarray=True, tupleize_cols=False)
# names
- self.assertRaises(Exception, read_csv, StringIO(data), header=[0,1,2,3],
+ self.assertRaises(ValueError, read_csv, StringIO(data), header=[0,1,2,3],
index_col=[0,1], names=['foo','bar'], tupleize_cols=False)
# usecols
- self.assertRaises(Exception, read_csv, StringIO(data), header=[0,1,2,3],
+ self.assertRaises(ValueError, read_csv, StringIO(data), header=[0,1,2,3],
index_col=[0,1], usecols=['foo','bar'], tupleize_cols=False)
# non-numeric index_col
- self.assertRaises(Exception, read_csv, StringIO(data), header=[0,1,2,3],
+ self.assertRaises(ValueError, read_csv, StringIO(data), header=[0,1,2,3],
index_col=['foo','bar'], tupleize_cols=False)
def test_pass_names_with_index(self):
@@ -2715,6 +2715,24 @@ def test_warn_if_chunks_have_mismatched_type(self):
df = self.read_csv(StringIO(data))
self.assertEqual(df.a.dtype, np.object)
+ def test_invalid_c_parser_opts_with_not_c_parser(self):
+ from pandas.io.parsers import _c_parser_defaults as c_defaults
+
+ data = """1,2,3,,
+1,2,3,4,
+1,2,3,4,5
+1,2,,,
+1,2,3,4,"""
+
+ engines = 'python', 'python-fwf'
+ for default in c_defaults:
+ for engine in engines:
+ kwargs = {default: object()}
+ with tm.assertRaisesRegexp(ValueError,
+ 'The %r option is not supported '
+ 'with the %r engine' % (default,
+ engine)):
+ read_csv(StringIO(data), engine=engine, **kwargs)
class TestParseSQL(unittest.TestCase):
@@ -2783,7 +2801,7 @@ def test_convert_sql_column_decimals(self):
def assert_same_values_and_dtype(res, exp):
- assert(res.dtype == exp.dtype)
+ tm.assert_equal(res.dtype, exp.dtype)
tm.assert_almost_equal(res, exp)
diff --git a/pandas/parser.pyx b/pandas/parser.pyx
index d08c020c9e9bc..8625038c57b23 100644
--- a/pandas/parser.pyx
+++ b/pandas/parser.pyx
@@ -237,7 +237,7 @@ cdef class TextReader:
cdef:
parser_t *parser
object file_handle, na_fvalues
- bint factorize, na_filter, verbose, has_usecols, has_mi_columns
+ bint na_filter, verbose, has_usecols, has_mi_columns
int parser_start
list clocks
char *c_encoding
@@ -276,7 +276,6 @@ cdef class TextReader:
converters=None,
- factorize=True,
as_recarray=False,
skipinitialspace=False,
@@ -338,8 +337,6 @@ cdef class TextReader:
raise ValueError('only length-1 separators excluded right now')
self.parser.delimiter = ord(delimiter)
- self.factorize = factorize
-
#----------------------------------------
# parser options
| Also add a test to make sure that the C parser options validation is actually
covered
example travis fail:
https://travis-ci.org/pydata/pandas/jobs/12171563
explanation (for the record):
if you print out `options` before this commit you'll see that they are all overwritten with a single value. Whatever this value is will depend on how the `_parser_defaults` dictionary happens to be ordered (which is random because of hashing).
This caused a bug because the value of `value` is retained from the loop over `_parser_defaults`, and `default` is _not_ reassigned in the two loops that follow the loop over `_parser_defaults`, so all the values end up being the same as the last argument that was iterated over from `_parser_defaults`.
magic explained :tada:
| https://api.github.com/repos/pandas-dev/pandas/pulls/5121 | 2013-10-05T22:34:34Z | 2013-10-05T23:28:25Z | 2013-10-05T23:28:25Z | 2014-06-24T19:40:22Z |
CLN: Remove leftover test.py file | diff --git a/test.py b/test.py
deleted file mode 100644
index b3295e2d830e7..0000000000000
--- a/test.py
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-import pandas as pd
-df = pd.DataFrame(
- {'pid' : [1,1,1,2,2,3,3,3],
- 'tag' : [23,45,62,24,45,34,25,62],
- })
-
-g = df.groupby('tag')
-
-import pdb; pdb.set_trace()
-g.filter(lambda x: len(x) > 1)
| Extra test file at top level with a set_trace on it was checked in with
the json normalize PR. I'm assuming it shouldn't be here. @jreback
@cpcloud? I think it's causing the test suite to hang for me, since I
run it from within the pandas directory.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5119 | 2013-10-05T16:25:24Z | 2013-10-05T16:32:34Z | 2013-10-05T16:32:34Z | 2014-07-16T08:33:15Z |
CLN: Remove redundant initialization from Int64Index and Float64Index constructor | diff --git a/pandas/core/index.py b/pandas/core/index.py
index 3f491b4271ddc..c39364d58e205 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -201,6 +201,8 @@ def _string_data_error(cls, data):
@classmethod
def _coerce_to_ndarray(cls, data):
+ """coerces data to ndarray, raises on scalar data. Converts other
+ iterables to list first and then to array. Does not touch ndarrays."""
if not isinstance(data, np.ndarray):
if np.isscalar(data):
@@ -1624,7 +1626,7 @@ class Int64Index(Index):
Parameters
----------
data : array-like (1-dimensional)
- dtype : NumPy dtype (default: object)
+ dtype : NumPy dtype (default: int64)
copy : bool
Make a copy of input ndarray
name : object
@@ -1651,33 +1653,8 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False):
subarr.name = name
return subarr
- if not isinstance(data, np.ndarray):
- if np.isscalar(data):
- cls._scalar_data_error(data)
-
- data = cls._coerce_to_ndarray(data)
-
- if issubclass(data.dtype.type, compat.string_types):
- cls._string_data_error(data)
-
- elif issubclass(data.dtype.type, np.integer):
- # don't force the upcast as we may be dealing
- # with a platform int
- if dtype is None or not issubclass(np.dtype(dtype).type, np.integer):
- dtype = np.int64
-
- subarr = np.array(data, dtype=dtype, copy=copy)
- else:
- subarr = np.array(data, dtype=np.int64, copy=copy)
- if len(data) > 0:
- if (subarr != data).any():
- raise TypeError('Unsafe NumPy casting, you must '
- 'explicitly cast')
-
- # other iterable of some kind
- if not isinstance(data, (list, tuple)):
- data = list(data)
- data = np.asarray(data)
+ # isscalar, generators handled in coerce_to_ndarray
+ data = cls._coerce_to_ndarray(data)
if issubclass(data.dtype.type, compat.string_types):
cls._string_data_error(data)
@@ -1767,11 +1744,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False):
subarr.name = name
return subarr
- if not isinstance(data, np.ndarray):
- if np.isscalar(data):
- cls._scalar_data_error(data)
-
- data = cls._coerce_to_ndarray(data)
+ data = cls._coerce_to_ndarray(data)
if issubclass(data.dtype.type, compat.string_types):
cls._string_data_error(data)
| `Int64Index` repeated itself and actually reconstructed an ndarray twice when passed in data was an iterable. This simplifies it down but does not actually change any behavior. (you'll see that there was basically exactly the same code twice)
| https://api.github.com/repos/pandas-dev/pandas/pulls/5117 | 2013-10-05T16:02:04Z | 2013-10-05T19:43:22Z | 2013-10-05T19:43:22Z | 2014-07-16T08:33:14Z |
API: convert objects on fillna when object result dtype, related (GH5103) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 9fa111d32e4bb..8f5308a90a0c7 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -562,6 +562,7 @@ Bug Fixes
(:issue:`5102`).
- Fixed a bug where ``groupby.plot()`` and friends were duplicating figures
multiple times (:issue:`5102`).
+ - Provide automatic conversion of ``object`` dtypes on fillna, related (:issue:`5103`)
pandas 0.12.0
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 3b451e2a3b196..9abcdd8ea4780 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1177,7 +1177,7 @@ def convert(self, convert_dates=True, convert_numeric=True, copy=True, by_item=T
# attempt to create new type blocks
is_unique = self.items.is_unique
blocks = []
- if by_item:
+ if by_item and not self._is_single_block:
for i, c in enumerate(self.items):
values = self.iget(i)
@@ -1200,6 +1200,17 @@ def convert(self, convert_dates=True, convert_numeric=True, copy=True, by_item=T
return blocks
+ def _maybe_downcast(self, blocks, downcast=None):
+
+ if downcast is not None:
+ return blocks
+
+ # split and convert the blocks
+ result_blocks = []
+ for blk in blocks:
+ result_blocks.extend(blk.convert(convert_dates=True,convert_numeric=False))
+ return result_blocks
+
def _can_hold_element(self, element):
return True
@@ -2050,6 +2061,8 @@ def apply(self, f, *args, **kwargs):
result_blocks.extend(applied)
else:
result_blocks.append(applied)
+ if len(result_blocks) == 0:
+ return self.make_empty(axes or self.axes)
bm = self.__class__(
result_blocks, axes or self.axes, do_integrity_check=do_integrity_check)
bm._consolidate_inplace()
diff --git a/pandas/core/ops.py b/pandas/core/ops.py
index c1c6e6e2f83d3..a10f3582bfe45 100644
--- a/pandas/core/ops.py
+++ b/pandas/core/ops.py
@@ -411,11 +411,13 @@ def na_op(x, y):
result = expressions.evaluate(op, str_rep, x, y,
raise_on_error=True, **eval_kwargs)
except TypeError:
- result = pa.empty(len(x), dtype=x.dtype)
if isinstance(y, (pa.Array, pd.Series)):
+ dtype = np.find_common_type([x.dtype,y.dtype],[])
+ result = np.empty(x.size, dtype=dtype)
mask = notnull(x) & notnull(y)
result[mask] = op(x[mask], y[mask])
else:
+ result = pa.empty(len(x), dtype=x.dtype)
mask = notnull(x)
result[mask] = op(x[mask], y)
@@ -690,12 +692,14 @@ def na_op(x, y):
op, str_rep, x, y, raise_on_error=True, **eval_kwargs)
except TypeError:
xrav = x.ravel()
- result = np.empty(x.size, dtype=x.dtype)
if isinstance(y, (np.ndarray, pd.Series)):
+ dtype = np.find_common_type([x.dtype,y.dtype],[])
+ result = np.empty(x.size, dtype=dtype)
yrav = y.ravel()
mask = notnull(xrav) & notnull(yrav)
result[mask] = op(xrav[mask], yrav[mask])
else:
+ result = np.empty(x.size, dtype=x.dtype)
mask = notnull(xrav)
result[mask] = op(xrav[mask], y)
@@ -855,6 +859,8 @@ def na_op(x, y):
result = expressions.evaluate(op, str_rep, x, y,
raise_on_error=True, **eval_kwargs)
except TypeError:
+
+ # TODO: might need to find_common_type here?
result = pa.empty(len(x), dtype=x.dtype)
mask = notnull(x)
result[mask] = op(x[mask], y)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index ff0e1b08d7247..0411934b9ef87 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -1664,8 +1664,9 @@ def get_atom_string(self, block, itemsize):
def set_atom_string(
self, block, existing_col, min_itemsize, nan_rep, encoding):
- # fill nan items with myself
- block = block.fillna(nan_rep)[0]
+ # fill nan items with myself, don't disturb the blocks by
+ # trying to downcast
+ block = block.fillna(nan_rep, downcast=False)[0]
data = block.values
# see if we have a valid string type
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 1e4e988431f43..9cb7483340817 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -4311,15 +4311,16 @@ def test_operators_none_as_na(self):
ops = [operator.add, operator.sub, operator.mul, operator.truediv]
+ # since filling converts dtypes from object, changed expected to be object
for op in ops:
filled = df.fillna(np.nan)
result = op(df, 3)
- expected = op(filled, 3)
+ expected = op(filled, 3).astype(object)
expected[com.isnull(expected)] = None
assert_frame_equal(result, expected)
result = op(df, df)
- expected = op(filled, filled)
+ expected = op(filled, filled).astype(object)
expected[com.isnull(expected)] = None
assert_frame_equal(result, expected)
@@ -4327,7 +4328,7 @@ def test_operators_none_as_na(self):
assert_frame_equal(result, expected)
result = op(df.fillna(7), df)
- assert_frame_equal(result, expected)
+ assert_frame_equal(result, expected, check_dtype=False)
def test_comparison_invalid(self):
@@ -6695,6 +6696,25 @@ def test_fillna(self):
df.fillna({ 2: 'foo' }, inplace=True)
assert_frame_equal(df, expected)
+ def test_fillna_dtype_conversion(self):
+ # make sure that fillna on an empty frame works
+ df = DataFrame(index=["A","B","C"], columns = [1,2,3,4,5])
+ result = df.get_dtype_counts().order()
+ expected = Series({ 'object' : 5 })
+ assert_series_equal(result, expected)
+
+ result = df.fillna(1)
+ expected = DataFrame(1, index=["A","B","C"], columns = [1,2,3,4,5])
+ result = result.get_dtype_counts().order()
+ expected = Series({ 'int64' : 5 })
+ assert_series_equal(result, expected)
+
+ # empty block
+ df = DataFrame(index=lrange(3),columns=['A','B'],dtype='float64')
+ result = df.fillna('nan')
+ expected = DataFrame('nan',index=lrange(3),columns=['A','B'])
+ assert_frame_equal(result, expected)
+
def test_ffill(self):
self.tsframe['A'][:5] = nan
self.tsframe['A'][-5:] = nan
@@ -10812,7 +10832,6 @@ def test_boolean_indexing_mixed(self):
expected.loc[35,4] = 1
assert_frame_equal(df2,expected)
- # add object, should this raise?
df['foo'] = 'test'
with tm.assertRaisesRegexp(TypeError, 'boolean setting on mixed-type'):
df[df > 0.3] = 1
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 5c94f378b88ea..07b33266d88a1 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -732,8 +732,9 @@ def test_logical_with_nas(self):
expected = DataFrame({'a': [np.nan, True]})
assert_frame_equal(result, expected)
+ # this is autodowncasted here
result = d['ItemA'].fillna(False) | d['ItemB']
- expected = DataFrame({'a': [True, True]}, dtype=object)
+ expected = DataFrame({'a': [True, True]})
assert_frame_equal(result, expected)
def test_neg(self):
| related #5103
| https://api.github.com/repos/pandas-dev/pandas/pulls/5112 | 2013-10-04T18:18:26Z | 2013-10-04T19:53:42Z | 2013-10-04T19:53:42Z | 2014-07-04T13:18:07Z |
DOC: doc fixups | diff --git a/doc/source/api.rst b/doc/source/api.rst
index 5ad36b3c8b45c..d062512ac3a5b 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -870,7 +870,7 @@ Serialization / IO / Conversion
.. currentmodule:: pandas.core.index
-.. _api.index
+.. _api.index:
Index
-----
@@ -878,7 +878,6 @@ Index
**Many of these methods or variants thereof are available on the objects that contain an index (Series/Dataframe)
and those should most likely be used before calling these methods directly.**
- * **values**
Modifying and Computations
~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst
index 33b16c1448ed8..c27bdd829f3a3 100644
--- a/doc/source/timeseries.rst
+++ b/doc/source/timeseries.rst
@@ -1114,6 +1114,7 @@ The infer_dst argument in tz_localize will attempt
to determine the right offset.
.. ipython:: python
+ :okexcept:
rng_hourly = DatetimeIndex(['11/06/2011 00:00', '11/06/2011 01:00',
'11/06/2011 01:00', '11/06/2011 02:00',
@@ -1132,7 +1133,7 @@ They can be both positive and negative. :ref:`DateOffsets<timeseries.offsets>` t
.. ipython:: python
from datetime import datetime, timedelta
- s = Series(date_range('2012-1-1', periods=3, freq='D'))
+ s = Series(date_range('2012-1-1', periods=3, freq='D'))
td = Series([ timedelta(days=i) for i in range(3) ])
df = DataFrame(dict(A = s, B = td))
df
| closes #5110.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5111 | 2013-10-04T16:54:20Z | 2013-10-04T16:54:53Z | 2013-10-04T16:54:53Z | 2014-07-16T08:33:10Z |
BUG: allow plot, boxplot, hist and completion on GroupBy objects | diff --git a/doc/source/10min.rst b/doc/source/10min.rst
index 705514ac0c364..85aafd6787f16 100644
--- a/doc/source/10min.rst
+++ b/doc/source/10min.rst
@@ -74,6 +74,43 @@ Having specific :ref:`dtypes <basics.dtypes>`
df2.dtypes
+If you're using IPython, tab completion for column names (as well as public
+attributes) is automatically enabled. Here's a subset of the attributes that
+will be completed:
+
+.. ipython::
+
+ @verbatim
+ In [1]: df2.<TAB>
+
+ df2.A df2.boxplot
+ df2.abs df2.C
+ df2.add df2.clip
+ df2.add_prefix df2.clip_lower
+ df2.add_suffix df2.clip_upper
+ df2.align df2.columns
+ df2.all df2.combine
+ df2.any df2.combineAdd
+ df2.append df2.combine_first
+ df2.apply df2.combineMult
+ df2.applymap df2.compound
+ df2.as_blocks df2.consolidate
+ df2.asfreq df2.convert_objects
+ df2.as_matrix df2.copy
+ df2.astype df2.corr
+ df2.at df2.corrwith
+ df2.at_time df2.count
+ df2.axes df2.cov
+ df2.B df2.cummax
+ df2.between_time df2.cummin
+ df2.bfill df2.cumprod
+ df2.blocks df2.cumsum
+ df2.bool df2.D
+
+As you can see, the columns ``A``, ``B``, ``C``, and ``D`` are automatically
+tab completed. ``E`` is there as well; the rest of the attributes have been
+truncated for brevity.
+
Viewing Data
------------
diff --git a/doc/source/groupby.rst b/doc/source/groupby.rst
index a8900bd83309f..723aee64fd0d9 100644
--- a/doc/source/groupby.rst
+++ b/doc/source/groupby.rst
@@ -188,6 +188,45 @@ however pass ``sort=False`` for potential speedups:
df2.groupby(['X'], sort=True).sum()
df2.groupby(['X'], sort=False).sum()
+.. _groupby.tabcompletion:
+
+``GroupBy`` will tab complete column names (and other attributes)
+
+.. ipython:: python
+ :suppress:
+
+ n = 10
+ weight = np.random.normal(166, 20, size=n)
+ height = np.random.normal(60, 10, size=n)
+ time = date_range('1/1/2000', periods=n)
+ gender = tm.choice(['male', 'female'], size=n)
+ df = DataFrame({'height': height, 'weight': weight,
+ 'gender': gender}, index=time)
+
+.. ipython:: python
+
+ df
+ gb = df.groupby('gender')
+
+
+.. ipython::
+
+ @verbatim
+ In [1]: gb.<TAB>
+ gb.agg gb.boxplot gb.cummin gb.describe gb.filter gb.get_group gb.height gb.last gb.median gb.ngroups gb.plot gb.rank gb.std gb.transform
+ gb.aggregate gb.count gb.cumprod gb.dtype gb.first gb.groups gb.hist gb.max gb.min gb.nth gb.prod gb.resample gb.sum gb.var
+ gb.apply gb.cummax gb.cumsum gb.fillna gb.gender gb.head gb.indices gb.mean gb.name gb.ohlc gb.quantile gb.size gb.tail gb.weight
+
+
+.. ipython:: python
+ :suppress:
+
+ df = DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
+ 'foo', 'bar', 'foo', 'foo'],
+ 'B' : ['one', 'one', 'two', 'three',
+ 'two', 'two', 'one', 'three'],
+ 'C' : randn(8), 'D' : randn(8)})
+
.. _groupby.multiindex:
GroupBy with MultiIndex
diff --git a/doc/source/release.rst b/doc/source/release.rst
index ebba7444e82d8..9fa111d32e4bb 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -380,6 +380,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
function signature.
- :func:`~pandas.read_html` now uses ``TextParser`` to parse HTML data from
bs4/lxml (:issue:`4770`).
+ - Removed the ``keep_internal`` keyword parameter in
+ ``pandas/core/groupby.py`` because it wasn't being used (:issue:`5102`).
.. _release.bug_fixes-0.13.0:
@@ -544,7 +546,7 @@ Bug Fixes
- Bug in setting with ``ix/loc`` and a mixed int/string index (:issue:`4544`)
- Make sure series-series boolean comparions are label based (:issue:`4947`)
- Bug in multi-level indexing with a Timestamp partial indexer (:issue:`4294`)
- - Tests/fix for multi-index construction of an all-nan frame (:isue:`4078`)
+ - Tests/fix for multi-index construction of an all-nan frame (:issue:`4078`)
- Fixed a bug where :func:`~pandas.read_html` wasn't correctly inferring
values of tables with commas (:issue:`5029`)
- Fixed a bug where :func:`~pandas.read_html` wasn't providing a stable
@@ -555,6 +557,11 @@ Bug Fixes
type of headers (:issue:`5048`).
- Fixed a bug where ``DatetimeIndex`` joins with ``PeriodIndex`` caused a
stack overflow (:issue:`3899`).
+ - Fixed a bug where ``groupby`` objects didn't allow plots (:issue:`5102`).
+ - Fixed a bug where ``groupby`` objects weren't tab-completing column names
+ (:issue:`5102`).
+ - Fixed a bug where ``groupby.plot()`` and friends were duplicating figures
+ multiple times (:issue:`5102`).
pandas 0.12.0
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index e70c01ffcb12f..8938e48eb493b 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1,4 +1,5 @@
import types
+from functools import wraps
import numpy as np
from pandas.compat import(
@@ -45,6 +46,10 @@
"""
+# special case to prevent duplicate plots when catching exceptions when
+# forwarding methods from NDFrames
+_plotting_methods = frozenset(['plot', 'boxplot', 'hist'])
+
_apply_whitelist = frozenset(['last', 'first',
'mean', 'sum', 'min', 'max',
'head', 'tail',
@@ -52,7 +57,8 @@
'resample',
'describe',
'rank', 'quantile', 'count',
- 'fillna', 'dtype'])
+ 'fillna', 'dtype']) | _plotting_methods
+
class GroupByError(Exception):
@@ -180,7 +186,6 @@ class GroupBy(PandasObject):
len(grouped) : int
Number of groups
"""
-
def __init__(self, obj, keys=None, axis=0, level=None,
grouper=None, exclusions=None, selection=None, as_index=True,
sort=True, group_keys=True, squeeze=False):
@@ -244,6 +249,9 @@ def _selection_list(self):
return [self._selection]
return self._selection
+ def _local_dir(self):
+ return sorted(set(self.obj._local_dir() + list(_apply_whitelist)))
+
def __getattr__(self, attr):
if attr in self.obj:
return self[attr]
@@ -285,6 +293,15 @@ def curried_with_axis(x):
def curried(x):
return f(x, *args, **kwargs)
+ # preserve the name so we can detect it when calling plot methods,
+ # to avoid duplicates
+ curried.__name__ = curried_with_axis.__name__ = name
+
+ # special case otherwise extra plots are created when catching the
+ # exception below
+ if name in _plotting_methods:
+ return self.apply(curried)
+
try:
return self.apply(curried_with_axis)
except Exception:
@@ -348,7 +365,11 @@ def apply(self, func, *args, **kwargs):
applied : type depending on grouped object and function
"""
func = _intercept_function(func)
- f = lambda g: func(g, *args, **kwargs)
+
+ @wraps(func)
+ def f(g):
+ return func(g, *args, **kwargs)
+
return self._python_apply_general(f)
def _python_apply_general(self, f):
@@ -598,7 +619,7 @@ def __iter__(self):
def nkeys(self):
return len(self.groupings)
- def get_iterator(self, data, axis=0, keep_internal=True):
+ def get_iterator(self, data, axis=0):
"""
Groupby iterator
@@ -607,16 +628,14 @@ def get_iterator(self, data, axis=0, keep_internal=True):
Generator yielding sequence of (name, subsetted object)
for each group
"""
- splitter = self._get_splitter(data, axis=axis,
- keep_internal=keep_internal)
+ splitter = self._get_splitter(data, axis=axis)
keys = self._get_group_keys()
for key, (i, group) in zip(keys, splitter):
yield key, group
- def _get_splitter(self, data, axis=0, keep_internal=True):
+ def _get_splitter(self, data, axis=0):
comp_ids, _, ngroups = self.group_info
- return get_splitter(data, comp_ids, ngroups, axis=axis,
- keep_internal=keep_internal)
+ return get_splitter(data, comp_ids, ngroups, axis=axis)
def _get_group_keys(self):
if len(self.groupings) == 1:
@@ -627,19 +646,19 @@ def _get_group_keys(self):
mapper = _KeyMapper(comp_ids, ngroups, self.labels, self.levels)
return [mapper.get_key(i) for i in range(ngroups)]
- def apply(self, f, data, axis=0, keep_internal=False):
+ def apply(self, f, data, axis=0):
mutated = False
- splitter = self._get_splitter(data, axis=axis,
- keep_internal=keep_internal)
+ splitter = self._get_splitter(data, axis=axis)
group_keys = self._get_group_keys()
# oh boy
- if hasattr(splitter, 'fast_apply') and axis == 0:
+ if (f.__name__ not in _plotting_methods and
+ hasattr(splitter, 'fast_apply') and axis == 0):
try:
values, mutated = splitter.fast_apply(f, group_keys)
return group_keys, values, mutated
- except (Exception) as detail:
- # we detect a mutatation of some kind
+ except Exception:
+ # we detect a mutation of some kind
# so take slow path
pass
@@ -1043,7 +1062,7 @@ def get_iterator(self, data, axis=0):
inds = lrange(start, n)
yield self.binlabels[-1], data.take(inds, axis=axis)
- def apply(self, f, data, axis=0, keep_internal=False):
+ def apply(self, f, data, axis=0):
result_keys = []
result_values = []
mutated = False
@@ -1617,6 +1636,7 @@ def filter(self, func, dropna=True, *args, **kwargs):
else:
return filtered.reindex(self.obj.index) # Fill with NaNs.
+
class NDFrameGroupBy(GroupBy):
def _iterate_slices(self):
@@ -1939,14 +1959,14 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
index = key_index
else:
stacked_values = np.vstack([np.asarray(x)
- for x in values]).T
+ for x in values]).T
index = values[0].index
columns = key_index
- except ValueError:
- #GH1738,, values is list of arrays of unequal lengths
- # fall through to the outer else caluse
+ except (ValueError, AttributeError):
+ # GH1738: values is list of arrays of unequal lengths fall
+ # through to the outer else caluse
return Series(values, index=key_index)
return DataFrame(stacked_values, index=index,
@@ -2268,6 +2288,7 @@ def ohlc(self):
"""
return self._apply_to_column_groupbys(lambda x: x._cython_agg_general('ohlc'))
+
from pandas.tools.plotting import boxplot_frame_groupby
DataFrameGroupBy.boxplot = boxplot_frame_groupby
@@ -2364,7 +2385,7 @@ class NDArrayGroupBy(GroupBy):
class DataSplitter(object):
- def __init__(self, data, labels, ngroups, axis=0, keep_internal=False):
+ def __init__(self, data, labels, ngroups, axis=0):
self.data = data
self.labels = com._ensure_int64(labels)
self.ngroups = ngroups
@@ -2419,10 +2440,8 @@ def _chop(self, sdata, slice_obj):
class FrameSplitter(DataSplitter):
-
- def __init__(self, data, labels, ngroups, axis=0, keep_internal=False):
- DataSplitter.__init__(self, data, labels, ngroups, axis=axis,
- keep_internal=keep_internal)
+ def __init__(self, data, labels, ngroups, axis=0):
+ super(FrameSplitter, self).__init__(data, labels, ngroups, axis=axis)
def fast_apply(self, f, names):
# must return keys::list, values::list, mutated::bool
@@ -2445,10 +2464,8 @@ def _chop(self, sdata, slice_obj):
class NDFrameSplitter(DataSplitter):
-
- def __init__(self, data, labels, ngroups, axis=0, keep_internal=False):
- DataSplitter.__init__(self, data, labels, ngroups, axis=axis,
- keep_internal=keep_internal)
+ def __init__(self, data, labels, ngroups, axis=0):
+ super(NDFrameSplitter, self).__init__(data, labels, ngroups, axis=axis)
self.factory = data._constructor
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index fec6460ea31f3..01cea90fa1e5a 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -2,6 +2,8 @@
import nose
import unittest
+from numpy.testing.decorators import slow
+
from datetime import datetime
from numpy import nan
@@ -9,8 +11,7 @@
from pandas.core.index import Index, MultiIndex
from pandas.core.common import rands
from pandas.core.api import Categorical, DataFrame
-from pandas.core.groupby import (GroupByError, SpecificationError, DataError,
- _apply_whitelist)
+from pandas.core.groupby import SpecificationError, DataError
from pandas.core.series import Series
from pandas.util.testing import (assert_panel_equal, assert_frame_equal,
assert_series_equal, assert_almost_equal,
@@ -18,14 +19,12 @@
from pandas.compat import(
range, long, lrange, StringIO, lmap, lzip, map, zip, builtins, OrderedDict
)
-from pandas import compat, _np_version_under1p7
+from pandas import compat
from pandas.core.panel import Panel
from pandas.tools.merge import concat
from collections import defaultdict
import pandas.core.common as com
-import pandas.core.datetools as dt
import numpy as np
-from numpy.testing import assert_equal
import pandas.core.nanops as nanops
@@ -2728,6 +2727,85 @@ def test_groupby_whitelist(self):
with tm.assertRaisesRegexp(AttributeError, msg):
getattr(gb, bl)
+ def test_series_groupby_plotting_nominally_works(self):
+ try:
+ import matplotlib as mpl
+ mpl.use('Agg')
+ except ImportError:
+ raise nose.SkipTest("matplotlib not installed")
+ n = 10
+ weight = Series(np.random.normal(166, 20, size=n))
+ height = Series(np.random.normal(60, 10, size=n))
+ gender = tm.choice(['male', 'female'], size=n)
+
+ weight.groupby(gender).plot()
+ tm.close()
+ height.groupby(gender).hist()
+ tm.close()
+
+ @slow
+ def test_frame_groupby_plot_boxplot(self):
+ try:
+ import matplotlib.pyplot as plt
+ import matplotlib as mpl
+ mpl.use('Agg')
+ except ImportError:
+ raise nose.SkipTest("matplotlib not installed")
+ tm.close()
+
+ n = 10
+ weight = Series(np.random.normal(166, 20, size=n))
+ height = Series(np.random.normal(60, 10, size=n))
+ gender = tm.choice(['male', 'female'], size=n)
+ df = DataFrame({'height': height, 'weight': weight, 'gender': gender})
+ gb = df.groupby('gender')
+
+ res = gb.plot()
+ self.assertEqual(len(plt.get_fignums()), 2)
+ self.assertEqual(len(res), 2)
+ tm.close()
+
+ res = gb.boxplot()
+ self.assertEqual(len(plt.get_fignums()), 1)
+ self.assertEqual(len(res), 2)
+ tm.close()
+
+ with tm.assertRaisesRegexp(TypeError, '.*str.+float'):
+ gb.hist()
+
+ @slow
+ def test_frame_groupby_hist(self):
+ try:
+ import matplotlib.pyplot as plt
+ import matplotlib as mpl
+ mpl.use('Agg')
+ except ImportError:
+ raise nose.SkipTest("matplotlib not installed")
+ tm.close()
+
+ n = 10
+ weight = Series(np.random.normal(166, 20, size=n))
+ height = Series(np.random.normal(60, 10, size=n))
+ gender_int = tm.choice([0, 1], size=n)
+ df_int = DataFrame({'height': height, 'weight': weight,
+ 'gender': gender_int})
+ gb = df_int.groupby('gender')
+ axes = gb.hist()
+ self.assertEqual(len(axes), 2)
+ self.assertEqual(len(plt.get_fignums()), 2)
+ tm.close()
+
+ def test_tab_completion(self):
+ grp = self.mframe.groupby(level='second')
+ results = set([v for v in dir(grp) if not v.startswith('_')])
+ expected = set(['A','B','C',
+ 'agg','aggregate','apply','boxplot','filter','first','get_group',
+ 'groups','hist','indices','last','max','mean','median',
+ 'min','name','ngroups','nth','ohlc','plot', 'prod',
+ 'size','std','sum','transform','var', 'count', 'head', 'describe',
+ 'cummax', 'dtype', 'quantile', 'rank', 'cumprod', 'tail',
+ 'resample', 'cummin', 'fillna', 'cumsum'])
+ self.assertEqual(results, expected)
def assert_fp_equal(a, b):
assert (np.abs(a - b) < 1e-12).all()
@@ -2764,7 +2842,5 @@ def testit(label_list, shape):
if __name__ == '__main__':
- import nose
- nose.runmodule(
- argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure', '-s'],
- exit=False)
+ nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure',
+ '-s'], exit=False)
| closes #5102
also fixes extra plots created by groupby plotting (couldn't find an issue), now there's a test that ensures that groupby only plots the number of axes/figures it's supposed to
removes an unused internal groupby parameter
| https://api.github.com/repos/pandas-dev/pandas/pulls/5105 | 2013-10-04T00:57:36Z | 2013-10-04T17:19:18Z | 2013-10-04T17:19:18Z | 2014-06-20T23:44:00Z |
BUG: fix PeriodIndex join with DatetimeIndex stack overflow | diff --git a/doc/source/release.rst b/doc/source/release.rst
index eaf10977af4f7..ebba7444e82d8 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -553,6 +553,8 @@ Bug Fixes
passed ``index_col=0`` (:issue:`5066`).
- Fixed a bug where :func:`~pandas.read_html` was incorrectly infering the
type of headers (:issue:`5048`).
+ - Fixed a bug where ``DatetimeIndex`` joins with ``PeriodIndex`` caused a
+ stack overflow (:issue:`3899`).
pandas 0.12.0
diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py
index cd81867ff8f08..579b0b3019fdc 100644
--- a/pandas/tseries/period.py
+++ b/pandas/tseries/period.py
@@ -12,8 +12,8 @@
import pandas.tseries.frequencies as _freq_mod
import pandas.core.common as com
-from pandas.core.common import (isnull, _NS_DTYPE, _INT64_DTYPE,
- _maybe_box, _values_from_object)
+from pandas.core.common import (isnull, _INT64_DTYPE, _maybe_box,
+ _values_from_object)
from pandas import compat
from pandas.lib import Timestamp
import pandas.lib as lib
@@ -712,13 +712,10 @@ def _array_values(self):
def astype(self, dtype):
dtype = np.dtype(dtype)
if dtype == np.object_:
- result = np.empty(len(self), dtype=dtype)
- result[:] = [x for x in self]
- return result
+ return Index(np.array(list(self), dtype), dtype)
elif dtype == _INT64_DTYPE:
- return self.values.copy()
- else: # pragma: no cover
- raise ValueError('Cannot cast PeriodIndex to dtype %s' % dtype)
+ return Index(self.values, dtype)
+ raise ValueError('Cannot cast PeriodIndex to dtype %s' % dtype)
def __iter__(self):
for val in self.values:
diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py
index 9abecc0aeeec6..55963b01d2779 100644
--- a/pandas/tseries/tests/test_period.py
+++ b/pandas/tseries/tests/test_period.py
@@ -22,8 +22,8 @@
import pandas.core.datetools as datetools
import pandas as pd
import numpy as np
-from pandas.compat import range, lrange, lmap, map, zip
-randn = np.random.randn
+from numpy.random import randn
+from pandas.compat import range, lrange, lmap, zip
from pandas import Series, TimeSeries, DataFrame
from pandas.util.testing import(assert_series_equal, assert_almost_equal,
@@ -1207,7 +1207,6 @@ def test_is_(self):
self.assertFalse(index.is_(index - 2))
self.assertFalse(index.is_(index - 0))
-
def test_comp_period(self):
idx = period_range('2007-01', periods=20, freq='M')
@@ -1913,6 +1912,17 @@ def test_join_self(self):
res = index.join(index, how=kind)
self.assert_(index is res)
+ def test_join_does_not_recur(self):
+ df = tm.makeCustomDataframe(3, 2, data_gen_f=lambda *args:
+ np.random.randint(2), c_idx_type='p',
+ r_idx_type='dt')
+ s = df.iloc[:2, 0]
+
+ res = s.index.join(df.columns, how='outer')
+ expected = Index([s.index[0], s.index[1],
+ df.columns[0], df.columns[1]], object)
+ tm.assert_index_equal(res, expected)
+
def test_align_series(self):
rng = period_range('1/1/2000', '1/1/2010', freq='A')
ts = Series(np.random.randn(len(rng)), index=rng)
@@ -2185,15 +2195,15 @@ def test_minutely(self):
def test_secondly(self):
self._check_freq('S', '1970-01-01')
-
+
def test_millisecondly(self):
self._check_freq('L', '1970-01-01')
def test_microsecondly(self):
self._check_freq('U', '1970-01-01')
-
+
def test_nanosecondly(self):
- self._check_freq('N', '1970-01-01')
+ self._check_freq('N', '1970-01-01')
def _check_freq(self, freq, base_date):
rng = PeriodIndex(start=base_date, periods=10, freq=freq)
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index f3598dd2d210b..5329f37095961 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -31,16 +31,12 @@
import pandas.index as _index
-from pandas.compat import(
- range, long, StringIO, lrange, lmap, map, zip, cPickle as pickle, product
-)
-from pandas import read_pickle
+from pandas.compat import range, long, StringIO, lrange, lmap, zip, product
import pandas.core.datetools as dt
from numpy.random import rand
from numpy.testing import assert_array_equal
from pandas.util.testing import assert_frame_equal
import pandas.compat as compat
-from pandas.core.datetools import BDay
import pandas.core.common as com
from pandas import concat
from pandas import _np_version_under1p7
@@ -2064,6 +2060,18 @@ def test_ns_index(self):
new_index = pd.DatetimeIndex(start=index[0], end=index[-1], freq=index.freq)
self.assert_index_parameters(new_index)
+ def test_join_with_period_index(self):
+ df = tm.makeCustomDataframe(10, 10, data_gen_f=lambda *args:
+ np.random.randint(2), c_idx_type='p',
+ r_idx_type='dt')
+ s = df.iloc[:5, 0]
+ joins = 'left', 'right', 'inner', 'outer'
+
+ for join in joins:
+ with tm.assertRaisesRegexp(ValueError, 'can only call with other '
+ 'PeriodIndex-ed objects'):
+ df.columns.join(s.index, how=join)
+
class TestDatetime64(unittest.TestCase):
"""
| closes #3899.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5101 | 2013-10-03T22:04:19Z | 2013-10-04T02:39:18Z | 2013-10-04T02:39:18Z | 2014-07-16T08:33:03Z |
TST: win32 paths cannot be turned into URLs by prefixing them with "file://" v2 | diff --git a/.gitignore b/.gitignore
index 201a965a0f409..edc6a54cf4345 100644
--- a/.gitignore
+++ b/.gitignore
@@ -38,3 +38,4 @@ pandas/io/*.json
.pydevproject
.settings
.idea
+*.pdb
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 49de8dddd7210..77d86b8a7a9f1 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -755,6 +755,8 @@ Bug Fixes
- Bug when renaming then set_index on a DataFrame (:issue:`5344`)
- Test suite no longer leaves around temporary files when testing graphics. (:issue:`5347`)
(thanks for catching this @yarikoptic!)
+ - Fixed html tests on win32. (:issue:`4580`)
+
pandas 0.12.0
-------------
diff --git a/pandas/io/common.py b/pandas/io/common.py
index aa5fdb29f3b5b..6b8186e253199 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -9,18 +9,18 @@
if compat.PY3:
- from urllib.request import urlopen
+ from urllib.request import urlopen, pathname2url
_urlopen = urlopen
from urllib.parse import urlparse as parse_url
import urllib.parse as compat_parse
- from urllib.parse import uses_relative, uses_netloc, uses_params, urlencode
+ from urllib.parse import uses_relative, uses_netloc, uses_params, urlencode, urljoin
from urllib.error import URLError
from http.client import HTTPException
else:
from urllib2 import urlopen as _urlopen
- from urllib import urlencode
+ from urllib import urlencode, pathname2url
from urlparse import urlparse as parse_url
- from urlparse import uses_relative, uses_netloc, uses_params
+ from urlparse import uses_relative, uses_netloc, uses_params, urljoin
from urllib2 import URLError
from httplib import HTTPException
from contextlib import contextmanager, closing
@@ -134,6 +134,21 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None):
return filepath_or_buffer, None
+def file_path_to_url(path):
+ """
+ converts an absolute native path to a FILE URL.
+
+ Parameters
+ ----------
+ path : a path in native format
+
+ Returns
+ -------
+ a valid FILE URL
+ """
+ return urljoin('file:', pathname2url(path))
+
+
# ZipFile is not a context manager for <= 2.6
# must be tuple index here since 2.6 doesn't use namedtuple for version_info
if sys.version_info[1] <= 6:
diff --git a/pandas/io/tests/test_html.py b/pandas/io/tests/test_html.py
index 71567fe2e599a..c26048d4cf20b 100644
--- a/pandas/io/tests/test_html.py
+++ b/pandas/io/tests/test_html.py
@@ -21,7 +21,7 @@
from pandas import (DataFrame, MultiIndex, read_csv, Timestamp, Index,
date_range, Series)
from pandas.compat import map, zip, StringIO, string_types
-from pandas.io.common import URLError, urlopen
+from pandas.io.common import URLError, urlopen, file_path_to_url
from pandas.io.html import read_html
import pandas.util.testing as tm
@@ -311,7 +311,7 @@ def test_invalid_url(self):
@slow
def test_file_url(self):
url = self.banklist_data
- dfs = self.read_html('file://' + url, 'First', attrs={'id': 'table'})
+ dfs = self.read_html(file_path_to_url(url), 'First', attrs={'id': 'table'})
tm.assert_isinstance(dfs, list)
for df in dfs:
tm.assert_isinstance(df, DataFrame)
@@ -362,7 +362,7 @@ def test_multiindex_header_index_skiprows(self):
@slow
def test_regex_idempotency(self):
url = self.banklist_data
- dfs = self.read_html('file://' + url,
+ dfs = self.read_html(file_path_to_url(url),
match=re.compile(re.compile('Florida')),
attrs={'id': 'table'})
tm.assert_isinstance(dfs, list)
@@ -637,9 +637,9 @@ def test_invalid_flavor():
flavor='not a* valid**++ flaver')
-def get_elements_from_url(url, element='table', base_url="file://"):
+def get_elements_from_file(url, element='table'):
_skip_if_none_of(('bs4', 'html5lib'))
- url = "".join([base_url, url])
+ url = file_path_to_url(url)
from bs4 import BeautifulSoup
with urlopen(url) as f:
soup = BeautifulSoup(f, features='html5lib')
@@ -651,7 +651,7 @@ def test_bs4_finds_tables():
filepath = os.path.join(DATA_PATH, "spam.html")
with warnings.catch_warnings():
warnings.filterwarnings('ignore')
- assert get_elements_from_url(filepath, 'table')
+ assert get_elements_from_file(filepath, 'table')
def get_lxml_elements(url, element):
| Rebased on master (unable to use same pull request). Closes #4580.
see http://stackoverflow.com/questions/11687478/convert-a-filename-to-a-file-url
| https://api.github.com/repos/pandas-dev/pandas/pulls/5100 | 2013-10-03T19:40:15Z | 2013-10-28T23:20:03Z | 2013-10-28T23:20:02Z | 2014-07-16T08:33:01Z |
date_range should (at least optionally) deal with right-open intervals | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 4a25a98f2cfbe..68bcc9c14a01b 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -174,6 +174,8 @@ Improvements to existing features
- :meth:`~pandas.io.json.json_normalize` is a new method to allow you to create a flat table
from semi-structured JSON data. :ref:`See the docs<io.json_normalize>` (:issue:`1067`)
- ``DataFrame.from_records()`` will now accept generators (:issue:`4910`)
+ - DatetimeIndex (and date_range) can now be constructed in a left- or
+ right-open fashion using the ``closed`` parameter (:issue:`4579`)
API Changes
~~~~~~~~~~~
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 33c90d3714e8a..a2b46f74244e2 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -115,6 +115,9 @@ class DatetimeIndex(Int64Index):
end : end time, datetime-like, optional
If periods is none, generated index will extend to first conforming
time on or just past end argument
+ closed : string or None, default None
+ Make the interval closed with respect to the given frequency to
+ the 'left', 'right', or both sides (None)
"""
_join_precedence = 10
@@ -143,7 +146,8 @@ class DatetimeIndex(Int64Index):
def __new__(cls, data=None,
freq=None, start=None, end=None, periods=None,
copy=False, name=None, tz=None,
- verify_integrity=True, normalize=False, **kwds):
+ verify_integrity=True, normalize=False,
+ closed=None, **kwds):
dayfirst = kwds.pop('dayfirst', None)
yearfirst = kwds.pop('yearfirst', None)
@@ -184,7 +188,7 @@ def __new__(cls, data=None,
if data is None:
return cls._generate(start, end, periods, name, offset,
- tz=tz, normalize=normalize,
+ tz=tz, normalize=normalize, closed=closed,
infer_dst=infer_dst)
if not isinstance(data, np.ndarray):
@@ -289,7 +293,7 @@ def __new__(cls, data=None,
@classmethod
def _generate(cls, start, end, periods, name, offset,
- tz=None, normalize=False, infer_dst=False):
+ tz=None, normalize=False, infer_dst=False, closed=None):
if com._count_not_none(start, end, periods) != 2:
raise ValueError('Must specify two of start, end, or periods')
@@ -301,6 +305,24 @@ def _generate(cls, start, end, periods, name, offset,
if end is not None:
end = Timestamp(end)
+ left_closed = False
+ right_closed = False
+
+ if start is None and end is None:
+ if closed is not None:
+ raise ValueError("Closed has to be None if not both of start"
+ "and end are defined")
+
+ if closed is None:
+ left_closed = True
+ right_closed = True
+ elif closed == "left":
+ left_closed = True
+ elif closed == "right":
+ right_closed = True
+ else:
+ raise ValueError("Closed has to be either 'left', 'right' or None")
+
try:
inferred_tz = tools._infer_tzinfo(start, end)
except:
@@ -387,6 +409,11 @@ def _generate(cls, start, end, periods, name, offset,
index.offset = offset
index.tz = tz
+ if not left_closed:
+ index = index[1:]
+ if not right_closed:
+ index = index[:-1]
+
return index
def _box_values(self, values):
@@ -1715,7 +1742,7 @@ def _generate_regular_range(start, end, periods, offset):
def date_range(start=None, end=None, periods=None, freq='D', tz=None,
- normalize=False, name=None):
+ normalize=False, name=None, closed=None):
"""
Return a fixed frequency datetime index, with day (calendar) as the default
frequency
@@ -1737,6 +1764,9 @@ def date_range(start=None, end=None, periods=None, freq='D', tz=None,
Normalize start/end dates to midnight before generating date range
name : str, default None
Name of the resulting index
+ closed : string or None, default None
+ Make the interval closed with respect to the given frequency to
+ the 'left', 'right', or both sides (None)
Notes
-----
@@ -1747,11 +1777,12 @@ def date_range(start=None, end=None, periods=None, freq='D', tz=None,
rng : DatetimeIndex
"""
return DatetimeIndex(start=start, end=end, periods=periods,
- freq=freq, tz=tz, normalize=normalize, name=name)
+ freq=freq, tz=tz, normalize=normalize, name=name,
+ closed=closed)
def bdate_range(start=None, end=None, periods=None, freq='B', tz=None,
- normalize=True, name=None):
+ normalize=True, name=None, closed=None):
"""
Return a fixed frequency datetime index, with business day as the default
frequency
@@ -1773,6 +1804,9 @@ def bdate_range(start=None, end=None, periods=None, freq='B', tz=None,
Normalize start/end dates to midnight before generating date range
name : str, default None
Name for the resulting index
+ closed : string or None, default None
+ Make the interval closed with respect to the given frequency to
+ the 'left', 'right', or both sides (None)
Notes
-----
@@ -1784,11 +1818,12 @@ def bdate_range(start=None, end=None, periods=None, freq='B', tz=None,
"""
return DatetimeIndex(start=start, end=end, periods=periods,
- freq=freq, tz=tz, normalize=normalize, name=name)
+ freq=freq, tz=tz, normalize=normalize, name=name,
+ closed=closed)
def cdate_range(start=None, end=None, periods=None, freq='C', tz=None,
- normalize=True, name=None, **kwargs):
+ normalize=True, name=None, closed=None, **kwargs):
"""
**EXPERIMENTAL** Return a fixed frequency datetime index, with
CustomBusinessDay as the default frequency
@@ -1820,6 +1855,9 @@ def cdate_range(start=None, end=None, periods=None, freq='C', tz=None,
holidays : list
list/array of dates to exclude from the set of valid business days,
passed to ``numpy.busdaycalendar``
+ closed : string or None, default None
+ Make the interval closed with respect to the given frequency to
+ the 'left', 'right', or both sides (None)
Notes
-----
@@ -1835,7 +1873,8 @@ def cdate_range(start=None, end=None, periods=None, freq='C', tz=None,
weekmask = kwargs.pop('weekmask', 'Mon Tue Wed Thu Fri')
freq = CDay(holidays=holidays, weekmask=weekmask)
return DatetimeIndex(start=start, end=end, periods=periods, freq=freq,
- tz=tz, normalize=normalize, name=name, **kwargs)
+ tz=tz, normalize=normalize, name=name,
+ closed=closed, **kwargs)
def _to_m8(key, tz=None):
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index e496bf46cf57a..ad7d3ba03a129 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -8,6 +8,7 @@
# import after tools, dateutil check
from dateutil.relativedelta import relativedelta
import pandas.tslib as tslib
+from pandas.tslib import Timestamp
import numpy as np
from pandas import _np_version_under1p7
@@ -92,9 +93,9 @@ def apply(self, other):
else:
for i in range(-self.n):
other = other - self._offset
- return other
+ return Timestamp(other)
else:
- return other + timedelta(self.n)
+ return Timestamp(other + timedelta(self.n))
def isAnchored(self):
return (self.n == 1)
@@ -373,7 +374,7 @@ def apply(self, other):
if self.offset:
result = result + self.offset
- return result
+ return Timestamp(result)
elif isinstance(other, (timedelta, Tick)):
return BDay(self.n, offset=self.offset + other,
@@ -516,7 +517,7 @@ def apply(self, other):
if n <= 0:
n = n + 1
other = other + relativedelta(months=n, day=31)
- return other
+ return Timestamp(other)
@classmethod
def onOffset(cls, dt):
@@ -538,7 +539,7 @@ def apply(self, other):
n += 1
other = other + relativedelta(months=n, day=1)
- return other
+ return Timestamp(other)
@classmethod
def onOffset(cls, dt):
@@ -660,7 +661,7 @@ def apply(self, other):
other = other + timedelta((self.weekday - otherDay) % 7)
for i in range(-k):
other = other - self._inc
- return other
+ return Timestamp(other)
def onOffset(self, dt):
return dt.weekday() == self.weekday
@@ -901,7 +902,7 @@ def apply(self, other):
other = other + relativedelta(months=monthsToGo + 3 * n, day=31)
- return other
+ return Timestamp(other)
def onOffset(self, dt):
modMonth = (dt.month - self.startingMonth) % 3
@@ -941,7 +942,7 @@ def apply(self, other):
n = n + 1
other = other + relativedelta(months=3 * n - monthsSince, day=1)
- return other
+ return Timestamp(other)
@property
def rule_code(self):
@@ -1093,7 +1094,7 @@ def _rollf(date):
# n == 0, roll forward
result = _rollf(result)
- return result
+ return Timestamp(result)
def onOffset(self, dt):
wkday, days_in_month = tslib.monthrange(dt.year, self.month)
@@ -1151,7 +1152,7 @@ def _rollf(date):
# n == 0, roll forward
result = _rollf(result)
- return result
+ return Timestamp(result)
def onOffset(self, dt):
return dt.month == self.month and dt.day == 1
diff --git a/pandas/tseries/tests/test_daterange.py b/pandas/tseries/tests/test_daterange.py
index cb17375266edf..3b40e75194d11 100644
--- a/pandas/tseries/tests/test_daterange.py
+++ b/pandas/tseries/tests/test_daterange.py
@@ -394,6 +394,21 @@ def test_month_range_union_tz(self):
early_dr.union(late_dr)
+ def test_range_closed(self):
+ begin = datetime(2011, 1, 1)
+ end = datetime(2014, 1, 1)
+
+ for freq in ["3D", "2M", "7W", "3H", "A"]:
+ closed = date_range(begin, end, closed=None, freq=freq)
+ left = date_range(begin, end, closed="left", freq=freq)
+ right = date_range(begin, end, closed="right", freq=freq)
+
+ expected_left = closed[:-1]
+ expected_right = closed[1:]
+
+ self.assert_(expected_left.equals(left))
+ self.assert_(expected_right.equals(right))
+
class TestCustomDateRange(unittest.TestCase):
| It is confusing that, albeit the name suggests otherwise, `date_range` behaves differently compared to the standard Python `range` generator in that it returns the right-closed interval.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4579 | 2013-10-03T19:15:12Z | 2013-10-15T12:38:35Z | 2013-10-15T12:38:35Z | 2014-06-27T14:49:22Z |
DOC: str.match should (obviously) be str.extract. | diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 44ef8f0d1a57e..fe6d796d95968 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -428,14 +428,14 @@ Enhancements
.. ipython:: python
- Series(['a1', 'b2', 'c3']).str.match(
+ Series(['a1', 'b2', 'c3']).str.extract(
'(?P<letter>[ab])(?P<digit>\d)')
and optional groups can also be used.
.. ipython:: python
- Series(['a1', 'b2', '3']).str.match(
+ Series(['a1', 'b2', '3']).str.extract(
'(?P<letter>[ab])?(?P<digit>\d)')
- ``read_stata`` now accepts Stata 13 format (:issue:`4291`)
| https://api.github.com/repos/pandas-dev/pandas/pulls/5099 | 2013-10-03T17:17:49Z | 2013-10-03T17:25:17Z | 2013-10-03T17:25:17Z | 2014-07-16T08:32:59Z | |
BUG: non-unique indexing in a Panel (GH4960) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 4f4681b112664..9b755c9ad2cda 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -290,6 +290,7 @@ API Changes
call with additional keyword args (:issue:`4435`)
- Provide __dir__ method (and local context) for tab completion / remove ipython completers code
(:issue:`4501`)
+ - Support non-unique axes in a Panel via indexing operations (:issue:`4960`)
Internal Refactoring
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 0d19736ed8083..7502b3898d7fb 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -623,8 +623,9 @@ def _getitem_lowerdim(self, tup):
# might have been a MultiIndex
elif section.ndim == self.ndim:
+
new_key = tup[:i] + (_NS,) + tup[i + 1:]
- # new_key = tup[:i] + tup[i+1:]
+
else:
new_key = tup[:i] + tup[i + 1:]
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 6fddc44d7552e..3b451e2a3b196 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -2413,12 +2413,17 @@ def _interleave(self, items):
return result
- def xs(self, key, axis=1, copy=True):
+ def xs(self, key, axis=1, copy=True, takeable=False):
if axis < 1:
raise AssertionError('Can only take xs across axis >= 1, got %d'
% axis)
- loc = self.axes[axis].get_loc(key)
+ # take by position
+ if takeable:
+ loc = key
+ else:
+ loc = self.axes[axis].get_loc(key)
+
slicer = [slice(None, None) for _ in range(self.ndim)]
slicer[axis] = loc
slicer = tuple(slicer)
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index b1752f94b8d97..1185e9514f7fc 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -504,6 +504,15 @@ def set_value(self, *args):
return result.set_value(*args)
def _box_item_values(self, key, values):
+ if self.ndim == values.ndim:
+ result = self._constructor(values)
+
+ # a dup selection will yield a full ndim
+ if result._get_axis(0).is_unique:
+ result = result[key]
+
+ return result
+
d = self._construct_axes_dict_for_slice(self._AXIS_ORDERS[1:])
return self._constructor_sliced(values, **d)
@@ -745,15 +754,27 @@ def xs(self, key, axis=1, copy=True):
_xs = xs
def _ixs(self, i, axis=0):
- # for compatibility with .ix indexing
- # Won't work with hierarchical indexing yet
+ """
+ i : int, slice, or sequence of integers
+ axis : int
+ """
+
key = self._get_axis(axis)[i]
# xs cannot handle a non-scalar key, so just reindex here
if _is_list_like(key):
- return self.reindex(**{self._get_axis_name(axis): key})
+ indexer = { self._get_axis_name(axis): key }
+ return self.reindex(**indexer)
+
+ # a reduction
+ if axis == 0:
+ values = self._data.iget(i)
+ return self._box_item_values(key,values)
- return self.xs(key, axis=axis)
+ # xs by position
+ self._consolidate_inplace()
+ new_data = self._data.xs(i, axis=axis, copy=True, takeable=True)
+ return self._construct_return_type(new_data)
def groupby(self, function, axis='major'):
"""
diff --git a/pandas/sparse/panel.py b/pandas/sparse/panel.py
index dd0204f11edfb..65a24dc1bf25f 100644
--- a/pandas/sparse/panel.py
+++ b/pandas/sparse/panel.py
@@ -172,6 +172,21 @@ def _set_items(self, new_items):
# DataFrame's columns / "items"
minor_axis = SparsePanelAxis('_minor_axis', 'columns')
+ def _ixs(self, i, axis=0):
+ """
+ for compat as we don't support Block Manager here
+ i : int, slice, or sequence of integers
+ axis : int
+ """
+
+ key = self._get_axis(axis)[i]
+
+ # xs cannot handle a non-scalar key, so just reindex here
+ if com.is_list_like(key):
+ return self.reindex(**{self._get_axis_name(axis): key})
+
+ return self.xs(key, axis=axis)
+
def _get_item_cache(self, key):
return self._frames[key]
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 5d3f7b350250d..5c94f378b88ea 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -1335,6 +1335,65 @@ def test_to_panel_duplicates(self):
idf = df.set_index(['a', 'b'])
assertRaisesRegexp(ValueError, 'non-uniquely indexed', idf.to_panel)
+ def test_panel_dups(self):
+
+ # GH 4960
+ # duplicates in an index
+
+ # items
+ data = np.random.randn(5, 100, 5)
+ no_dup_panel = Panel(data, items=list("ABCDE"))
+ panel = Panel(data, items=list("AACDE"))
+
+ expected = no_dup_panel['A']
+ result = panel.iloc[0]
+ assert_frame_equal(result, expected)
+
+ expected = no_dup_panel['E']
+ result = panel.loc['E']
+ assert_frame_equal(result, expected)
+
+ expected = no_dup_panel.loc[['A','B']]
+ expected.items = ['A','A']
+ result = panel.loc['A']
+ assert_panel_equal(result, expected)
+
+ # major
+ data = np.random.randn(5, 5, 5)
+ no_dup_panel = Panel(data, major_axis=list("ABCDE"))
+ panel = Panel(data, major_axis=list("AACDE"))
+
+ expected = no_dup_panel.loc[:,'A']
+ result = panel.iloc[:,0]
+ assert_frame_equal(result, expected)
+
+ expected = no_dup_panel.loc[:,'E']
+ result = panel.loc[:,'E']
+ assert_frame_equal(result, expected)
+
+ expected = no_dup_panel.loc[:,['A','B']]
+ expected.major_axis = ['A','A']
+ result = panel.loc[:,'A']
+ assert_panel_equal(result, expected)
+
+ # minor
+ data = np.random.randn(5, 100, 5)
+ no_dup_panel = Panel(data, minor_axis=list("ABCDE"))
+ panel = Panel(data, minor_axis=list("AACDE"))
+
+ expected = no_dup_panel.loc[:,:,'A']
+ result = panel.iloc[:,:,0]
+ assert_frame_equal(result, expected)
+
+ expected = no_dup_panel.loc[:,:,'E']
+ result = panel.loc[:,:,'E']
+ assert_frame_equal(result, expected)
+
+ expected = no_dup_panel.loc[:,:,['A','B']]
+ expected.minor_axis = ['A','A']
+ result = panel.loc[:,:,'A']
+ assert_panel_equal(result, expected)
+
def test_filter(self):
pass
diff --git a/pandas/util/testing.py b/pandas/util/testing.py
index b25f85c961798..946a4d94b6045 100644
--- a/pandas/util/testing.py
+++ b/pandas/util/testing.py
@@ -357,12 +357,14 @@ def assert_panelnd_equal(left, right,
right_ind = getattr(right, axis)
assert_index_equal(left_ind, right_ind)
- for col, series in compat.iteritems(left):
- assert col in right, "non-matching column '%s'" % col
- assert_func(series, right[col], check_less_precise=check_less_precise)
-
- for col in right:
- assert col in left
+ for i, item in enumerate(left._get_axis(0)):
+ assert item in right, "non-matching item (right) '%s'" % item
+ litem = left.iloc[i]
+ ritem = right.iloc[i]
+ assert_func(litem, ritem, check_less_precise=check_less_precise)
+
+ for i, item in enumerate(right._get_axis(0)):
+ assert item in left, "non-matching item (left) '%s'" % item
# TODO: strangely check_names fails in py3 ?
_panel_frame_equal = partial(assert_frame_equal, check_names=False)
| TST: update Panel tests to iterate by position rather than location (for matching non-unique)
closes #4960
| https://api.github.com/repos/pandas-dev/pandas/pulls/5097 | 2013-10-03T15:57:50Z | 2013-10-03T21:14:18Z | 2013-10-03T21:14:18Z | 2014-06-30T18:24:07Z |
TST: Groupby filter tests involved len, closing #4447 | diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index e70c01ffcb12f..538831692fd67 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -17,7 +17,7 @@
from pandas.util.decorators import cache_readonly, Appender
import pandas.core.algorithms as algos
import pandas.core.common as com
-from pandas.core.common import _possibly_downcast_to_dtype, notnull
+from pandas.core.common import _possibly_downcast_to_dtype, isnull, notnull
import pandas.lib as lib
import pandas.algos as _algos
@@ -1605,8 +1605,19 @@ def filter(self, func, dropna=True, *args, **kwargs):
else:
wrapper = lambda x: func(x, *args, **kwargs)
- indexers = [self.obj.index.get_indexer(group.index) \
- if wrapper(group) else [] for _ , group in self]
+ # Interpret np.nan as False.
+ def true_and_notnull(x, *args, **kwargs):
+ b = wrapper(x, *args, **kwargs)
+ return b and notnull(b)
+
+ try:
+ indexers = [self.obj.index.get_indexer(group.index) \
+ if true_and_notnull(group) else [] \
+ for _ , group in self]
+ except ValueError:
+ raise TypeError("the filter must return a boolean result")
+ except TypeError:
+ raise TypeError("the filter must return a boolean result")
if len(indexers) == 0:
filtered = self.obj.take([]) # because np.concatenate would fail
@@ -2124,7 +2135,8 @@ def add_indexer():
add_indexer()
else:
if getattr(res,'ndim',None) == 1:
- if res.ravel()[0]:
+ val = res.ravel()[0]
+ if val and notnull(val):
add_indexer()
else:
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index fec6460ea31f3..babe72e3ca106 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -2642,9 +2642,37 @@ def raise_if_sum_is_zero(x):
s = pd.Series([-1,0,1,2])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
- self.assertRaises(ValueError,
+ self.assertRaises(TypeError,
lambda: grouped.filter(raise_if_sum_is_zero))
+ def test_filter_bad_shapes(self):
+ df = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc'), 'C': np.arange(8)})
+ s = df['B']
+ g_df = df.groupby('B')
+ g_s = s.groupby(s)
+
+ f = lambda x: x
+ self.assertRaises(TypeError, lambda: g_df.filter(f))
+ self.assertRaises(TypeError, lambda: g_s.filter(f))
+
+ f = lambda x: x == 1
+ self.assertRaises(TypeError, lambda: g_df.filter(f))
+ self.assertRaises(TypeError, lambda: g_s.filter(f))
+
+ f = lambda x: np.outer(x, x)
+ self.assertRaises(TypeError, lambda: g_df.filter(f))
+ self.assertRaises(TypeError, lambda: g_s.filter(f))
+
+ def test_filter_nan_is_false(self):
+ df = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc'), 'C': np.arange(8)})
+ s = df['B']
+ g_df = df.groupby(df['B'])
+ g_s = s.groupby(s)
+
+ f = lambda x: np.nan
+ assert_frame_equal(g_df.filter(f), df.loc[[]])
+ assert_series_equal(g_s.filter(f), s[[]])
+
def test_filter_against_workaround(self):
np.random.seed(0)
# Series of ints
@@ -2697,6 +2725,29 @@ def test_filter_against_workaround(self):
new_way = grouped.filter(lambda x: x['ints'].mean() > N/20)
assert_frame_equal(new_way.sort_index(), old_way.sort_index())
+ def test_filter_using_len(self):
+ # BUG GH4447
+ df = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc'), 'C': np.arange(8)})
+ grouped = df.groupby('B')
+ actual = grouped.filter(lambda x: len(x) > 2)
+ expected = DataFrame({'A': np.arange(2, 6), 'B': list('bbbb'), 'C': np.arange(2, 6)}, index=np.arange(2, 6))
+ assert_frame_equal(actual, expected)
+
+ actual = grouped.filter(lambda x: len(x) > 4)
+ expected = df.ix[[]]
+ assert_frame_equal(actual, expected)
+
+ # Series have always worked properly, but we'll test anyway.
+ s = df['B']
+ grouped = s.groupby(s)
+ actual = grouped.filter(lambda x: len(x) > 2)
+ expected = Series(4*['b'], index=np.arange(2, 6))
+ assert_series_equal(actual, expected)
+
+ actual = grouped.filter(lambda x: len(x) > 4)
+ expected = s[[]]
+ assert_series_equal(actual, expected)
+
def test_groupby_whitelist(self):
from string import ascii_lowercase
letters = np.array(list(ascii_lowercase))
| closed #4447 (tests only, so no release notes necessary)
...which was apparently fixed by #4657. More tests looking for shape-related bugs in filter would be nice. So far I have no discovered any.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5096 | 2013-10-03T14:39:24Z | 2013-10-13T23:37:53Z | 2013-10-13T23:37:53Z | 2014-06-29T17:32:18Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.