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 |
|---|---|---|---|---|---|---|---|
CI: Pin ipython version | diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst
index ed7688f229ca8..474068e43a4d4 100644
--- a/doc/source/user_guide/timeseries.rst
+++ b/doc/source/user_guide/timeseries.rst
@@ -1981,7 +1981,6 @@ frequency. Arithmetic is not allowed between ``Period`` with different ``freq``
p = pd.Period("2012-01", freq="2M")
p + 2
p - 1
- @okexcept
p == pd.Period("2012-01", freq="3M")
| - [x] closes #48431 (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.
Should fix the docbuild till they release the fix
| https://api.github.com/repos/pandas-dev/pandas/pulls/48444 | 2022-09-07T17:38:30Z | 2022-09-07T20:24:04Z | 2022-09-07T20:24:04Z | 2022-09-07T20:47:48Z |
BUG: Fix pyarrow groupby tests | diff --git a/pandas/core/series.py b/pandas/core/series.py
index 167590331754d..fc97a8f04e0cc 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -573,7 +573,10 @@ def _set_axis(self, axis: int, labels: AnyArrayLike | list) -> None:
"""
labels = ensure_index(labels)
- if labels._is_all_dates:
+ if labels._is_all_dates and not (
+ type(labels) is Index and not isinstance(labels.dtype, np.dtype)
+ ):
+ # exclude e.g. timestamp[ns][pyarrow] dtype from this casting
deep_labels = labels
if isinstance(labels, CategoricalIndex):
deep_labels = labels.categories
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 0385e4482a32b..f700a7c918d49 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -516,15 +516,6 @@ def test_groupby_extension_no_sort(self, data_for_grouping, request):
reason=f"pyarrow doesn't support factorizing {pa_dtype}",
)
)
- elif pa.types.is_date(pa_dtype) or (
- pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is None
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- raises=AttributeError,
- reason="GH 34986",
- )
- )
super().test_groupby_extension_no_sort(data_for_grouping)
def test_groupby_extension_transform(self, data_for_grouping, request):
@@ -551,8 +542,7 @@ def test_groupby_extension_apply(
self, data_for_grouping, groupby_apply_op, request
):
pa_dtype = data_for_grouping.dtype.pyarrow_dtype
- # Is there a better way to get the "series" ID for groupby_apply_op?
- is_series = "series" in request.node.nodeid
+ # TODO: Is there a better way to get the "object" ID for groupby_apply_op?
is_object = "object" in request.node.nodeid
if pa.types.is_duration(pa_dtype):
request.node.add_marker(
@@ -571,13 +561,6 @@ def test_groupby_extension_apply(
reason="GH 47514: _concat_datetime expects axis arg.",
)
)
- elif not is_series:
- request.node.add_marker(
- pytest.mark.xfail(
- raises=AttributeError,
- reason="GH 34986",
- )
- )
with tm.maybe_produces_warning(
PerformanceWarning, pa_version_under7p0, check_stacklevel=False
):
@@ -610,16 +593,6 @@ def test_groupby_extension_agg(self, as_index, data_for_grouping, request):
reason=f"pyarrow doesn't support factorizing {pa_dtype}",
)
)
- elif as_index is True and (
- pa.types.is_date(pa_dtype)
- or (pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is None)
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- raises=AttributeError,
- reason="GH 34986",
- )
- )
with tm.maybe_produces_warning(
PerformanceWarning, pa_version_under7p0, check_stacklevel=False
):
@@ -1464,12 +1437,13 @@ def test_diff(self, data, periods, request):
@pytest.mark.parametrize("dropna", [True, False])
def test_value_counts(self, all_data, dropna, request):
pa_dtype = all_data.dtype.pyarrow_dtype
- if pa.types.is_date(pa_dtype) or (
- pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is None
- ):
+ if (
+ pa.types.is_date(pa_dtype)
+ or (pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is None)
+ ) and dropna:
request.node.add_marker(
pytest.mark.xfail(
- raises=AttributeError,
+ raises=NotImplementedError, # tries casting to i8
reason="GH 34986",
)
)
@@ -1489,7 +1463,7 @@ def test_value_counts_with_normalize(self, data, request):
):
request.node.add_marker(
pytest.mark.xfail(
- raises=AttributeError,
+ raises=NotImplementedError, # tries casting to i8
reason="GH 34986",
)
)
| orthogonal to #48428 | https://api.github.com/repos/pandas-dev/pandas/pulls/48443 | 2022-09-07T17:29:10Z | 2022-09-09T22:02:58Z | 2022-09-09T22:02:58Z | 2022-09-12T18:58:52Z |
Backport PR #48419 on branch 1.5.x (BUG: ensure to return writable buffer in __dataframe__ interchange for categorical column) | diff --git a/pandas/core/interchange/column.py b/pandas/core/interchange/column.py
index 83f57d5bb8d3e..c9bafbfaad2d2 100644
--- a/pandas/core/interchange/column.py
+++ b/pandas/core/interchange/column.py
@@ -270,7 +270,7 @@ def _get_data_buffer(
buffer = PandasBuffer(self._col.to_numpy(), allow_copy=self._allow_copy)
dtype = self.dtype
elif self.dtype[0] == DtypeKind.CATEGORICAL:
- codes = self._col.values.codes
+ codes = self._col.values._codes
buffer = PandasBuffer(codes, allow_copy=self._allow_copy)
dtype = self._dtype_from_pandasdtype(codes.dtype)
elif self.dtype[0] == DtypeKind.STRING:
diff --git a/pandas/tests/interchange/test_impl.py b/pandas/tests/interchange/test_impl.py
index b4c27ba31317b..2abe975ebcc12 100644
--- a/pandas/tests/interchange/test_impl.py
+++ b/pandas/tests/interchange/test_impl.py
@@ -5,6 +5,7 @@
import pytest
from pandas._libs.tslibs import iNaT
+import pandas.util._test_decorators as td
import pandas as pd
import pandas._testing as tm
@@ -193,3 +194,13 @@ def test_datetime():
assert col.describe_null == (ColumnNullType.USE_SENTINEL, iNaT)
tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))
+
+
+@td.skip_if_np_lt("1.23")
+def test_categorical_to_numpy_dlpack():
+ # https://github.com/pandas-dev/pandas/issues/48393
+ df = pd.DataFrame({"A": pd.Categorical(["a", "b", "a"])})
+ col = df.__dataframe__().get_column_by_name("A")
+ result = np.from_dlpack(col.get_buffers()["data"][0])
+ expected = np.array([0, 1, 0], dtype="int8")
+ tm.assert_numpy_array_equal(result, expected)
| Backport PR #48419: BUG: ensure to return writable buffer in __dataframe__ interchange for categorical column | https://api.github.com/repos/pandas-dev/pandas/pulls/48441 | 2022-09-07T16:29:10Z | 2022-09-07T20:46:06Z | 2022-09-07T20:46:06Z | 2022-09-07T20:46:07Z |
DOC: Improve docs for plotting | diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index 8d6c2062f9484..17befb3d27da4 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -266,6 +266,7 @@ def hist_frame(
Parameters
----------
+%(data)s\
column : str or list of str, optional
Column name or list of names, or vector.
Can be any valid input to :meth:`pandas.DataFrame.groupby`.
@@ -276,7 +277,7 @@ def hist_frame(
The matplotlib axes to be used by boxplot.
fontsize : float or str
Tick label font size in points or as a string (e.g., `large`).
-rot : int or float, default 0
+rot : float, default 0
The rotation angle of labels (in degrees)
with respect to the screen coordinate system.
grid : bool, default True
@@ -466,7 +467,7 @@ def hist_frame(
"""
-@Substitution(backend="")
+@Substitution(data="data : DataFrame\n The data to visualize.\n", backend="")
@Appender(_boxplot_doc)
def boxplot(
data: DataFrame,
@@ -497,7 +498,7 @@ def boxplot(
)
-@Substitution(backend=_backend_doc)
+@Substitution(data="", backend=_backend_doc)
@Appender(_boxplot_doc)
def boxplot_frame(
self,
@@ -556,7 +557,7 @@ def boxplot_frame_groupby(
column : column name or list of names, or vector
Can be any valid input to groupby.
- fontsize : int or str
+ fontsize : float or str
rot : label rotation angle
grid : Setting this to True will show the grid
ax : Matplotlib axis object, default None
@@ -730,10 +731,10 @@ class PlotAccessor(PandasObject):
Now applicable to planar plots (`scatter`, `hexbin`).
- rot : int, default None
+ rot : float, default None
Rotation for ticks (xticks for vertical, yticks for horizontal
plots).
- fontsize : int, default None
+ fontsize : float, default None
Font size for xticks and yticks.
colormap : str or matplotlib colormap object, default None
Colormap to select colors from. If string, load colormap with that
diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py
index cad03b1923e9d..2106e05a817ce 100644
--- a/pandas/plotting/_matplotlib/hist.py
+++ b/pandas/plotting/_matplotlib/hist.py
@@ -323,7 +323,7 @@ def _grouped_hist(
layout : optional
sharex : bool, default False
sharey : bool, default False
- rot : int, default 90
+ rot : float, default 90
grid : bool, default True
legend: : bool, default False
kwargs : dict, keyword arguments passed to matplotlib.Axes.hist
diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py
index 4f197b5fc7095..9dbf43c5d70c5 100644
--- a/pandas/plotting/_misc.py
+++ b/pandas/plotting/_misc.py
@@ -19,7 +19,7 @@
)
-def table(ax, data, rowLabels=None, colLabels=None, **kwargs):
+def table(ax, data, **kwargs):
"""
Helper function to convert DataFrame and Series to matplotlib.table.
@@ -285,14 +285,18 @@ def andrews_curves(
----------
frame : DataFrame
Data to be plotted, preferably normalized to (0.0, 1.0).
- class_column : Name of the column containing class names
- ax : matplotlib axes object, default None
- samples : Number of points to plot in each curve
- color : list or tuple, optional
- Colors to use for the different classes.
+ class_column : label
+ Name of the column containing class names.
+ ax : axes object, default None
+ Axes to use.
+ samples : int
+ Number of points to plot in each curve.
+ color : str, list[str] or tuple[str], optional
+ Colors to use for the different classes. Colors can be strings
+ or 3-element floating point RBG values.
colormap : str or matplotlib colormap object, default None
- Colormap to select colors from. If string, load colormap with that name
- from matplotlib.
+ Colormap to select colors from. If a string, load colormap with that
+ name from matplotlib.
**kwargs
Options to pass to matplotlib plotting method.
@@ -430,7 +434,7 @@ def parallel_coordinates(
Returns
-------
- class:`matplotlib.axis.Axes`
+ matplotlib.axis.Axes
Examples
--------
@@ -470,19 +474,21 @@ def lag_plot(series: Series, lag: int = 1, ax: Axes | None = None, **kwds) -> Ax
Parameters
----------
- series : Time series
- lag : lag of the scatter plot, default 1
+ series : Series
+ The time series to visualize.
+ lag : int, default 1
+ Lag length of the scatter plot.
ax : Matplotlib axis object, optional
+ The matplotlib axis object to use.
**kwds
Matplotlib scatter method keyword arguments.
Returns
-------
- class:`matplotlib.axis.Axes`
+ matplotlib.axis.Axes
Examples
--------
-
Lag plots are most commonly used to look for patterns in time series data.
Given the following time series
@@ -514,18 +520,19 @@ def autocorrelation_plot(series: Series, ax: Axes | None = None, **kwargs) -> Ax
Parameters
----------
- series : Time series
+ series : Series
+ The time series to visualize.
ax : Matplotlib axis object, optional
+ The matplotlib axis object to use.
**kwargs
Options to pass to matplotlib plotting method.
Returns
-------
- class:`matplotlib.axis.Axes`
+ matplotlib.axis.Axes
Examples
--------
-
The horizontal lines in the plot correspond to 95% and 99% confidence bands.
The dashed line is 99% confidence band.
| - [X] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
Some doc issues found when adding typing to pandas-stubs | https://api.github.com/repos/pandas-dev/pandas/pulls/48437 | 2022-09-07T10:51:08Z | 2022-09-09T17:42:55Z | 2022-09-09T17:42:55Z | 2022-10-13T17:00:49Z |
Backport PR #48411 on branch 1.5.x (REGR: get_loc for ExtensionEngine not returning bool indexer for na) | diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx
index 0cf7c4d45c634..617760c2981c4 100644
--- a/pandas/_libs/index.pyx
+++ b/pandas/_libs/index.pyx
@@ -1061,7 +1061,7 @@ cdef class ExtensionEngine(SharedEngine):
cdef ndarray _get_bool_indexer(self, val):
if checknull(val):
- return self.values.isna().view("uint8")
+ return self.values.isna()
try:
return self.values == val
diff --git a/pandas/tests/indexes/test_indexing.py b/pandas/tests/indexes/test_indexing.py
index 739039241a31d..ab934df992d61 100644
--- a/pandas/tests/indexes/test_indexing.py
+++ b/pandas/tests/indexes/test_indexing.py
@@ -20,6 +20,7 @@
from pandas.errors import InvalidIndexError
from pandas import (
+ NA,
DatetimeIndex,
Index,
IntervalIndex,
@@ -221,6 +222,13 @@ def test_get_loc_generator(self, index):
# MultiIndex specifically checks for generator; others for scalar
index.get_loc(x for x in range(5))
+ def test_get_loc_masked_duplicated_na(self):
+ # GH#48411
+ idx = Index([1, 2, NA, NA], dtype="Int64")
+ result = idx.get_loc(NA)
+ expected = np.array([False, False, True, True])
+ tm.assert_numpy_array_equal(result, expected)
+
class TestGetIndexer:
def test_get_indexer_base(self, index):
@@ -253,6 +261,13 @@ def test_get_indexer_consistency(self, index):
assert isinstance(indexer, np.ndarray)
assert indexer.dtype == np.intp
+ def test_get_indexer_masked_duplicated_na(self):
+ # GH#48411
+ idx = Index([1, 2, NA, NA], dtype="Int64")
+ result = idx.get_indexer_for(Index([1, NA], dtype="Int64"))
+ expected = np.array([0, 2, 3], dtype=result.dtype)
+ tm.assert_numpy_array_equal(result, expected)
+
class TestConvertSliceIndexer:
def test_convert_almost_null_slice(self, index):
| Backport PR #48411: REGR: get_loc for ExtensionEngine not returning bool indexer for na | https://api.github.com/repos/pandas-dev/pandas/pulls/48430 | 2022-09-07T07:12:48Z | 2022-09-07T10:39:51Z | 2022-09-07T10:39:51Z | 2022-09-07T10:39:52Z |
ENH: Add index param to df.to_dict | diff --git a/doc/source/whatsnew/v1.6.0.rst b/doc/source/whatsnew/v1.6.0.rst
index aff950c6933dd..266480f2e28e2 100644
--- a/doc/source/whatsnew/v1.6.0.rst
+++ b/doc/source/whatsnew/v1.6.0.rst
@@ -31,6 +31,7 @@ Other enhancements
- :meth:`.GroupBy.quantile` now preserving nullable dtypes instead of casting to numpy dtypes (:issue:`37493`)
- :meth:`Series.add_suffix`, :meth:`DataFrame.add_suffix`, :meth:`Series.add_prefix` and :meth:`DataFrame.add_prefix` support an ``axis`` argument. If ``axis`` is set, the default behaviour of which axis to consider can be overwritten (:issue:`47819`)
- :func:`assert_frame_equal` now shows the first element where the DataFrames differ, analogously to ``pytest``'s output (:issue:`47910`)
+- Added ``index`` parameter to :meth:`DataFrame.to_dict` (:issue:`46398`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index c52a7b0daa30e..26a068fc94395 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1864,6 +1864,7 @@ def to_dict(
"dict", "list", "series", "split", "tight", "records", "index"
] = "dict",
into: type[dict] = dict,
+ index: bool = True,
) -> dict | list[dict]:
"""
Convert the DataFrame to a dictionary.
@@ -1900,6 +1901,13 @@ def to_dict(
instance of the mapping type you want. If you want a
collections.defaultdict, you must pass it initialized.
+ index : bool, default True
+ Whether to include the index item (and index_names item if `orient`
+ is 'tight') in the returned dictionary. Can only be ``False``
+ when `orient` is 'split' or 'tight'.
+
+ .. versionadded:: 1.6.0
+
Returns
-------
dict, list or collections.abc.Mapping
@@ -2005,6 +2013,11 @@ def to_dict(
elif orient.startswith("i"):
orient = "index"
+ if not index and orient not in ["split", "tight"]:
+ raise ValueError(
+ "'index=False' is only valid when 'orient' is 'split' or 'tight'"
+ )
+
if orient == "dict":
return into_c((k, v.to_dict(into)) for k, v in self.items())
@@ -2015,8 +2028,8 @@ def to_dict(
elif orient == "split":
return into_c(
- (
- ("index", self.index.tolist()),
+ ((("index", self.index.tolist()),) if index else ())
+ + (
("columns", self.columns.tolist()),
(
"data",
@@ -2030,8 +2043,8 @@ def to_dict(
elif orient == "tight":
return into_c(
- (
- ("index", self.index.tolist()),
+ ((("index", self.index.tolist()),) if index else ())
+ + (
("columns", self.columns.tolist()),
(
"data",
@@ -2040,9 +2053,9 @@ def to_dict(
for t in self.itertuples(index=False, name=None)
],
),
- ("index_names", list(self.index.names)),
- ("column_names", list(self.columns.names)),
)
+ + ((("index_names", list(self.index.names)),) if index else ())
+ + (("column_names", list(self.columns.names)),)
)
elif orient == "series":
diff --git a/pandas/tests/frame/methods/test_to_dict.py b/pandas/tests/frame/methods/test_to_dict.py
index 6d5c32cae7368..613f7147a4a7d 100644
--- a/pandas/tests/frame/methods/test_to_dict.py
+++ b/pandas/tests/frame/methods/test_to_dict.py
@@ -421,3 +421,31 @@ def test_to_dict_returns_native_types(self, orient, data, expected_types):
for i, key, value in assertion_iterator:
assert value == data[key][i]
assert type(value) is expected_types[key][i]
+
+ @pytest.mark.parametrize("orient", ["dict", "list", "series", "records", "index"])
+ def test_to_dict_index_false_error(self, orient):
+ # GH#46398
+ df = DataFrame({"col1": [1, 2], "col2": [3, 4]}, index=["row1", "row2"])
+ msg = "'index=False' is only valid when 'orient' is 'split' or 'tight'"
+ with pytest.raises(ValueError, match=msg):
+ df.to_dict(orient=orient, index=False)
+
+ @pytest.mark.parametrize(
+ "orient, expected",
+ [
+ ("split", {"columns": ["col1", "col2"], "data": [[1, 3], [2, 4]]}),
+ (
+ "tight",
+ {
+ "columns": ["col1", "col2"],
+ "data": [[1, 3], [2, 4]],
+ "column_names": [None],
+ },
+ ),
+ ],
+ )
+ def test_to_dict_index_false(self, orient, expected):
+ # GH#46398
+ df = DataFrame({"col1": [1, 2], "col2": [3, 4]}, index=["row1", "row2"])
+ result = df.to_dict(orient=orient, index=False)
+ tm.assert_dict_equal(result, expected)
| - [x] closes #46398
- [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/48429 | 2022-09-07T05:50:04Z | 2022-09-13T16:46:03Z | 2022-09-13T16:46:03Z | 2022-10-13T17:00:48Z |
BUG/TST: fix a bunch of arraymanager+pyarrow tests | diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index dcf69dfda1ae8..fd156ccfc8b31 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -297,19 +297,10 @@ def apply_with_block(self: T, f, align_keys=None, swap_axis=True, **kwargs) -> T
if obj.ndim == 2:
kwargs[k] = obj[[i]]
- # error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no
- # attribute "tz"
- if hasattr(arr, "tz") and arr.tz is None: # type: ignore[union-attr]
- # DatetimeArray needs to be converted to ndarray for DatetimeLikeBlock
-
- # error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no
- # attribute "_data"
- arr = arr._data # type: ignore[union-attr]
- elif arr.dtype.kind == "m" and not isinstance(arr, np.ndarray):
- # TimedeltaArray needs to be converted to ndarray for TimedeltaBlock
-
- # error: "ExtensionArray" has no attribute "_data"
- arr = arr._data # type: ignore[attr-defined]
+ if isinstance(arr.dtype, np.dtype) and not isinstance(arr, np.ndarray):
+ # i.e. TimedeltaArray, DatetimeArray with tz=None. Need to
+ # convert for the Block constructors.
+ arr = np.asarray(arr)
if self.ndim == 2:
arr = ensure_block_shape(arr, 2)
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 0385e4482a32b..e491909aabe7a 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -716,63 +716,6 @@ class TestBaseMissing(base.BaseMissingTests):
def test_dropna_array(self, data_missing):
super().test_dropna_array(data_missing)
- def test_fillna_limit_pad(self, data_missing, using_array_manager, request):
- if using_array_manager and pa.types.is_duration(
- data_missing.dtype.pyarrow_dtype
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
- super().test_fillna_limit_pad(data_missing)
-
- def test_fillna_limit_backfill(self, data_missing, using_array_manager, request):
- if using_array_manager and pa.types.is_duration(
- data_missing.dtype.pyarrow_dtype
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
- super().test_fillna_limit_backfill(data_missing)
-
- def test_fillna_series(self, data_missing, using_array_manager, request):
- if using_array_manager and pa.types.is_duration(
- data_missing.dtype.pyarrow_dtype
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
- super().test_fillna_series(data_missing)
-
- def test_fillna_series_method(
- self, data_missing, fillna_method, using_array_manager, request
- ):
- if using_array_manager and pa.types.is_duration(
- data_missing.dtype.pyarrow_dtype
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
- super().test_fillna_series_method(data_missing, fillna_method)
-
- def test_fillna_frame(self, data_missing, using_array_manager, request):
- if using_array_manager and pa.types.is_duration(
- data_missing.dtype.pyarrow_dtype
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
- super().test_fillna_frame(data_missing)
-
class TestBasePrinting(base.BasePrintingTests):
def test_series_repr(self, data, request):
@@ -981,7 +924,7 @@ def test_setitem_scalar_series(self, data, box_in_series, request):
)
super().test_setitem_scalar_series(data, box_in_series)
- def test_setitem_sequence(self, data, box_in_series, using_array_manager, request):
+ def test_setitem_sequence(self, data, box_in_series, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -989,47 +932,9 @@ def test_setitem_sequence(self, data, box_in_series, using_array_manager, reques
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif (
- using_array_manager
- and pa.types.is_duration(data.dtype.pyarrow_dtype)
- and box_in_series
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_sequence(data, box_in_series)
- def test_setitem_sequence_mismatched_length_raises(
- self, data, as_array, using_array_manager, request
- ):
- if using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
- super().test_setitem_sequence_mismatched_length_raises(data, as_array)
-
- def test_setitem_empty_indexer(
- self, data, box_in_series, using_array_manager, request
- ):
- if (
- using_array_manager
- and pa.types.is_duration(data.dtype.pyarrow_dtype)
- and box_in_series
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
- super().test_setitem_empty_indexer(data, box_in_series)
-
- def test_setitem_sequence_broadcasts(
- self, data, box_in_series, using_array_manager, request
- ):
+ def test_setitem_sequence_broadcasts(self, data, box_in_series, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1037,20 +942,10 @@ def test_setitem_sequence_broadcasts(
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif (
- using_array_manager
- and pa.types.is_duration(data.dtype.pyarrow_dtype)
- and box_in_series
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_sequence_broadcasts(data, box_in_series)
@pytest.mark.parametrize("setter", ["loc", "iloc"])
- def test_setitem_scalar(self, data, setter, using_array_manager, request):
+ def test_setitem_scalar(self, data, setter, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1058,15 +953,9 @@ def test_setitem_scalar(self, data, setter, using_array_manager, request):
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_scalar(data, setter)
- def test_setitem_loc_scalar_mixed(self, data, using_array_manager, request):
+ def test_setitem_loc_scalar_mixed(self, data, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1074,15 +963,9 @@ def test_setitem_loc_scalar_mixed(self, data, using_array_manager, request):
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_loc_scalar_mixed(data)
- def test_setitem_loc_scalar_single(self, data, using_array_manager, request):
+ def test_setitem_loc_scalar_single(self, data, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1090,17 +973,9 @@ def test_setitem_loc_scalar_single(self, data, using_array_manager, request):
reason=f"Not supported by pyarrow < 2.0 with timestamp type {tz}"
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_loc_scalar_single(data)
- def test_setitem_loc_scalar_multiple_homogoneous(
- self, data, using_array_manager, request
- ):
+ def test_setitem_loc_scalar_multiple_homogoneous(self, data, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1108,15 +983,9 @@ def test_setitem_loc_scalar_multiple_homogoneous(
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_loc_scalar_multiple_homogoneous(data)
- def test_setitem_iloc_scalar_mixed(self, data, using_array_manager, request):
+ def test_setitem_iloc_scalar_mixed(self, data, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1124,15 +993,9 @@ def test_setitem_iloc_scalar_mixed(self, data, using_array_manager, request):
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_iloc_scalar_mixed(data)
- def test_setitem_iloc_scalar_single(self, data, using_array_manager, request):
+ def test_setitem_iloc_scalar_single(self, data, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1140,17 +1003,9 @@ def test_setitem_iloc_scalar_single(self, data, using_array_manager, request):
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_iloc_scalar_single(data)
- def test_setitem_iloc_scalar_multiple_homogoneous(
- self, data, using_array_manager, request
- ):
+ def test_setitem_iloc_scalar_multiple_homogoneous(self, data, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1158,12 +1013,6 @@ def test_setitem_iloc_scalar_multiple_homogoneous(
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_iloc_scalar_multiple_homogoneous(data)
@pytest.mark.parametrize(
@@ -1175,9 +1024,7 @@ def test_setitem_iloc_scalar_multiple_homogoneous(
],
ids=["numpy-array", "boolean-array", "boolean-array-na"],
)
- def test_setitem_mask(
- self, data, mask, box_in_series, using_array_manager, request
- ):
+ def test_setitem_mask(self, data, mask, box_in_series, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1185,21 +1032,9 @@ def test_setitem_mask(
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif (
- using_array_manager
- and pa.types.is_duration(data.dtype.pyarrow_dtype)
- and box_in_series
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_mask(data, mask, box_in_series)
- def test_setitem_mask_boolean_array_with_na(
- self, data, box_in_series, using_array_manager, request
- ):
+ def test_setitem_mask_boolean_array_with_na(self, data, box_in_series, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
unit = getattr(data.dtype.pyarrow_dtype, "unit", None)
if pa_version_under2p0 and tz not in (None, "UTC") and unit == "us":
@@ -1208,16 +1043,6 @@ def test_setitem_mask_boolean_array_with_na(
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif (
- using_array_manager
- and pa.types.is_duration(data.dtype.pyarrow_dtype)
- and box_in_series
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_mask_boolean_array_with_na(data, box_in_series)
@pytest.mark.parametrize(
@@ -1225,9 +1050,7 @@ def test_setitem_mask_boolean_array_with_na(
[[0, 1, 2], pd.array([0, 1, 2], dtype="Int64"), np.array([0, 1, 2])],
ids=["list", "integer-array", "numpy-array"],
)
- def test_setitem_integer_array(
- self, data, idx, box_in_series, using_array_manager, request
- ):
+ def test_setitem_integer_array(self, data, idx, box_in_series, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1235,23 +1058,11 @@ def test_setitem_integer_array(
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif (
- using_array_manager
- and pa.types.is_duration(data.dtype.pyarrow_dtype)
- and box_in_series
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_integer_array(data, idx, box_in_series)
@pytest.mark.parametrize("as_callable", [True, False])
@pytest.mark.parametrize("setter", ["loc", None])
- def test_setitem_mask_aligned(
- self, data, as_callable, setter, using_array_manager, request
- ):
+ def test_setitem_mask_aligned(self, data, as_callable, setter, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1259,16 +1070,10 @@ def test_setitem_mask_aligned(
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_mask_aligned(data, as_callable, setter)
@pytest.mark.parametrize("setter", ["loc", None])
- def test_setitem_mask_broadcast(self, data, setter, using_array_manager, request):
+ def test_setitem_mask_broadcast(self, data, setter, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1276,12 +1081,6 @@ def test_setitem_mask_broadcast(self, data, setter, using_array_manager, request
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_mask_broadcast(data, setter)
def test_setitem_tuple_index(self, data, request):
@@ -1294,7 +1093,7 @@ def test_setitem_tuple_index(self, data, request):
)
super().test_setitem_tuple_index(data)
- def test_setitem_slice(self, data, box_in_series, using_array_manager, request):
+ def test_setitem_slice(self, data, box_in_series, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1302,19 +1101,9 @@ def test_setitem_slice(self, data, box_in_series, using_array_manager, request):
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif (
- using_array_manager
- and pa.types.is_duration(data.dtype.pyarrow_dtype)
- and box_in_series
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_slice(data, box_in_series)
- def test_setitem_loc_iloc_slice(self, data, using_array_manager, request):
+ def test_setitem_loc_iloc_slice(self, data, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1322,12 +1111,6 @@ def test_setitem_loc_iloc_slice(self, data, using_array_manager, request):
reason=f"Not supported by pyarrow < 2.0 with timestamp type {tz}"
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_loc_iloc_slice(data)
def test_setitem_slice_array(self, data, request):
@@ -1340,9 +1123,7 @@ def test_setitem_slice_array(self, data, request):
)
super().test_setitem_slice_array(data)
- def test_setitem_with_expansion_dataframe_column(
- self, data, full_indexer, using_array_manager, request
- ):
+ def test_setitem_with_expansion_dataframe_column(self, data, full_indexer, request):
# Is there a better way to get the full_indexer id "null_slice"?
is_null_slice = "null_slice" in request.node.nodeid
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
@@ -1352,21 +1133,9 @@ def test_setitem_with_expansion_dataframe_column(
reason=f"Not supported by pyarrow < 2.0 with timestamp type {tz}"
)
)
- elif (
- using_array_manager
- and pa.types.is_duration(data.dtype.pyarrow_dtype)
- and not is_null_slice
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_with_expansion_dataframe_column(data, full_indexer)
- def test_setitem_with_expansion_row(
- self, data, na_value, using_array_manager, request
- ):
+ def test_setitem_with_expansion_row(self, data, na_value, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1374,15 +1143,9 @@ def test_setitem_with_expansion_row(
reason=(f"Not supported by pyarrow < 2.0 with timestamp type {tz}")
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_with_expansion_row(data, na_value)
- def test_setitem_frame_2d_values(self, data, using_array_manager, request):
+ def test_setitem_frame_2d_values(self, data, request):
tz = getattr(data.dtype.pyarrow_dtype, "tz", None)
if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
@@ -1390,12 +1153,6 @@ def test_setitem_frame_2d_values(self, data, using_array_manager, request):
reason=f"Not supported by pyarrow < 2.0 with timestamp type {tz}"
)
)
- elif using_array_manager and pa.types.is_duration(data.dtype.pyarrow_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="Checking ndim when using arraymanager with duration type"
- )
- )
super().test_setitem_frame_2d_values(data)
@pytest.mark.xfail(reason="GH 45419: pyarrow.ChunkedArray does not support views")
@@ -1678,26 +1435,6 @@ def test_factorize_empty(self, data, request):
)
super().test_factorize_empty(data)
- def test_fillna_copy_frame(self, data_missing, request, using_array_manager):
- pa_dtype = data_missing.dtype.pyarrow_dtype
- if using_array_manager and pa.types.is_duration(pa_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason=f"Checking ndim when using arraymanager with {pa_dtype}"
- )
- )
- super().test_fillna_copy_frame(data_missing)
-
- def test_fillna_copy_series(self, data_missing, request, using_array_manager):
- pa_dtype = data_missing.dtype.pyarrow_dtype
- if using_array_manager and pa.types.is_duration(pa_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason=f"Checking ndim when using arraymanager with {pa_dtype}"
- )
- )
- super().test_fillna_copy_series(data_missing)
-
def test_shift_fill_value(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
tz = getattr(pa_dtype, "tz", None)
@@ -1735,16 +1472,10 @@ def test_insert(self, data, request):
)
super().test_insert(data)
- def test_combine_first(self, data, request, using_array_manager):
+ def test_combine_first(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
tz = getattr(pa_dtype, "tz", None)
- if using_array_manager and pa.types.is_duration(pa_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason=f"Checking ndim when using arraymanager with {pa_dtype}"
- )
- )
- elif pa_version_under2p0 and tz not in (None, "UTC"):
+ if pa_version_under2p0 and tz not in (None, "UTC"):
request.node.add_marker(
pytest.mark.xfail(
reason=f"Not supported by pyarrow < 2.0 with timestamp type {tz}"
@@ -1752,30 +1483,6 @@ def test_combine_first(self, data, request, using_array_manager):
)
super().test_combine_first(data)
- @pytest.mark.parametrize("frame", [True, False])
- @pytest.mark.parametrize(
- "periods, indices",
- [(-2, [2, 3, 4, -1, -1]), (0, [0, 1, 2, 3, 4]), (2, [-1, -1, 0, 1, 2])],
- )
- def test_container_shift(
- self, data, frame, periods, indices, request, using_array_manager
- ):
- pa_dtype = data.dtype.pyarrow_dtype
- if (
- using_array_manager
- and pa.types.is_duration(pa_dtype)
- and periods in (-2, 2)
- ):
- request.node.add_marker(
- pytest.mark.xfail(
- reason=(
- f"Checking ndim when using arraymanager with "
- f"{pa_dtype} and periods={periods}"
- )
- )
- )
- super().test_container_shift(data, frame, periods, indices)
-
@pytest.mark.xfail(
reason="result dtype pyarrow[bool] better than expected dtype object"
)
@@ -1803,15 +1510,9 @@ def test_searchsorted(self, data_for_sorting, as_series, request):
)
super().test_searchsorted(data_for_sorting, as_series)
- def test_where_series(self, data, na_value, as_frame, request, using_array_manager):
+ def test_where_series(self, data, na_value, as_frame, request):
pa_dtype = data.dtype.pyarrow_dtype
- if using_array_manager and pa.types.is_duration(pa_dtype):
- request.node.add_marker(
- pytest.mark.xfail(
- reason=f"Checking ndim when using arraymanager with {pa_dtype}"
- )
- )
- elif pa.types.is_temporal(pa_dtype):
+ if pa.types.is_temporal(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/48428 | 2022-09-07T04:13:44Z | 2022-09-12T19:24:39Z | 2022-09-12T19:24:38Z | 2022-09-13T17:24:00Z |
BLD: Refactor Dockerfile to not install dev enviornment on base | diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index c9c5058fb365c..6aff77c708378 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -153,6 +153,9 @@ jobs:
- name: Build image
run: docker build --pull --no-cache --tag pandas-dev-env .
+ - name: Show environment
+ run: docker run -w /home/pandas pandas-dev-env mamba run -n pandas-dev python -c "import pandas as pd; print(pd.show_versions())"
+
requirements-dev-text-installable:
name: Test install requirements-dev.txt
runs-on: ubuntu-latest
diff --git a/Dockerfile b/Dockerfile
index 02c360d2f3d49..9de8695b24274 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,4 +1,4 @@
-FROM quay.io/condaforge/mambaforge:4.13.0-1
+FROM quay.io/condaforge/mambaforge
# if you forked pandas, you can pass in your own GitHub username to use your fork
# i.e. gh_username=myname
@@ -10,16 +10,12 @@ ENV DEBIAN_FRONTEND=noninteractive
# Configure apt and install packages
RUN apt-get update \
- && apt-get -y install --no-install-recommends apt-utils dialog 2>&1 \
+ && apt-get -y install --no-install-recommends apt-utils git tzdata dialog 2>&1 \
#
- # Install tzdata and configure timezone (fix for tests which try to read from "/etc/localtime")
- && apt-get -y install tzdata \
+ # Configure timezone (fix for tests which try to read from "/etc/localtime")
&& ln -fs /usr/share/zoneinfo/Etc/UTC /etc/localtime \
&& dpkg-reconfigure -f noninteractive tzdata \
#
- # Verify git, process tools, lsb-release (common in install instructions for CLIs) installed
- && apt-get -y install git iproute2 procps iproute2 lsb-release \
- #
# cleanup
&& apt-get autoremove -y \
&& apt-get clean -y \
@@ -35,18 +31,12 @@ RUN mkdir "$pandas_home" \
&& git remote add upstream "https://github.com/pandas-dev/pandas.git" \
&& git pull upstream main
-# Because it is surprisingly difficult to activate a conda environment inside a DockerFile
-# (from personal experience and per https://github.com/ContinuumIO/docker-images/issues/89),
-# we just update the base/root one from the 'environment.yml' file instead of creating a new one.
-#
# Set up environment
-RUN mamba env update -n base -f "$pandas_home/environment.yml"
+RUN mamba env create -f "$pandas_home/environment.yml"
# Build C extensions and pandas
-SHELL ["/bin/bash", "-c"]
-RUN . /opt/conda/etc/profile.d/conda.sh \
- && conda activate base \
- && cd "$pandas_home" \
+SHELL ["mamba", "run", "--no-capture-output", "-n", "pandas-dev", "/bin/bash", "-c"]
+RUN cd "$pandas_home" \
&& export \
&& python setup.py build_ext -j 4 \
&& python -m pip install --no-build-isolation -e .
diff --git a/doc/source/development/contributing_environment.rst b/doc/source/development/contributing_environment.rst
index 070e6d2892bc8..c7613b4744719 100644
--- a/doc/source/development/contributing_environment.rst
+++ b/doc/source/development/contributing_environment.rst
@@ -237,6 +237,16 @@ Run Container::
# Run a container and bind your local repo to the container
docker run -it -w /home/pandas --rm -v path-to-local-pandas-repo:/home/pandas pandas-yourname-env
+Then a ``pandas-dev`` virtual environment will be available with all the development dependencies.
+
+.. code-block:: shell
+
+ root@... :/home/pandas# conda env list
+ # conda environments:
+ #
+ base * /opt/conda
+ pandas-dev /opt/conda/envs/pandas-dev
+
.. note::
If you bind your local repo for the first time, you have to build the C extensions afterwards.
Run the following command inside the container::
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index c479c59082464..30cee571c314f 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -331,6 +331,7 @@ Other enhancements
- Added ``copy`` keyword to :meth:`Series.set_axis` and :meth:`DataFrame.set_axis` to allow user to set axis on a new object without necessarily copying the underlying data (:issue:`47932`)
- :meth:`DataFrame.set_index` now supports a ``copy`` keyword. If ``False``, the underlying data is not copied when a new :class:`DataFrame` is returned (:issue:`48043`)
- The method :meth:`.ExtensionArray.factorize` accepts ``use_na_sentinel=False`` for determining how null values are to be treated (:issue:`46601`)
+- The ``Dockerfile`` now installs a dedicated ``pandas-dev`` virtual environment for pandas development instead of using the ``base`` environment (:issue:`48427`)
.. ---------------------------------------------------------------------------
.. _whatsnew_150.notable_bug_fixes:
| - [x] closes #48382 (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).
* Ensure packages are installed with `--no-install-recommends` and remove some unnecessary packages (saves ~0.7GB)
* Add smoke test to show `pandas-dev` environment is installed.
| https://api.github.com/repos/pandas-dev/pandas/pulls/48427 | 2022-09-07T02:16:56Z | 2022-09-07T20:27:08Z | 2022-09-07T20:27:08Z | 2022-09-07T20:47:23Z |
BUG: Column.size should be a method | diff --git a/pandas/core/interchange/column.py b/pandas/core/interchange/column.py
index 83f57d5bb8d3e..bb78bb7d38afb 100644
--- a/pandas/core/interchange/column.py
+++ b/pandas/core/interchange/column.py
@@ -81,7 +81,6 @@ def __init__(self, column: pd.Series, allow_copy: bool = True) -> None:
self._col = column
self._allow_copy = allow_copy
- @property
def size(self) -> int:
"""
Size of the column, in elements.
diff --git a/pandas/tests/interchange/test_impl.py b/pandas/tests/interchange/test_impl.py
index b4c27ba31317b..328050d0c0cb8 100644
--- a/pandas/tests/interchange/test_impl.py
+++ b/pandas/tests/interchange/test_impl.py
@@ -163,14 +163,14 @@ def test_string():
df = pd.DataFrame({"A": test_str_data})
col = df.__dataframe__().get_column_by_name("A")
- assert col.size == 6
+ assert col.size() == 6
assert col.null_count == 1
assert col.dtype[0] == DtypeKind.STRING
assert col.describe_null == (ColumnNullType.USE_BYTEMASK, 0)
df_sliced = df[1:]
col = df_sliced.__dataframe__().get_column_by_name("A")
- assert col.size == 5
+ assert col.size() == 5
assert col.null_count == 1
assert col.dtype[0] == DtypeKind.STRING
assert col.describe_null == (ColumnNullType.USE_BYTEMASK, 0)
@@ -187,7 +187,7 @@ def test_datetime():
df = pd.DataFrame({"A": [pd.Timestamp("2022-01-01"), pd.NaT]})
col = df.__dataframe__().get_column_by_name("A")
- assert col.size == 2
+ assert col.size() == 2
assert col.null_count == 1
assert col.dtype[0] == DtypeKind.DATETIME
assert col.describe_null == (ColumnNullType.USE_SENTINEL, iNaT)
diff --git a/pandas/tests/interchange/test_spec_conformance.py b/pandas/tests/interchange/test_spec_conformance.py
index 392402871a5fd..965938b111e86 100644
--- a/pandas/tests/interchange/test_spec_conformance.py
+++ b/pandas/tests/interchange/test_spec_conformance.py
@@ -27,7 +27,7 @@ def test_only_one_dtype(test_data, df_from_dict):
null_count = dfX.get_column_by_name(column).null_count
assert null_count == 0
assert isinstance(null_count, int)
- assert dfX.get_column_by_name(column).size == column_size
+ assert dfX.get_column_by_name(column).size() == column_size
assert dfX.get_column_by_name(column).offset == 0
@@ -52,7 +52,7 @@ def test_mixed_dtypes(df_from_dict):
colX = dfX.get_column_by_name(column)
assert colX.null_count == 0
assert isinstance(colX.null_count, int)
- assert colX.size == 3
+ assert colX.size() == 3
assert colX.offset == 0
assert colX.dtype[0] == kind
@@ -118,14 +118,14 @@ def test_column_get_chunks(size, n_chunks, df_from_dict):
dfX = df.__dataframe__()
chunks = list(dfX.get_column(0).get_chunks(n_chunks))
assert len(chunks) == n_chunks
- assert sum(chunk.size for chunk in chunks) == size
+ assert sum(chunk.size() for chunk in chunks) == size
def test_get_columns(df_from_dict):
df = df_from_dict({"a": [0, 1], "b": [2.5, 3.5]})
dfX = df.__dataframe__()
for colX in dfX.get_columns():
- assert colX.size == 2
+ assert colX.size() == 2
assert colX.num_chunks() == 1
# for meanings of dtype[0] see the spec; we cannot import the spec here as this
# file is expected to be vendored *anywhere*
| - [x] closes #48392 (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).
As part of the new interchange protocol in 1.5
| https://api.github.com/repos/pandas-dev/pandas/pulls/48426 | 2022-09-06T22:15:35Z | 2022-09-08T15:14:01Z | 2022-09-08T15:14:01Z | 2022-09-08T15:14:05Z |
Backport PR #48264 on branch 1.5.x (BUG: ArrowExtensionArray._from_* accepts pyarrow arrays) | diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 1f7939011a1f1..cfae5b4cae681 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -224,11 +224,13 @@ def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy=False):
Construct a new ExtensionArray from a sequence of scalars.
"""
pa_dtype = to_pyarrow_type(dtype)
- if isinstance(scalars, cls):
- data = scalars._data
+ is_cls = isinstance(scalars, cls)
+ if is_cls or isinstance(scalars, (pa.Array, pa.ChunkedArray)):
+ if is_cls:
+ scalars = scalars._data
if pa_dtype:
- data = data.cast(pa_dtype)
- return cls(data)
+ scalars = scalars.cast(pa_dtype)
+ return cls(scalars)
else:
return cls(
pa.chunked_array(pa.array(scalars, type=pa_dtype, from_pandas=True))
@@ -242,7 +244,10 @@ def _from_sequence_of_strings(
Construct a new ExtensionArray from a sequence of strings.
"""
pa_type = to_pyarrow_type(dtype)
- if pa.types.is_timestamp(pa_type):
+ if pa_type is None:
+ # Let pyarrow try to infer or raise
+ scalars = strings
+ elif pa.types.is_timestamp(pa_type):
from pandas.core.tools.datetimes import to_datetime
scalars = to_datetime(strings, errors="raise")
@@ -272,8 +277,9 @@ def _from_sequence_of_strings(
scalars = to_numeric(strings, errors="raise")
else:
- # Let pyarrow try to infer or raise
- scalars = strings
+ raise NotImplementedError(
+ f"Converting strings to {pa_type} is not implemented."
+ )
return cls._from_sequence(scalars, dtype=pa_type, copy=copy)
def __getitem__(self, item: PositionalIndexer):
diff --git a/pandas/core/tools/times.py b/pandas/core/tools/times.py
index 030cee3f678f4..87667921bf75a 100644
--- a/pandas/core/tools/times.py
+++ b/pandas/core/tools/times.py
@@ -80,17 +80,20 @@ def _convert_listlike(arg, format):
format_found = False
for element in arg:
time_object = None
- for time_format in formats:
- try:
- time_object = datetime.strptime(element, time_format).time()
- if not format_found:
- # Put the found format in front
- fmt = formats.pop(formats.index(time_format))
- formats.insert(0, fmt)
- format_found = True
- break
- except (ValueError, TypeError):
- continue
+ try:
+ time_object = time.fromisoformat(element)
+ except (ValueError, TypeError):
+ for time_format in formats:
+ try:
+ time_object = datetime.strptime(element, time_format).time()
+ if not format_found:
+ # Put the found format in front
+ fmt = formats.pop(formats.index(time_format))
+ formats.insert(0, fmt)
+ format_found = True
+ break
+ except (ValueError, TypeError):
+ continue
if time_object is not None:
times.append(time_object)
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 43c52ef8848e2..9100b67edbe69 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -21,10 +21,13 @@
import pytest
from pandas.compat import (
+ is_ci_environment,
+ is_platform_windows,
pa_version_under2p0,
pa_version_under3p0,
pa_version_under4p0,
pa_version_under6p0,
+ pa_version_under7p0,
pa_version_under8p0,
pa_version_under9p0,
)
@@ -35,6 +38,8 @@
pa = pytest.importorskip("pyarrow", minversion="1.0.1")
+from pandas.core.arrays.arrow.array import ArrowExtensionArray
+
from pandas.core.arrays.arrow.dtype import ArrowDtype # isort:skip
@@ -222,6 +227,96 @@ def test_from_dtype(self, data, request):
)
super().test_from_dtype(data)
+ def test_from_sequence_pa_array(self, data, request):
+ # https://github.com/pandas-dev/pandas/pull/47034#discussion_r955500784
+ # data._data = pa.ChunkedArray
+ if pa_version_under3p0:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="ChunkedArray has no attribute combine_chunks",
+ )
+ )
+ result = type(data)._from_sequence(data._data)
+ tm.assert_extension_array_equal(result, data)
+ assert isinstance(result._data, pa.ChunkedArray)
+
+ result = type(data)._from_sequence(data._data.combine_chunks())
+ tm.assert_extension_array_equal(result, data)
+ assert isinstance(result._data, pa.ChunkedArray)
+
+ def test_from_sequence_pa_array_notimplemented(self, request):
+ if pa_version_under6p0:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=AttributeError,
+ reason="month_day_nano_interval not implemented by pyarrow.",
+ )
+ )
+ with pytest.raises(NotImplementedError, match="Converting strings to"):
+ ArrowExtensionArray._from_sequence_of_strings(
+ ["12-1"], dtype=pa.month_day_nano_interval()
+ )
+
+ def test_from_sequence_of_strings_pa_array(self, data, request):
+ pa_dtype = data.dtype.pyarrow_dtype
+ if pa_version_under3p0:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="ChunkedArray has no attribute combine_chunks",
+ )
+ )
+ elif pa.types.is_time64(pa_dtype) and pa_dtype.equals("time64[ns]"):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="Nanosecond time parsing not supported.",
+ )
+ )
+ elif pa.types.is_duration(pa_dtype):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=pa.ArrowNotImplementedError,
+ reason=f"pyarrow doesn't support parsing {pa_dtype}",
+ )
+ )
+ elif pa.types.is_boolean(pa_dtype):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason="Iterating over ChunkedArray[bool] returns PyArrow scalars.",
+ )
+ )
+ elif pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None:
+ if pa_version_under7p0:
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=pa.ArrowNotImplementedError,
+ reason=f"pyarrow doesn't support string cast from {pa_dtype}",
+ )
+ )
+ elif is_platform_windows() and is_ci_environment():
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=pa.ArrowInvalid,
+ reason=(
+ "TODO: Set ARROW_TIMEZONE_DATABASE environment variable "
+ "on CI to path to the tzdata for pyarrow."
+ ),
+ )
+ )
+ elif pa_version_under6p0 and pa.types.is_temporal(pa_dtype):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ raises=pa.ArrowNotImplementedError,
+ reason=f"pyarrow doesn't support string cast from {pa_dtype}",
+ )
+ )
+ pa_array = data._data.cast(pa.string())
+ result = type(data)._from_sequence_of_strings(pa_array, dtype=data.dtype)
+ tm.assert_extension_array_equal(result, data)
+
+ pa_array = pa_array.combine_chunks()
+ result = type(data)._from_sequence_of_strings(pa_array, dtype=data.dtype)
+ tm.assert_extension_array_equal(result, data)
+
@pytest.mark.xfail(
raises=NotImplementedError, reason="pyarrow.ChunkedArray backing is 1D."
diff --git a/pandas/tests/tools/test_to_time.py b/pandas/tests/tools/test_to_time.py
index a8316e0f3970c..c80b1e080a1d1 100644
--- a/pandas/tests/tools/test_to_time.py
+++ b/pandas/tests/tools/test_to_time.py
@@ -4,6 +4,8 @@
import numpy as np
import pytest
+from pandas.compat import PY311
+
from pandas import Series
import pandas._testing as tm
from pandas.core.tools.datetimes import to_time as to_time_alias
@@ -40,8 +42,9 @@ def test_parsers_time(self, time_string):
def test_odd_format(self):
new_string = "14.15"
msg = r"Cannot convert arg \['14\.15'\] to a time"
- with pytest.raises(ValueError, match=msg):
- to_time(new_string)
+ if not PY311:
+ with pytest.raises(ValueError, match=msg):
+ to_time(new_string)
assert to_time(new_string, format="%H.%M") == time(14, 15)
def test_arraylike(self):
| Backport PR #48264: BUG: ArrowExtensionArray._from_* accepts pyarrow arrays | https://api.github.com/repos/pandas-dev/pandas/pulls/48422 | 2022-09-06T20:40:26Z | 2022-09-07T07:13:52Z | 2022-09-07T07:13:52Z | 2022-09-07T07:13:52Z |
Backport PR #48398 on branch 1.5.x (WARN: Avoid FutureWarnings in tests) | diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py
index 4cf6706707569..3d7e5c6823e9d 100644
--- a/pandas/tests/frame/methods/test_fillna.py
+++ b/pandas/tests/frame/methods/test_fillna.py
@@ -777,6 +777,6 @@ def test_fillna_nonconsolidated_frame():
],
columns=["i1", "i2", "i3", "f1"],
)
- df_nonconsol = df.pivot("i1", "i2")
+ df_nonconsol = df.pivot(index="i1", columns="i2")
result = df_nonconsol.fillna(0)
assert result.isna().sum().sum() == 0
| Backport PR #48398: WARN: Avoid FutureWarnings in tests | https://api.github.com/repos/pandas-dev/pandas/pulls/48420 | 2022-09-06T19:47:38Z | 2022-09-08T21:13:58Z | 2022-09-08T21:13:58Z | 2022-09-08T21:13:59Z |
BUG: ensure to return writable buffer in __dataframe__ interchange for categorical column | diff --git a/pandas/core/interchange/column.py b/pandas/core/interchange/column.py
index 83f57d5bb8d3e..c9bafbfaad2d2 100644
--- a/pandas/core/interchange/column.py
+++ b/pandas/core/interchange/column.py
@@ -270,7 +270,7 @@ def _get_data_buffer(
buffer = PandasBuffer(self._col.to_numpy(), allow_copy=self._allow_copy)
dtype = self.dtype
elif self.dtype[0] == DtypeKind.CATEGORICAL:
- codes = self._col.values.codes
+ codes = self._col.values._codes
buffer = PandasBuffer(codes, allow_copy=self._allow_copy)
dtype = self._dtype_from_pandasdtype(codes.dtype)
elif self.dtype[0] == DtypeKind.STRING:
diff --git a/pandas/tests/interchange/test_impl.py b/pandas/tests/interchange/test_impl.py
index b4c27ba31317b..2abe975ebcc12 100644
--- a/pandas/tests/interchange/test_impl.py
+++ b/pandas/tests/interchange/test_impl.py
@@ -5,6 +5,7 @@
import pytest
from pandas._libs.tslibs import iNaT
+import pandas.util._test_decorators as td
import pandas as pd
import pandas._testing as tm
@@ -193,3 +194,13 @@ def test_datetime():
assert col.describe_null == (ColumnNullType.USE_SENTINEL, iNaT)
tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))
+
+
+@td.skip_if_np_lt("1.23")
+def test_categorical_to_numpy_dlpack():
+ # https://github.com/pandas-dev/pandas/issues/48393
+ df = pd.DataFrame({"A": pd.Categorical(["a", "b", "a"])})
+ col = df.__dataframe__().get_column_by_name("A")
+ result = np.from_dlpack(col.get_buffers()["data"][0])
+ expected = np.array([0, 1, 0], dtype="int8")
+ tm.assert_numpy_array_equal(result, expected)
| - [x] closes https://github.com/pandas-dev/pandas/issues/48393
- [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
| https://api.github.com/repos/pandas-dev/pandas/pulls/48419 | 2022-09-06T19:23:08Z | 2022-09-07T16:29:01Z | 2022-09-07T16:29:01Z | 2022-09-07T16:29:12Z |
Backport PR #48414 on branch 1.5.x (DOC: Add deprecation to is_categorical) | diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 1173703386491..f5262aa7ceeaa 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -280,6 +280,9 @@ def is_categorical(arr) -> bool:
"""
Check whether an array-like is a Categorical instance.
+ .. deprecated:: 1.1.0
+ Use ``is_categorical_dtype`` instead.
+
Parameters
----------
arr : array-like
| Backport PR #48414: DOC: Add deprecation to is_categorical | https://api.github.com/repos/pandas-dev/pandas/pulls/48418 | 2022-09-06T19:16:24Z | 2022-09-06T20:50:35Z | 2022-09-06T20:50:35Z | 2022-09-06T20:50:35Z |
Revert set_index inplace and copy keyword changes | diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst
index 92729a16c6a30..f939945fc6cda 100644
--- a/doc/source/user_guide/indexing.rst
+++ b/doc/source/user_guide/indexing.rst
@@ -1723,12 +1723,13 @@ the given columns to a MultiIndex:
frame
Other options in ``set_index`` allow you not drop the index columns or to add
-the index without creating a copy of the underlying data:
+the index in-place (without creating a new object):
.. ipython:: python
data.set_index('c', drop=False)
- data.set_index(['a', 'b'], copy=False)
+ data.set_index(['a', 'b'], inplace=True)
+ data
Reset the index
~~~~~~~~~~~~~~~
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index c479c59082464..c63772f5b9a3e 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -329,7 +329,6 @@ Other enhancements
- :meth:`DataFrame.quantile` gained a ``method`` argument that can accept ``table`` to evaluate multi-column quantiles (:issue:`43881`)
- :class:`Interval` now supports checking whether one interval is contained by another interval (:issue:`46613`)
- Added ``copy`` keyword to :meth:`Series.set_axis` and :meth:`DataFrame.set_axis` to allow user to set axis on a new object without necessarily copying the underlying data (:issue:`47932`)
-- :meth:`DataFrame.set_index` now supports a ``copy`` keyword. If ``False``, the underlying data is not copied when a new :class:`DataFrame` is returned (:issue:`48043`)
- The method :meth:`.ExtensionArray.factorize` accepts ``use_na_sentinel=False`` for determining how null values are to be treated (:issue:`46601`)
.. ---------------------------------------------------------------------------
@@ -932,7 +931,6 @@ Other Deprecations
- Deprecated the ``inplace`` keyword in :meth:`DataFrame.set_axis` and :meth:`Series.set_axis`, use ``obj = obj.set_axis(..., copy=False)`` instead (:issue:`48130`)
- Deprecated producing a single element when iterating over a :class:`DataFrameGroupBy` or a :class:`SeriesGroupBy` that has been grouped by a list of length 1; A tuple of length one will be returned instead (:issue:`42795`)
- Fixed up warning message of deprecation of :meth:`MultiIndex.lesort_depth` as public method, as the message previously referred to :meth:`MultiIndex.is_lexsorted` instead (:issue:`38701`)
-- Deprecated the ``inplace`` keyword in :meth:`DataFrame.set_index`, use ``df = df.set_index(..., copy=False)`` instead (:issue:`48115`)
- Deprecated the ``sort_columns`` argument in :meth:`DataFrame.plot` and :meth:`Series.plot` (:issue:`47563`).
- Deprecated positional arguments for all but the first argument of :meth:`DataFrame.to_stata` and :func:`read_stata`, use keyword arguments instead (:issue:`48128`).
- Deprecated the ``mangle_dupe_cols`` argument in :func:`read_csv`, :func:`read_fwf`, :func:`read_table` and :func:`read_excel`. The argument was never implemented, and a new argument where the renaming pattern can be specified will be added instead (:issue:`47718`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4cdd62b038485..13b1a054702fb 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5856,9 +5856,8 @@ def set_index(
*,
drop: bool = ...,
append: bool = ...,
- inplace: Literal[False] | lib.NoDefault = ...,
+ inplace: Literal[False] = ...,
verify_integrity: bool = ...,
- copy: bool | lib.NoDefault = ...,
) -> DataFrame:
...
@@ -5871,7 +5870,6 @@ def set_index(
append: bool = ...,
inplace: Literal[True],
verify_integrity: bool = ...,
- copy: bool | lib.NoDefault = ...,
) -> None:
...
@@ -5881,9 +5879,8 @@ def set_index(
keys,
drop: bool = True,
append: bool = False,
- inplace: bool | lib.NoDefault = lib.no_default,
+ inplace: bool = False,
verify_integrity: bool = False,
- copy: bool | lib.NoDefault = lib.no_default,
) -> DataFrame | None:
"""
Set the DataFrame index using existing columns.
@@ -5906,18 +5903,10 @@ def set_index(
Whether to append columns to existing index.
inplace : bool, default False
Whether to modify the DataFrame rather than creating a new one.
-
- .. deprecated:: 1.5.0
-
verify_integrity : bool, default False
Check the new index for duplicates. Otherwise defer the check until
necessary. Setting to False will improve the performance of this
method.
- copy : bool, default True
- Whether to make a copy of the underlying data when returning a new
- DataFrame.
-
- .. versionadded:: 1.5.0
Returns
-------
@@ -5982,25 +5971,7 @@ def set_index(
3 9 7 2013 84
4 16 10 2014 31
"""
- if inplace is not lib.no_default:
- inplace = validate_bool_kwarg(inplace, "inplace")
- warnings.warn(
- "The 'inplace' keyword in DataFrame.set_index is deprecated "
- "and will be removed in a future version. Use "
- "`df = df.set_index(..., copy=False)` instead.",
- FutureWarning,
- stacklevel=find_stack_level(inspect.currentframe()),
- )
- else:
- inplace = False
-
- if inplace:
- if copy is not lib.no_default:
- raise ValueError("Cannot specify copy when inplace=True")
- copy = False
- elif copy is lib.no_default:
- copy = True
-
+ inplace = validate_bool_kwarg(inplace, "inplace")
self._check_inplace_and_allows_duplicate_labels(inplace)
if not isinstance(keys, list):
keys = [keys]
@@ -6036,7 +6007,7 @@ def set_index(
if inplace:
frame = self
else:
- frame = self.copy(deep=copy)
+ frame = self.copy()
arrays = []
names: list[Hashable] = []
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 5052c27ea47f3..9da9a73b247ff 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -782,9 +782,9 @@ def get_result(self, copy: bool = True) -> DataFrame:
if self.indicator:
result = self._indicator_post_merge(result)
- result = self._maybe_add_join_keys(result, left_indexer, right_indexer)
+ self._maybe_add_join_keys(result, left_indexer, right_indexer)
- result = self._maybe_restore_index_levels(result)
+ self._maybe_restore_index_levels(result)
self._maybe_drop_cross_column(result, self._cross)
@@ -851,7 +851,7 @@ def _indicator_post_merge(self, result: DataFrame) -> DataFrame:
result = result.drop(labels=["_left_indicator", "_right_indicator"], axis=1)
return result
- def _maybe_restore_index_levels(self, result: DataFrame) -> DataFrame:
+ def _maybe_restore_index_levels(self, result: DataFrame) -> None:
"""
Restore index levels specified as `on` parameters
@@ -869,7 +869,7 @@ def _maybe_restore_index_levels(self, result: DataFrame) -> DataFrame:
Returns
-------
- DataFrame
+ None
"""
names_to_restore = []
for name, left_key, right_key in zip(
@@ -893,15 +893,14 @@ def _maybe_restore_index_levels(self, result: DataFrame) -> DataFrame:
names_to_restore.append(name)
if names_to_restore:
- result = result.set_index(names_to_restore, copy=False)
- return result
+ result.set_index(names_to_restore, inplace=True)
def _maybe_add_join_keys(
self,
result: DataFrame,
left_indexer: np.ndarray | None,
right_indexer: np.ndarray | None,
- ) -> DataFrame:
+ ) -> None:
left_has_missing = None
right_has_missing = None
@@ -992,12 +991,11 @@ def _maybe_add_join_keys(
for level_name in result.index.names
]
- result = result.set_index(idx_list, copy=False)
+ result.set_index(idx_list, inplace=True)
else:
result.index = Index(key_col, name=name)
else:
result.insert(i, name or f"key_{i}", key_col)
- return result
def _get_join_indexers(self) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]:
"""return the join indexers"""
@@ -1767,8 +1765,7 @@ def get_result(self, copy: bool = True) -> DataFrame:
result = self._reindex_and_concat(
join_index, left_join_indexer, right_join_indexer, copy=copy
)
-
- result = self._maybe_add_join_keys(result, left_indexer, right_indexer)
+ self._maybe_add_join_keys(result, left_indexer, right_indexer)
return result
diff --git a/pandas/io/parsers/arrow_parser_wrapper.py b/pandas/io/parsers/arrow_parser_wrapper.py
index bb62b1405da3a..2305c209936b6 100644
--- a/pandas/io/parsers/arrow_parser_wrapper.py
+++ b/pandas/io/parsers/arrow_parser_wrapper.py
@@ -117,7 +117,7 @@ def _finalize_output(self, frame: DataFrame) -> DataFrame:
# String case
if item not in frame.columns:
raise ValueError(f"Index {item} invalid")
- frame = frame.set_index(self.index_col, drop=True, copy=False)
+ frame.set_index(self.index_col, drop=True, inplace=True)
# Clear names if headerless and no name given
if self.header is None and not multi_index_named:
frame.index.names = [None] * len(frame.index.names)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 77f35bc09abd3..96ba6b2e84cf3 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -4667,7 +4667,7 @@ def read(
columns.insert(0, n)
s = super().read(where=where, columns=columns, start=start, stop=stop)
if is_multi_index:
- s = s.set_index(self.levels, copy=False)
+ s.set_index(self.levels, inplace=True)
s = s.iloc[:, 0]
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 219b8105561ee..ee6564d103147 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -152,7 +152,7 @@ def _wrap_result(
frame = _parse_date_columns(frame, parse_dates)
if index_col is not None:
- frame = frame.set_index(index_col, copy=False)
+ frame.set_index(index_col, inplace=True)
return frame
@@ -980,7 +980,7 @@ def _query_iterator(
self._harmonize_columns(parse_dates=parse_dates)
if self.index is not None:
- self.frame = self.frame.set_index(self.index, copy=False)
+ self.frame.set_index(self.index, inplace=True)
yield self.frame
@@ -1021,7 +1021,7 @@ def read(
self._harmonize_columns(parse_dates=parse_dates)
if self.index is not None:
- self.frame = self.frame.set_index(self.index, copy=False)
+ self.frame.set_index(self.index, inplace=True)
return self.frame
diff --git a/pandas/tests/frame/methods/test_combine_first.py b/pandas/tests/frame/methods/test_combine_first.py
index f841b763863d2..90df28ce74454 100644
--- a/pandas/tests/frame/methods/test_combine_first.py
+++ b/pandas/tests/frame/methods/test_combine_first.py
@@ -394,12 +394,12 @@ def test_combine_first_string_dtype_only_na(self, nullable_string_dtype):
PerformanceWarning,
pa_version_under7p0 and nullable_string_dtype == "string[pyarrow]",
):
- df = df.set_index(["a", "b"], copy=False)
+ df.set_index(["a", "b"], inplace=True)
with tm.maybe_produces_warning(
PerformanceWarning,
pa_version_under7p0 and nullable_string_dtype == "string[pyarrow]",
):
- df2 = df2.set_index(["a", "b"], copy=False)
+ df2.set_index(["a", "b"], inplace=True)
result = df.combine_first(df2)
with tm.maybe_produces_warning(
PerformanceWarning,
diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py
index b404c34a4ddb8..4c39cf99f18ff 100644
--- a/pandas/tests/frame/methods/test_set_index.py
+++ b/pandas/tests/frame/methods/test_set_index.py
@@ -25,27 +25,6 @@
class TestSetIndex:
- def test_set_index_copy(self):
- # GH#48043
- df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
- expected = DataFrame({"B": [3, 4], "C": [5, 6]}, index=Index([1, 2], name="A"))
-
- res = df.set_index("A", copy=True)
- tm.assert_frame_equal(res, expected)
- assert not any(tm.shares_memory(df[col], res[col]) for col in res.columns)
-
- res = df.set_index("A", copy=False)
- tm.assert_frame_equal(res, expected)
- assert all(tm.shares_memory(df[col], res[col]) for col in res.columns)
-
- msg = "Cannot specify copy when inplace=True"
- with pytest.raises(ValueError, match=msg):
- with tm.assert_produces_warning(FutureWarning, match="The 'inplace'"):
- df.set_index("A", inplace=True, copy=True)
- with pytest.raises(ValueError, match=msg):
- with tm.assert_produces_warning(FutureWarning, match="The 'inplace'"):
- df.set_index("A", inplace=True, copy=False)
-
def test_set_index_multiindex(self):
# segfault in GH#3308
d = {"t1": [2, 2.5, 3], "t2": [4, 5, 6]}
@@ -199,10 +178,7 @@ def test_set_index_drop_inplace(self, frame_of_index_cols, drop, inplace, keys):
if inplace:
result = df.copy()
- with tm.assert_produces_warning(
- FutureWarning, match="The 'inplace' keyword"
- ):
- return_value = result.set_index(keys, drop=drop, inplace=True)
+ return_value = result.set_index(keys, drop=drop, inplace=True)
assert return_value is None
else:
result = df.set_index(keys, drop=drop)
diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py
index cb97e2bfb6202..bc6c676568f73 100644
--- a/pandas/tests/frame/test_api.py
+++ b/pandas/tests/frame/test_api.py
@@ -244,8 +244,7 @@ def _check_f(base, f):
# set_index
f = lambda x: x.set_index("a", inplace=True)
- with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
- _check_f(data.copy(), f)
+ _check_f(data.copy(), f)
# reset_index
f = lambda x: x.reset_index(inplace=True)
diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py
index aedc9270fd37c..35335c54cd41e 100644
--- a/pandas/tests/frame/test_query_eval.py
+++ b/pandas/tests/frame/test_query_eval.py
@@ -436,8 +436,7 @@ def test_date_index_query(self):
df = DataFrame(np.random.randn(n, 3))
df["dates1"] = date_range("1/1/2012", periods=n)
df["dates3"] = date_range("1/1/2014", periods=n)
- with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
- return_value = df.set_index("dates1", inplace=True, drop=True)
+ return_value = df.set_index("dates1", inplace=True, drop=True)
assert return_value is None
res = df.query("index < 20130101 < dates3", engine=engine, parser=parser)
expec = df[(df.index < "20130101") & ("20130101" < df.dates3)]
@@ -450,8 +449,7 @@ def test_date_index_query_with_NaT(self):
df["dates1"] = date_range("1/1/2012", periods=n)
df["dates3"] = date_range("1/1/2014", periods=n)
df.iloc[0, 0] = pd.NaT
- with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
- return_value = df.set_index("dates1", inplace=True, drop=True)
+ return_value = df.set_index("dates1", inplace=True, drop=True)
assert return_value is None
res = df.query("index < 20130101 < dates3", engine=engine, parser=parser)
expec = df[(df.index < "20130101") & ("20130101" < df.dates3)]
@@ -465,8 +463,7 @@ def test_date_index_query_with_NaT_duplicates(self):
d["dates3"] = date_range("1/1/2014", periods=n)
df = DataFrame(d)
df.loc[np.random.rand(n) > 0.5, "dates1"] = pd.NaT
- with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
- return_value = df.set_index("dates1", inplace=True, drop=True)
+ return_value = df.set_index("dates1", inplace=True, drop=True)
assert return_value is None
res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser)
expec = df[(df.index.to_series() < "20130101") & ("20130101" < df.dates3)]
@@ -797,8 +794,7 @@ def test_date_index_query(self):
df = DataFrame(np.random.randn(n, 3))
df["dates1"] = date_range("1/1/2012", periods=n)
df["dates3"] = date_range("1/1/2014", periods=n)
- with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
- return_value = df.set_index("dates1", inplace=True, drop=True)
+ return_value = df.set_index("dates1", inplace=True, drop=True)
assert return_value is None
res = df.query(
"(index < 20130101) & (20130101 < dates3)", engine=engine, parser=parser
@@ -813,8 +809,7 @@ def test_date_index_query_with_NaT(self):
df["dates1"] = date_range("1/1/2012", periods=n)
df["dates3"] = date_range("1/1/2014", periods=n)
df.iloc[0, 0] = pd.NaT
- with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
- return_value = df.set_index("dates1", inplace=True, drop=True)
+ return_value = df.set_index("dates1", inplace=True, drop=True)
assert return_value is None
res = df.query(
"(index < 20130101) & (20130101 < dates3)", engine=engine, parser=parser
@@ -829,8 +824,7 @@ def test_date_index_query_with_NaT_duplicates(self):
df["dates1"] = date_range("1/1/2012", periods=n)
df["dates3"] = date_range("1/1/2014", periods=n)
df.loc[np.random.rand(n) > 0.5, "dates1"] = pd.NaT
- with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
- return_value = df.set_index("dates1", inplace=True, drop=True)
+ return_value = df.set_index("dates1", inplace=True, drop=True)
assert return_value is None
msg = r"'BoolOp' nodes are not implemented"
with pytest.raises(NotImplementedError, match=msg):
diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py
index 5a66d13efce65..b064c12f89c21 100644
--- a/pandas/tests/groupby/test_apply.py
+++ b/pandas/tests/groupby/test_apply.py
@@ -678,7 +678,7 @@ def test_apply_groupby_datetimeindex():
result = df.groupby("Name").sum()
expected = DataFrame({"Name": ["A", "B", "C"], "Value": [10, 50, 90]})
- expected = expected.set_index("Name", copy=False)
+ expected.set_index("Name", inplace=True)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index 7ba22c09cd26d..d813a2848a5dc 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -98,7 +98,7 @@ def test_builtins_apply(keys, f):
if f != sum:
expected = gb.agg(fname).reset_index()
- expected = expected.set_index(keys, copy=False, drop=False)
+ expected.set_index(keys, inplace=True, drop=False)
tm.assert_frame_equal(result, expected, check_dtype=False)
tm.assert_series_equal(getattr(result, fname)(), getattr(df, fname)())
@@ -454,7 +454,7 @@ def test_groupby_non_arithmetic_agg_types(dtype, method, data):
df_out = DataFrame(exp)
df_out["b"] = df_out.b.astype(out_type)
- df_out = df_out.set_index("a", copy=False)
+ df_out.set_index("a", inplace=True)
grpd = df.groupby("a")
t = getattr(grpd, method)(*data["args"])
diff --git a/pandas/tests/indexes/multi/test_reshape.py b/pandas/tests/indexes/multi/test_reshape.py
index f4b845be2709c..af546a08d50ff 100644
--- a/pandas/tests/indexes/multi/test_reshape.py
+++ b/pandas/tests/indexes/multi/test_reshape.py
@@ -35,7 +35,7 @@ def test_insert(idx):
idx.insert(0, ("foo2",))
left = pd.DataFrame([["a", "b", 0], ["b", "d", 1]], columns=["1st", "2nd", "3rd"])
- left = left.set_index(["1st", "2nd"], copy=False)
+ left.set_index(["1st", "2nd"], inplace=True)
ts = left["3rd"].copy(deep=True)
left.loc[("b", "x"), "3rd"] = 2
@@ -65,7 +65,7 @@ def test_insert(idx):
],
columns=["1st", "2nd", "3rd"],
)
- right = right.set_index(["1st", "2nd"], copy=False)
+ right.set_index(["1st", "2nd"], inplace=True)
# FIXME data types changes to float because
# of intermediate nan insertion;
tm.assert_frame_equal(left, right, check_dtype=False)
diff --git a/pandas/tests/indexing/multiindex/test_indexing_slow.py b/pandas/tests/indexing/multiindex/test_indexing_slow.py
index 16b0ae2c63eb1..e8c766d489813 100644
--- a/pandas/tests/indexing/multiindex/test_indexing_slow.py
+++ b/pandas/tests/indexing/multiindex/test_indexing_slow.py
@@ -60,18 +60,15 @@ def validate(mi, df, key):
assert key[: i + 1] in mi.index
right = df[mask].copy()
- msg = "The 'inplace' keyword in DataFrame.set_index is deprecated"
if i + 1 != len(key): # partial key
return_value = right.drop(cols[: i + 1], axis=1, inplace=True)
assert return_value is None
- with tm.assert_produces_warning(FutureWarning, match=msg):
- return_value = right.set_index(cols[i + 1 : -1], inplace=True)
+ return_value = right.set_index(cols[i + 1 : -1], inplace=True)
assert return_value is None
tm.assert_frame_equal(mi.loc[key[: i + 1]], right)
else: # full key
- with tm.assert_produces_warning(FutureWarning, match=msg):
- return_value = right.set_index(cols[:-1], inplace=True)
+ return_value = right.set_index(cols[:-1], inplace=True)
assert return_value is None
if len(right) == 1: # single hit
right = Series(
diff --git a/pandas/tests/indexing/multiindex/test_multiindex.py b/pandas/tests/indexing/multiindex/test_multiindex.py
index 100b3e55b03c5..08e15545cb998 100644
--- a/pandas/tests/indexing/multiindex/test_multiindex.py
+++ b/pandas/tests/indexing/multiindex/test_multiindex.py
@@ -131,7 +131,7 @@ def test_multiindex_complex(self):
"z": non_complex_data,
}
)
- result = result.set_index(["x", "y"], copy=False)
+ result.set_index(["x", "y"], inplace=True)
expected = DataFrame(
{"z": non_complex_data},
index=MultiIndex.from_arrays(
diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py
index 6c6ea4c8b0e0a..40a50c55de2a4 100644
--- a/pandas/tests/io/pytables/test_append.py
+++ b/pandas/tests/io/pytables/test_append.py
@@ -137,7 +137,7 @@ def test_append_series(setup_path):
mi["B"] = np.arange(len(mi))
mi["C"] = "foo"
mi.loc[3:5, "C"] = "bar"
- mi = mi.set_index(["C", "B"], copy=False)
+ mi.set_index(["C", "B"], inplace=True)
s = mi.stack()
s.index = s.index.droplevel(2)
store.append("mi", s)
@@ -326,7 +326,7 @@ def test_append_with_different_block_ordering(setup_path):
a = df.pop("A")
df["A"] = a
- df = df.set_index("index", copy=False)
+ df.set_index("index", inplace=True)
store.append("df", df)
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index c2c47672b190d..ee55837324f20 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -771,7 +771,7 @@ def _roundtrip(self, test_frame1):
assert self.pandasSQL.to_sql(test_frame1, "test_frame_roundtrip") == 4
result = self.pandasSQL.read_query("SELECT * FROM test_frame_roundtrip")
- result = result.set_index("level_0", copy=False)
+ result.set_index("level_0", inplace=True)
# result.index.astype(int)
result.index.name = None
@@ -928,7 +928,7 @@ def test_roundtrip(self, test_frame1):
# HACK!
result.index = test_frame1.index
- result = result.set_index("level_0", copy=False)
+ result.set_index("level_0", inplace=True)
result.index.astype(int)
result.index.name = None
tm.assert_frame_equal(result, test_frame1)
diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py
index b64af2dd98bcb..94226ae1a2575 100644
--- a/pandas/tests/plotting/frame/test_frame.py
+++ b/pandas/tests/plotting/frame/test_frame.py
@@ -1551,8 +1551,8 @@ def test_errorbar_with_partial_columns(self):
self._check_has_errorbars(ax, xerr=0, yerr=2)
ix = date_range("1/1/2000", periods=10, freq="M")
- df = df.set_index(ix, copy=False)
- df_err = df_err.set_index(ix, copy=False)
+ df.set_index(ix, inplace=True)
+ df_err.set_index(ix, inplace=True)
ax = _check_plot_works(df.plot, yerr=df_err, kind="line")
self._check_has_errorbars(ax, xerr=0, yerr=2)
diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py
index f3d24fa53f7ed..6e87c221426c1 100644
--- a/pandas/tests/reshape/merge/test_join.py
+++ b/pandas/tests/reshape/merge/test_join.py
@@ -409,7 +409,7 @@ def test_join_hierarchical_mixed(self):
df = DataFrame([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "c"])
new_df = df.groupby(["a"]).agg({"b": [np.mean, np.sum]})
other_df = DataFrame([(1, 2, 3), (7, 10, 6)], columns=["a", "b", "d"])
- other_df = other_df.set_index("a", copy=False)
+ other_df.set_index("a", inplace=True)
# GH 9455, 12219
msg = "merging between different levels is deprecated"
with tm.assert_produces_warning(FutureWarning, match=msg):
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index c7d7d1b0daa50..f172528041fb3 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -1347,7 +1347,7 @@ def test_merge_on_index_with_more_values(self, how, index, expected_index):
],
columns=["a", "key", "b"],
)
- expected = expected.set_index(expected_index, copy=False)
+ expected.set_index(expected_index, inplace=True)
tm.assert_frame_equal(result, expected)
def test_merge_right_index_right(self):
diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py
index cc8019c50bc1e..0dbe45eeb1e82 100644
--- a/pandas/tests/reshape/merge/test_multi.py
+++ b/pandas/tests/reshape/merge/test_multi.py
@@ -130,7 +130,7 @@ def run_asserts(left, right, sort):
left["4th"] = bind_cols(left)
right["5th"] = -bind_cols(right)
- right = right.set_index(icols, copy=False)
+ right.set_index(icols, inplace=True)
run_asserts(left, right, sort)
@@ -143,7 +143,7 @@ def run_asserts(left, right, sort):
i = np.random.permutation(len(left))
right = left.iloc[i, :-1]
right["5th"] = -bind_cols(right)
- right = right.set_index(icols, copy=False)
+ right.set_index(icols, inplace=True)
run_asserts(left, right, sort)
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index 6ddffd0d006dc..5e87e36f21cca 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -252,9 +252,7 @@ def test_timedelta_assignment():
def test_underlying_data_conversion(using_copy_on_write):
# GH 4080
df = DataFrame({c: [1, 2, 3] for c in ["a", "b", "c"]})
- msg = "The 'inplace' keyword"
- with tm.assert_produces_warning(FutureWarning, match=msg):
- return_value = df.set_index(["a", "b", "c"], inplace=True)
+ return_value = df.set_index(["a", "b", "c"], inplace=True)
assert return_value is None
s = Series([1], index=[(2, 2, 2)])
df["val"] = 0
@@ -268,8 +266,7 @@ def test_underlying_data_conversion(using_copy_on_write):
expected = DataFrame(
{"a": [1, 2, 3], "b": [1, 2, 3], "c": [1, 2, 3], "val": [0, 1, 0]}
)
- with tm.assert_produces_warning(FutureWarning, match=msg):
- return_value = expected.set_index(["a", "b", "c"], inplace=True)
+ return_value = expected.set_index(["a", "b", "c"], inplace=True)
assert return_value is None
tm.assert_frame_equal(df, expected)
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index 943ffc10f52c8..c9ec2985488be 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -706,7 +706,7 @@ def test_rolling_window_as_string(center, expected_data):
data = npr.randint(1, high=100, size=len(days))
df = DataFrame({"DateCol": days, "metric": data})
- df = df.set_index("DateCol", copy=False)
+ df.set_index("DateCol", inplace=True)
result = df.rolling(window="21D", min_periods=2, closed="left", center=center)[
"metric"
].agg("max")
| See the discussion in https://github.com/pandas-dev/pandas/issues/48141
Reverts https://github.com/pandas-dev/pandas/pull/48043 and https://github.com/pandas-dev/pandas/pull/48115 for now. | https://api.github.com/repos/pandas-dev/pandas/pulls/48417 | 2022-09-06T18:23:45Z | 2022-09-14T19:02:30Z | 2022-09-14T19:02:30Z | 2022-09-15T00:06:32Z |
REF: ensure to apply suffixes before concat step in merge code | diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 5052c27ea47f3..472984c65a897 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -764,8 +764,9 @@ def _reindex_and_concat(
from pandas import concat
+ left.columns = llabels
+ right.columns = rlabels
result = concat([left, right], axis=1, copy=copy)
- result.columns = llabels.append(rlabels)
return result
def get_result(self, copy: bool = True) -> DataFrame:
| Follow-up on https://github.com/pandas-dev/pandas/pull/48082
I _could_ add a test by writing a small DataFrame subclass that checks for duplicate columns in its constructor, or we could rely on geopandas CI catching this (we do test against pandas main). Either way is fine for me. | https://api.github.com/repos/pandas-dev/pandas/pulls/48416 | 2022-09-06T18:05:48Z | 2022-09-08T18:44:12Z | 2022-09-08T18:44:12Z | 2022-09-08T18:44:16Z |
DOC: Add deprecation to is_categorical | diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 1173703386491..f5262aa7ceeaa 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -280,6 +280,9 @@ def is_categorical(arr) -> bool:
"""
Check whether an array-like is a Categorical instance.
+ .. deprecated:: 1.1.0
+ Use ``is_categorical_dtype`` instead.
+
Parameters
----------
arr : array-like
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/48414 | 2022-09-06T15:39:44Z | 2022-09-06T19:16:17Z | 2022-09-06T19:16:17Z | 2022-09-06T19:16:23Z |
Backport PR #48229 on branch 1.5.x (TST: Test Nullable int floordiv by 0) | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 8671b73526f80..c479c59082464 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -1011,6 +1011,8 @@ Time Zones
Numeric
^^^^^^^
- Bug in operations with array-likes with ``dtype="boolean"`` and :attr:`NA` incorrectly altering the array in-place (:issue:`45421`)
+- Bug in arithmetic operations with nullable types without :attr:`NA` values not matching the same operation with non-nullable types (:issue:`48223`)
+- Bug in ``floordiv`` when dividing by ``IntegerDtype`` ``0`` would return ``0`` instead of ``inf`` (:issue:`48223`)
- Bug in division, ``pow`` and ``mod`` operations on array-likes with ``dtype="boolean"`` not being like their ``np.bool_`` counterparts (:issue:`46063`)
- Bug in multiplying a :class:`Series` with ``IntegerDtype`` or ``FloatingDtype`` by an array-like with ``timedelta64[ns]`` dtype incorrectly raising (:issue:`45622`)
- Bug in :meth:`mean` where the optional dependency ``bottleneck`` causes precision loss linear in the length of the array. ``bottleneck`` has been disabled for :meth:`mean` improving the loss to log-linear but may result in a performance decrease. (:issue:`42878`)
diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py
index e6a085ceb4d29..5b9780e390775 100644
--- a/pandas/tests/arrays/integer/test_arithmetic.py
+++ b/pandas/tests/arrays/integer/test_arithmetic.py
@@ -75,6 +75,21 @@ def test_floordiv(dtype):
tm.assert_extension_array_equal(result, expected)
+def test_floordiv_by_int_zero_no_mask(any_int_ea_dtype):
+ # GH 48223: Aligns with non-masked floordiv
+ # but differs from numpy
+ # https://github.com/pandas-dev/pandas/issues/30188#issuecomment-564452740
+ ser = pd.Series([0, 1], dtype=any_int_ea_dtype)
+ result = 1 // ser
+ expected = pd.Series([np.inf, 1.0], dtype="Float64")
+ tm.assert_series_equal(result, expected)
+
+ ser_non_nullable = ser.astype(ser.dtype.numpy_dtype)
+ result = 1 // ser_non_nullable
+ expected = expected.astype(np.float64)
+ tm.assert_series_equal(result, expected)
+
+
def test_mod(dtype):
a = pd.array([1, 2, 3, None, 5], dtype=dtype)
b = pd.array([0, 1, None, 3, 4], dtype=dtype)
| Backport PR #48229: TST: Test Nullable int floordiv by 0 | https://api.github.com/repos/pandas-dev/pandas/pulls/48413 | 2022-09-06T14:13:44Z | 2022-09-06T20:40:21Z | 2022-09-06T20:40:21Z | 2022-09-06T20:40:21Z |
DEPR: Adjust read excel behavior for xlrd >= 2.0 | diff --git a/ci/deps/azure-38-slow.yaml b/ci/deps/azure-38-slow.yaml
index 2b4339cf12658..9651837f26114 100644
--- a/ci/deps/azure-38-slow.yaml
+++ b/ci/deps/azure-38-slow.yaml
@@ -30,7 +30,7 @@ dependencies:
- moto>=1.3.14
- scipy
- sqlalchemy
- - xlrd<2.0
+ - xlrd>=2.0
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index ad72b9c8577e9..e7ac4c783b855 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -33,7 +33,7 @@ dependencies:
- s3fs>=0.4.2
- scipy
- sqlalchemy
- - xlrd<2.0
+ - xlrd>=2.0
- xlsxwriter
- xlwt
- pyreadstat
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 151b41705f9a5..6dc0d0cfaf80b 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -27,7 +27,7 @@ including other versions of pandas.
**Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.**
This is no longer supported, switch to using ``openpyxl`` instead.
- Attempting to use the the ``xlwt`` engine will raise a ``FutureWarning``
+ Attempting to use the ``xlwt`` engine will raise a ``FutureWarning``
unless the option :attr:`io.excel.xls.writer` is set to ``"xlwt"``.
While this option is now deprecated and will also raise a ``FutureWarning``,
it can be globally set and the warning suppressed. Users are recommended to
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index c72f294bf6ac8..221e8b9ccfb14 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -1,11 +1,13 @@
import abc
import datetime
+from distutils.version import LooseVersion
import inspect
from io import BufferedIOBase, BytesIO, RawIOBase
import os
from textwrap import fill
-from typing import Any, Dict, Mapping, Union, cast
+from typing import IO, Any, Dict, Mapping, Optional, Union, cast
import warnings
+import zipfile
from pandas._config import config
@@ -13,11 +15,12 @@
from pandas._typing import Buffer, FilePathOrBuffer, StorageOptions
from pandas.compat._optional import import_optional_dependency
from pandas.errors import EmptyDataError
-from pandas.util._decorators import Appender, deprecate_nonkeyword_arguments
+from pandas.util._decorators import Appender, deprecate_nonkeyword_arguments, doc
from pandas.core.dtypes.common import is_bool, is_float, is_integer, is_list_like
from pandas.core.frame import DataFrame
+from pandas.core.shared_docs import _shared_docs
from pandas.io.common import IOHandles, get_handle, stringify_path, validate_header_arg
from pandas.io.excel._util import (
@@ -116,17 +119,15 @@
When ``engine=None``, the following logic will be
used to determine the engine:
- - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
- then `odf <https://pypi.org/project/odfpy/>`_ will be used.
- - Otherwise if ``path_or_buffer`` is a bytes stream, the file has the
- extension ``.xls``, or is an ``xlrd`` Book instance, then ``xlrd`` will
- be used.
- - Otherwise if `openpyxl <https://pypi.org/project/openpyxl/>`_ is installed,
- then ``openpyxl`` will be used.
- - Otherwise ``xlrd`` will be used and a ``FutureWarning`` will be raised.
-
- Specifying ``engine="xlrd"`` will continue to be allowed for the
- indefinite future.
+ - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
+ then `odf <https://pypi.org/project/odfpy/>`_ will be used.
+ - Otherwise if ``path_or_buffer`` is an xls format,
+ ``xlrd`` will be used.
+ - Otherwise if `openpyxl <https://pypi.org/project/openpyxl/>`_ is installed,
+ then ``openpyxl`` will be used.
+ - Otherwise if ``xlrd >= 2.0`` is installed, a ``ValueError`` will be raised.
+ - Otherwise ``xlrd`` will be used and a ``FutureWarning`` will be raised. This
+ case will raise a ``ValueError`` in a future version of pandas.
converters : dict, default None
Dict of functions for converting values in certain columns. Keys can
@@ -888,39 +889,92 @@ def close(self):
return content
-def _is_ods_stream(stream: Union[BufferedIOBase, RawIOBase]) -> bool:
+XLS_SIGNATURE = b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
+ZIP_SIGNATURE = b"PK\x03\x04"
+PEEK_SIZE = max(len(XLS_SIGNATURE), len(ZIP_SIGNATURE))
+
+
+@doc(storage_options=_shared_docs["storage_options"])
+def inspect_excel_format(
+ path: Optional[str] = None,
+ content: Union[None, BufferedIOBase, RawIOBase, bytes] = None,
+ storage_options: StorageOptions = None,
+) -> str:
"""
- Check if the stream is an OpenDocument Spreadsheet (.ods) file
+ Inspect the path or content of an excel file and get its format.
+
+ At least one of path or content must be not None. If both are not None,
+ content will take precedence.
- It uses magic values inside the stream
+ Adopted from xlrd: https://github.com/python-excel/xlrd.
Parameters
----------
- stream : Union[BufferedIOBase, RawIOBase]
- IO stream with data which might be an ODS file
+ path : str, optional
+ Path to file to inspect. May be a URL.
+ content : file-like object, optional
+ Content of file to inspect.
+ {storage_options}
Returns
-------
- is_ods : bool
- Boolean indication that this is indeed an ODS file or not
+ str
+ Format of file.
+
+ Raises
+ ------
+ ValueError
+ If resulting stream is empty.
+ BadZipFile
+ If resulting stream does not have an XLS signature and is not a valid zipfile.
"""
- stream.seek(0)
- is_ods = False
- if stream.read(4) == b"PK\003\004":
- stream.seek(30)
- is_ods = (
- stream.read(54) == b"mimetype"
- b"application/vnd.oasis.opendocument.spreadsheet"
- )
- stream.seek(0)
- return is_ods
+ content_or_path: Union[None, str, BufferedIOBase, RawIOBase, IO[bytes]]
+ if isinstance(content, bytes):
+ content_or_path = BytesIO(content)
+ else:
+ content_or_path = content or path
+ assert content_or_path is not None
+
+ with get_handle(
+ content_or_path, "rb", storage_options=storage_options, is_text=False
+ ) as handle:
+ stream = handle.handle
+ stream.seek(0)
+ buf = stream.read(PEEK_SIZE)
+ if buf is None:
+ raise ValueError("stream is empty")
+ else:
+ assert isinstance(buf, bytes)
+ peek = buf
+ stream.seek(0)
+
+ if peek.startswith(XLS_SIGNATURE):
+ return "xls"
+ elif not peek.startswith(ZIP_SIGNATURE):
+ raise ValueError("File is not a recognized excel file")
+
+ # ZipFile typing is overly-strict
+ # https://github.com/python/typeshed/issues/4212
+ zf = zipfile.ZipFile(stream) # type: ignore[arg-type]
+
+ # Workaround for some third party files that use forward slashes and
+ # lower case names.
+ component_names = [name.replace("\\", "/").lower() for name in zf.namelist()]
+
+ if "xl/workbook.xml" in component_names:
+ return "xlsx"
+ if "xl/workbook.bin" in component_names:
+ return "xlsb"
+ if "content.xml" in component_names:
+ return "ods"
+ return "zip"
class ExcelFile:
"""
Class for parsing tabular excel sheets into DataFrame objects.
- See read_excel for more documentation
+ See read_excel for more documentation.
Parameters
----------
@@ -947,12 +1001,13 @@ class ExcelFile:
- If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
then `odf <https://pypi.org/project/odfpy/>`_ will be used.
- - Otherwise if ``path_or_buffer`` is a bytes stream, the file has the
- extension ``.xls``, or is an ``xlrd`` Book instance, then ``xlrd``
- will be used.
+ - Otherwise if ``path_or_buffer`` is an xls format,
+ ``xlrd`` will be used.
- Otherwise if `openpyxl <https://pypi.org/project/openpyxl/>`_ is installed,
then ``openpyxl`` will be used.
+ - Otherwise if ``xlrd >= 2.0`` is installed, a ``ValueError`` will be raised.
- Otherwise ``xlrd`` will be used and a ``FutureWarning`` will be raised.
+ This case will raise a ``ValueError`` in a future version of pandas.
.. warning::
@@ -975,33 +1030,47 @@ class ExcelFile:
def __init__(
self, path_or_buffer, engine=None, storage_options: StorageOptions = None
):
- if engine is None:
- # Determine ext and use odf for ods stream/file
- if isinstance(path_or_buffer, (BufferedIOBase, RawIOBase)):
- ext = None
- if _is_ods_stream(path_or_buffer):
- engine = "odf"
- else:
- ext = os.path.splitext(str(path_or_buffer))[-1]
- if ext == ".ods":
- engine = "odf"
+ if engine is not None and engine not in self._engines:
+ raise ValueError(f"Unknown engine: {engine}")
- if (
- import_optional_dependency(
- "xlrd", raise_on_missing=False, on_version="ignore"
- )
- is not None
- ):
- from xlrd import Book
+ # Could be a str, ExcelFile, Book, etc.
+ self.io = path_or_buffer
+ # Always a string
+ self._io = stringify_path(path_or_buffer)
- if isinstance(path_or_buffer, Book):
- engine = "xlrd"
+ # Determine xlrd version if installed
+ if (
+ import_optional_dependency(
+ "xlrd", raise_on_missing=False, on_version="ignore"
+ )
+ is None
+ ):
+ xlrd_version = None
+ else:
+ import xlrd
- # GH 35029 - Prefer openpyxl except for xls files
- if engine is None:
- if ext is None or isinstance(path_or_buffer, bytes) or ext == ".xls":
- engine = "xlrd"
- elif (
+ xlrd_version = LooseVersion(xlrd.__version__)
+
+ if isinstance(path_or_buffer, (BufferedIOBase, RawIOBase, bytes)):
+ ext = inspect_excel_format(
+ content=path_or_buffer, storage_options=storage_options
+ )
+ elif xlrd_version is not None and isinstance(path_or_buffer, xlrd.Book):
+ ext = "xls"
+ else:
+ # path_or_buffer is path-like, use stringified path
+ ext = inspect_excel_format(
+ path=str(self._io), storage_options=storage_options
+ )
+
+ if engine is None:
+ if ext == "ods":
+ engine = "odf"
+ elif ext == "xls":
+ engine = "xlrd"
+ else:
+ # GH 35029 - Prefer openpyxl except for xls files
+ if (
import_optional_dependency(
"openpyxl", raise_on_missing=False, on_version="ignore"
)
@@ -1009,37 +1078,39 @@ def __init__(
):
engine = "openpyxl"
else:
- caller = inspect.stack()[1]
- if (
- caller.filename.endswith("pandas/io/excel/_base.py")
- and caller.function == "read_excel"
- ):
- stacklevel = 4
- else:
- stacklevel = 2
- warnings.warn(
- "The xlrd engine is no longer maintained and is not "
- "supported when using pandas with python >= 3.9. However, "
- "the engine xlrd will continue to be allowed for the "
- "indefinite future. Beginning with pandas 1.2.0, the "
- "openpyxl engine will be used if it is installed and the "
- "engine argument is not specified. Either install openpyxl "
- "or specify engine='xlrd' to silence this warning.",
- FutureWarning,
- stacklevel=stacklevel,
- )
engine = "xlrd"
- if engine not in self._engines:
- raise ValueError(f"Unknown engine: {engine}")
+
+ if engine == "xlrd" and ext != "xls" and xlrd_version is not None:
+ if xlrd_version >= "2":
+ raise ValueError(
+ f"Your version of xlrd is {xlrd_version}. In xlrd >= 2.0, "
+ f"only the xls format is supported. Install openpyxl instead."
+ )
+ else:
+ caller = inspect.stack()[1]
+ if (
+ caller.filename.endswith(
+ os.path.join("pandas", "io", "excel", "_base.py")
+ )
+ and caller.function == "read_excel"
+ ):
+ stacklevel = 4
+ else:
+ stacklevel = 2
+ warnings.warn(
+ f"Your version of xlrd is {xlrd_version}. In xlrd >= 2.0, "
+ f"only the xls format is supported. As a result, the "
+ f"openpyxl engine will be used if it is installed and the "
+ f"engine argument is not specified. Install "
+ f"openpyxl instead.",
+ FutureWarning,
+ stacklevel=stacklevel,
+ )
+ assert engine in self._engines, f"Engine {engine} not recognized"
self.engine = engine
self.storage_options = storage_options
- # Could be a str, ExcelFile, Book, etc.
- self.io = path_or_buffer
- # Always a string
- self._io = stringify_path(path_or_buffer)
-
self._reader = self._engines[engine](self._io, storage_options=storage_options)
def __fspath__(self):
diff --git a/pandas/tests/io/__init__.py b/pandas/tests/io/__init__.py
index c5e867f45b92d..39474dedba78c 100644
--- a/pandas/tests/io/__init__.py
+++ b/pandas/tests/io/__init__.py
@@ -14,4 +14,8 @@
r"Use 'tree.iter\(\)' or 'list\(tree.iter\(\)\)' instead."
":PendingDeprecationWarning"
),
+ # GH 26552
+ pytest.mark.filterwarnings(
+ "ignore:As the xlwt package is no longer maintained:FutureWarning"
+ ),
]
diff --git a/pandas/tests/io/excel/__init__.py b/pandas/tests/io/excel/__init__.py
index 384f1006c44df..b7ceb28573484 100644
--- a/pandas/tests/io/excel/__init__.py
+++ b/pandas/tests/io/excel/__init__.py
@@ -1,5 +1,9 @@
+from distutils.version import LooseVersion
+
import pytest
+from pandas.compat._optional import import_optional_dependency
+
pytestmark = [
pytest.mark.filterwarnings(
# Looks like tree.getiterator is deprecated in favor of tree.iter
@@ -13,4 +17,19 @@
pytest.mark.filterwarnings(
"ignore:As the xlwt package is no longer maintained:FutureWarning"
),
+ # GH 38571
+ pytest.mark.filterwarnings(
+ "ignore:.*In xlrd >= 2.0, only the xls format is supported:FutureWarning"
+ ),
]
+
+
+if (
+ import_optional_dependency("xlrd", raise_on_missing=False, on_version="ignore")
+ is None
+):
+ xlrd_version = None
+else:
+ import xlrd
+
+ xlrd_version = LooseVersion(xlrd.__version__)
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 98a55ae39bd77..df1250cee8b00 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -11,6 +11,7 @@
import pandas as pd
from pandas import DataFrame, Index, MultiIndex, Series
import pandas._testing as tm
+from pandas.tests.io.excel import xlrd_version
read_ext_params = [".xls", ".xlsx", ".xlsm", ".xlsb", ".ods"]
engine_params = [
@@ -57,6 +58,13 @@ def _is_valid_engine_ext_pair(engine, read_ext: str) -> bool:
return False
if read_ext == ".xlsb" and engine != "pyxlsb":
return False
+ if (
+ engine == "xlrd"
+ and xlrd_version is not None
+ and xlrd_version >= "2"
+ and read_ext != ".xls"
+ ):
+ return False
return True
@@ -614,6 +622,19 @@ def test_bad_engine_raises(self, read_ext):
with pytest.raises(ValueError, match="Unknown engine: foo"):
pd.read_excel("", engine=bad_engine)
+ def test_missing_file_raises(self, read_ext):
+ bad_file = f"foo{read_ext}"
+ # CI tests with zh_CN.utf8, translates to "No such file or directory"
+ with pytest.raises(
+ FileNotFoundError, match=r"(No such file or directory|没有那个文件或目录)"
+ ):
+ pd.read_excel(bad_file)
+
+ def test_corrupt_bytes_raises(self, read_ext, engine):
+ bad_stream = b"foo"
+ with pytest.raises(ValueError, match="File is not a recognized excel file"):
+ pd.read_excel(bad_stream)
+
@tm.network
def test_read_from_http_url(self, read_ext):
url = (
@@ -1158,6 +1179,19 @@ def test_excel_read_binary(self, engine, read_ext):
actual = pd.read_excel(data, engine=engine)
tm.assert_frame_equal(expected, actual)
+ def test_excel_read_binary_via_read_excel(self, read_ext, engine):
+ # GH 38424
+ if read_ext == ".xlsb" and engine == "pyxlsb":
+ pytest.xfail("GH 38667 - should default to pyxlsb but doesn't")
+ with open("test1" + read_ext, "rb") as f:
+ result = pd.read_excel(f)
+ expected = pd.read_excel("test1" + read_ext, engine=engine)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.skipif(
+ xlrd_version is not None and xlrd_version >= "2",
+ reason="xlrd no longer supports xlsx",
+ )
def test_excel_high_surrogate(self, engine):
# GH 23809
expected = DataFrame(["\udc88"], columns=["Column1"])
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index 80ebeb4c03d89..197738330efe1 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -1195,9 +1195,9 @@ def test_datetimes(self, path):
write_frame = DataFrame({"A": datetimes})
write_frame.to_excel(path, "Sheet1")
- # GH 35029 - Default changed to openpyxl, but test is for odf/xlrd
- engine = "odf" if path.endswith("ods") else "xlrd"
- read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0, engine=engine)
+ if path.endswith("xlsx") or path.endswith("xlsm"):
+ pytest.skip("Defaults to openpyxl and fails - GH #38644")
+ read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0)
tm.assert_series_equal(write_frame["A"], read_frame["A"])
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
index f2fbcbc2e2f04..2a1114a9570f0 100644
--- a/pandas/tests/io/excel/test_xlrd.py
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -4,6 +4,7 @@
import pandas as pd
import pandas._testing as tm
+from pandas.tests.io.excel import xlrd_version
from pandas.io.excel import ExcelFile
@@ -17,6 +18,8 @@ def skip_ods_and_xlsb_files(read_ext):
pytest.skip("Not valid for xlrd")
if read_ext == ".xlsb":
pytest.skip("Not valid for xlrd")
+ if read_ext in (".xlsx", ".xlsm") and xlrd_version >= "2":
+ pytest.skip("Not valid for xlrd >= 2.0")
def test_read_xlrd_book(read_ext, frame):
@@ -66,7 +69,7 @@ def test_excel_file_warning_with_xlsx_file(datapath):
pd.read_excel(path, "Sheet1", engine=None)
-def test_read_excel_warning_with_xlsx_file(tmpdir, datapath):
+def test_read_excel_warning_with_xlsx_file(datapath):
# GH 29375
path = datapath("io", "data", "excel", "test1.xlsx")
has_openpyxl = (
@@ -76,12 +79,19 @@ def test_read_excel_warning_with_xlsx_file(tmpdir, datapath):
is not None
)
if not has_openpyxl:
- with tm.assert_produces_warning(
- FutureWarning,
- raise_on_extra_warnings=False,
- match="The xlrd engine is no longer maintained",
- ):
- pd.read_excel(path, "Sheet1", engine=None)
+ if xlrd_version >= "2":
+ with pytest.raises(
+ ValueError,
+ match="Your version of xlrd is ",
+ ):
+ pd.read_excel(path, "Sheet1", engine=None)
+ else:
+ with tm.assert_produces_warning(
+ FutureWarning,
+ raise_on_extra_warnings=False,
+ match="The xlrd engine is no longer maintained",
+ ):
+ pd.read_excel(path, "Sheet1", engine=None)
else:
with tm.assert_produces_warning(None):
pd.read_excel(path, "Sheet1", engine=None)
| - [x] closes #38424
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Alternative to #38522. I've been testing this locally using both xlrd 1.2.0 and 2.0.1.
One test fails because we used to default to xlrd but now default to openpyxl, it's not clear to me if this test should be passing with openpyxl.
cc @cjw296, @jreback, @jorisvandenbossche
| https://api.github.com/repos/pandas-dev/pandas/pulls/38571 | 2020-12-18T23:42:20Z | 2020-12-23T23:01:22Z | 2020-12-23T23:01:22Z | 2020-12-24T09:04:59Z |
TST/REF: misplaced Series.reindex test | diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py
index ca098296daf8d..b66a95bae51c5 100644
--- a/pandas/tests/frame/methods/test_set_index.py
+++ b/pandas/tests/frame/methods/test_set_index.py
@@ -684,3 +684,14 @@ def __str__(self) -> str:
with pytest.raises(TypeError, match=msg):
# custom label wrapped in list
df.set_index([thing2])
+
+ def test_set_index_periodindex(self):
+ # GH#6631
+ df = DataFrame(np.random.random(6))
+ idx1 = period_range("2011/01/01", periods=6, freq="M")
+ idx2 = period_range("2013", periods=6, freq="A")
+
+ df = df.set_index(idx1)
+ tm.assert_index_equal(df.index, idx1)
+ df = df.set_index(idx2)
+ tm.assert_index_equal(df.index, idx2)
diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py
index 789510b452969..1c813d47e21a9 100644
--- a/pandas/tests/indexes/datetimes/test_datetime.py
+++ b/pandas/tests/indexes/datetimes/test_datetime.py
@@ -1,4 +1,4 @@
-from datetime import date, timedelta
+from datetime import date
import dateutil
import numpy as np
@@ -12,51 +12,6 @@
class TestDatetimeIndex:
- def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self):
- # GH7774
- index = date_range("20130101", periods=3, tz="US/Eastern")
- assert str(index.reindex([])[0].tz) == "US/Eastern"
- assert str(index.reindex(np.array([]))[0].tz) == "US/Eastern"
-
- def test_reindex_with_same_tz(self):
- # GH 32740
- rng_a = date_range("2010-01-01", "2010-01-02", periods=24, tz="utc")
- rng_b = date_range("2010-01-01", "2010-01-02", periods=23, tz="utc")
- result1, result2 = rng_a.reindex(
- rng_b, method="nearest", tolerance=timedelta(seconds=20)
- )
- expected_list1 = [
- "2010-01-01 00:00:00",
- "2010-01-01 01:05:27.272727272",
- "2010-01-01 02:10:54.545454545",
- "2010-01-01 03:16:21.818181818",
- "2010-01-01 04:21:49.090909090",
- "2010-01-01 05:27:16.363636363",
- "2010-01-01 06:32:43.636363636",
- "2010-01-01 07:38:10.909090909",
- "2010-01-01 08:43:38.181818181",
- "2010-01-01 09:49:05.454545454",
- "2010-01-01 10:54:32.727272727",
- "2010-01-01 12:00:00",
- "2010-01-01 13:05:27.272727272",
- "2010-01-01 14:10:54.545454545",
- "2010-01-01 15:16:21.818181818",
- "2010-01-01 16:21:49.090909090",
- "2010-01-01 17:27:16.363636363",
- "2010-01-01 18:32:43.636363636",
- "2010-01-01 19:38:10.909090909",
- "2010-01-01 20:43:38.181818181",
- "2010-01-01 21:49:05.454545454",
- "2010-01-01 22:54:32.727272727",
- "2010-01-02 00:00:00",
- ]
- expected1 = DatetimeIndex(
- expected_list1, dtype="datetime64[ns, UTC]", freq=None
- )
- expected2 = np.array([0] + [-1] * 21 + [23], dtype=np.dtype("intp"))
- tm.assert_index_equal(result1, expected1)
- tm.assert_numpy_array_equal(result2, expected2)
-
def test_time_loc(self): # GH8667
from datetime import time
diff --git a/pandas/tests/indexes/datetimes/test_reindex.py b/pandas/tests/indexes/datetimes/test_reindex.py
new file mode 100644
index 0000000000000..fa847ad072ada
--- /dev/null
+++ b/pandas/tests/indexes/datetimes/test_reindex.py
@@ -0,0 +1,53 @@
+from datetime import timedelta
+
+import numpy as np
+
+from pandas import DatetimeIndex, date_range
+import pandas._testing as tm
+
+
+class TestDatetimeIndexReindex:
+ def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self):
+ # GH#7774
+ index = date_range("2013-01-01", periods=3, tz="US/Eastern")
+ assert str(index.reindex([])[0].tz) == "US/Eastern"
+ assert str(index.reindex(np.array([]))[0].tz) == "US/Eastern"
+
+ def test_reindex_with_same_tz_nearest(self):
+ # GH#32740
+ rng_a = date_range("2010-01-01", "2010-01-02", periods=24, tz="utc")
+ rng_b = date_range("2010-01-01", "2010-01-02", periods=23, tz="utc")
+ result1, result2 = rng_a.reindex(
+ rng_b, method="nearest", tolerance=timedelta(seconds=20)
+ )
+ expected_list1 = [
+ "2010-01-01 00:00:00",
+ "2010-01-01 01:05:27.272727272",
+ "2010-01-01 02:10:54.545454545",
+ "2010-01-01 03:16:21.818181818",
+ "2010-01-01 04:21:49.090909090",
+ "2010-01-01 05:27:16.363636363",
+ "2010-01-01 06:32:43.636363636",
+ "2010-01-01 07:38:10.909090909",
+ "2010-01-01 08:43:38.181818181",
+ "2010-01-01 09:49:05.454545454",
+ "2010-01-01 10:54:32.727272727",
+ "2010-01-01 12:00:00",
+ "2010-01-01 13:05:27.272727272",
+ "2010-01-01 14:10:54.545454545",
+ "2010-01-01 15:16:21.818181818",
+ "2010-01-01 16:21:49.090909090",
+ "2010-01-01 17:27:16.363636363",
+ "2010-01-01 18:32:43.636363636",
+ "2010-01-01 19:38:10.909090909",
+ "2010-01-01 20:43:38.181818181",
+ "2010-01-01 21:49:05.454545454",
+ "2010-01-01 22:54:32.727272727",
+ "2010-01-02 00:00:00",
+ ]
+ expected1 = DatetimeIndex(
+ expected_list1, dtype="datetime64[ns, UTC]", freq=None
+ )
+ expected2 = np.array([0] + [-1] * 21 + [23], dtype=np.dtype("intp"))
+ tm.assert_index_equal(result1, expected1)
+ tm.assert_numpy_array_equal(result2, expected2)
diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py
index f4773e885829e..273d02ca27d7b 100644
--- a/pandas/tests/indexes/period/test_period.py
+++ b/pandas/tests/indexes/period/test_period.py
@@ -274,46 +274,6 @@ def _check_all_fields(self, periodindex):
for x, val in zip(periods, field_s):
assert getattr(x, field) == val
- def test_period_set_index_reindex(self):
- # GH 6631
- df = DataFrame(np.random.random(6))
- idx1 = period_range("2011/01/01", periods=6, freq="M")
- idx2 = period_range("2013", periods=6, freq="A")
-
- df = df.set_index(idx1)
- tm.assert_index_equal(df.index, idx1)
- df = df.set_index(idx2)
- tm.assert_index_equal(df.index, idx2)
-
- @pytest.mark.parametrize(
- "p_values, o_values, values, expected_values",
- [
- (
- [Period("2019Q1", "Q-DEC"), Period("2019Q2", "Q-DEC")],
- [Period("2019Q1", "Q-DEC"), Period("2019Q2", "Q-DEC"), "All"],
- [1.0, 1.0],
- [1.0, 1.0, np.nan],
- ),
- (
- [Period("2019Q1", "Q-DEC"), Period("2019Q2", "Q-DEC")],
- [Period("2019Q1", "Q-DEC"), Period("2019Q2", "Q-DEC")],
- [1.0, 1.0],
- [1.0, 1.0],
- ),
- ],
- )
- def test_period_reindex_with_object(
- self, p_values, o_values, values, expected_values
- ):
- # GH 28337
- period_index = PeriodIndex(p_values)
- object_index = Index(o_values)
-
- s = Series(values, index=period_index)
- result = s.reindex(object_index)
- expected = Series(expected_values, index=object_index)
- tm.assert_series_equal(result, expected)
-
def test_is_(self):
create_index = lambda: period_range(freq="A", start="1/1/2001", end="12/1/2009")
index = create_index()
diff --git a/pandas/tests/series/methods/test_reindex.py b/pandas/tests/series/methods/test_reindex.py
index 0415434f01fcf..22efc99805983 100644
--- a/pandas/tests/series/methods/test_reindex.py
+++ b/pandas/tests/series/methods/test_reindex.py
@@ -1,8 +1,16 @@
import numpy as np
import pytest
-import pandas as pd
-from pandas import Categorical, Series, date_range, isna
+from pandas import (
+ Categorical,
+ Index,
+ NaT,
+ Period,
+ PeriodIndex,
+ Series,
+ date_range,
+ isna,
+)
import pandas._testing as tm
@@ -293,5 +301,33 @@ def test_reindex_datetimeindexes_tz_naive_and_aware():
def test_reindex_empty_series_tz_dtype():
# GH 20869
result = Series(dtype="datetime64[ns, UTC]").reindex([0, 1])
- expected = Series([pd.NaT] * 2, dtype="datetime64[ns, UTC]")
+ expected = Series([NaT] * 2, dtype="datetime64[ns, UTC]")
tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "p_values, o_values, values, expected_values",
+ [
+ (
+ [Period("2019Q1", "Q-DEC"), Period("2019Q2", "Q-DEC")],
+ [Period("2019Q1", "Q-DEC"), Period("2019Q2", "Q-DEC"), "All"],
+ [1.0, 1.0],
+ [1.0, 1.0, np.nan],
+ ),
+ (
+ [Period("2019Q1", "Q-DEC"), Period("2019Q2", "Q-DEC")],
+ [Period("2019Q1", "Q-DEC"), Period("2019Q2", "Q-DEC")],
+ [1.0, 1.0],
+ [1.0, 1.0],
+ ),
+ ],
+)
+def test_reindex_periodindex_with_object(p_values, o_values, values, expected_values):
+ # GH#28337
+ period_index = PeriodIndex(p_values)
+ object_index = Index(o_values)
+
+ ser = Series(values, index=period_index)
+ result = ser.reindex(object_index)
+ expected = Series(expected_values, index=object_index)
+ tm.assert_series_equal(result, expected)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38570 | 2020-12-18T22:29:35Z | 2020-12-19T02:13:10Z | 2020-12-19T02:13:10Z | 2020-12-19T02:19:05Z |
TST/REF: indexes/datetimes/methods/ | diff --git a/pandas/tests/indexes/datetimelike_/__init__.py b/pandas/tests/indexes/datetimelike_/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/indexes/test_datetimelike.py b/pandas/tests/indexes/datetimelike_/test_equals.py
similarity index 100%
rename from pandas/tests/indexes/test_datetimelike.py
rename to pandas/tests/indexes/datetimelike_/test_equals.py
diff --git a/pandas/tests/indexes/datetimes/methods/__init__.py b/pandas/tests/indexes/datetimes/methods/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/methods/test_astype.py
similarity index 100%
rename from pandas/tests/indexes/datetimes/test_astype.py
rename to pandas/tests/indexes/datetimes/methods/test_astype.py
diff --git a/pandas/tests/indexes/datetimes/test_fillna.py b/pandas/tests/indexes/datetimes/methods/test_fillna.py
similarity index 100%
rename from pandas/tests/indexes/datetimes/test_fillna.py
rename to pandas/tests/indexes/datetimes/methods/test_fillna.py
diff --git a/pandas/tests/indexes/datetimes/test_shift.py b/pandas/tests/indexes/datetimes/methods/test_shift.py
similarity index 100%
rename from pandas/tests/indexes/datetimes/test_shift.py
rename to pandas/tests/indexes/datetimes/methods/test_shift.py
diff --git a/pandas/tests/indexes/datetimes/test_snap.py b/pandas/tests/indexes/datetimes/methods/test_snap.py
similarity index 100%
rename from pandas/tests/indexes/datetimes/test_snap.py
rename to pandas/tests/indexes/datetimes/methods/test_snap.py
diff --git a/pandas/tests/indexes/datetimes/test_to_period.py b/pandas/tests/indexes/datetimes/methods/test_to_period.py
similarity index 100%
rename from pandas/tests/indexes/datetimes/test_to_period.py
rename to pandas/tests/indexes/datetimes/methods/test_to_period.py
diff --git a/pandas/tests/indexes/period/methods/__init__.py b/pandas/tests/indexes/period/methods/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/indexes/period/test_asfreq.py b/pandas/tests/indexes/period/methods/test_asfreq.py
similarity index 100%
rename from pandas/tests/indexes/period/test_asfreq.py
rename to pandas/tests/indexes/period/methods/test_asfreq.py
diff --git a/pandas/tests/indexes/period/test_astype.py b/pandas/tests/indexes/period/methods/test_astype.py
similarity index 100%
rename from pandas/tests/indexes/period/test_astype.py
rename to pandas/tests/indexes/period/methods/test_astype.py
diff --git a/pandas/tests/indexes/period/test_fillna.py b/pandas/tests/indexes/period/methods/test_fillna.py
similarity index 100%
rename from pandas/tests/indexes/period/test_fillna.py
rename to pandas/tests/indexes/period/methods/test_fillna.py
diff --git a/pandas/tests/indexes/period/test_shift.py b/pandas/tests/indexes/period/methods/test_shift.py
similarity index 100%
rename from pandas/tests/indexes/period/test_shift.py
rename to pandas/tests/indexes/period/methods/test_shift.py
diff --git a/pandas/tests/indexes/period/test_to_timestamp.py b/pandas/tests/indexes/period/methods/test_to_timestamp.py
similarity index 100%
rename from pandas/tests/indexes/period/test_to_timestamp.py
rename to pandas/tests/indexes/period/methods/test_to_timestamp.py
diff --git a/pandas/tests/indexes/timedeltas/methods/__init__.py b/pandas/tests/indexes/timedeltas/methods/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/indexes/timedeltas/test_astype.py b/pandas/tests/indexes/timedeltas/methods/test_astype.py
similarity index 100%
rename from pandas/tests/indexes/timedeltas/test_astype.py
rename to pandas/tests/indexes/timedeltas/methods/test_astype.py
diff --git a/pandas/tests/indexes/timedeltas/test_fillna.py b/pandas/tests/indexes/timedeltas/methods/test_fillna.py
similarity index 100%
rename from pandas/tests/indexes/timedeltas/test_fillna.py
rename to pandas/tests/indexes/timedeltas/methods/test_fillna.py
diff --git a/pandas/tests/indexes/timedeltas/test_shift.py b/pandas/tests/indexes/timedeltas/methods/test_shift.py
similarity index 100%
rename from pandas/tests/indexes/timedeltas/test_shift.py
rename to pandas/tests/indexes/timedeltas/methods/test_shift.py
| https://api.github.com/repos/pandas-dev/pandas/pulls/38569 | 2020-12-18T22:24:42Z | 2020-12-19T02:10:45Z | 2020-12-19T02:10:45Z | 2020-12-19T02:13:30Z | |
TST/REF: misplaced DataFrame.append test | diff --git a/pandas/tests/frame/methods/test_append.py b/pandas/tests/frame/methods/test_append.py
index 38b5c150630fe..356dc800d9662 100644
--- a/pandas/tests/frame/methods/test_append.py
+++ b/pandas/tests/frame/methods/test_append.py
@@ -2,15 +2,14 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series, Timestamp
+from pandas import DataFrame, Series, Timestamp, date_range, timedelta_range
import pandas._testing as tm
class TestDataFrameAppend:
- @pytest.mark.parametrize("klass", [Series, DataFrame])
- def test_append_multiindex(self, multiindex_dataframe_random_data, klass):
+ def test_append_multiindex(self, multiindex_dataframe_random_data, frame_or_series):
obj = multiindex_dataframe_random_data
- if klass is Series:
+ if frame_or_series is Series:
obj = obj["A"]
a = obj[:5]
@@ -209,3 +208,17 @@ def test_other_dtypes(self, data, dtype):
result = df.append(df.iloc[0]).iloc[-1]
expected = Series(data, name=0, dtype=dtype)
tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["datetime64[ns]", "timedelta64[ns]"])
+ def test_append_numpy_bug_1681(self, dtype):
+ # another datetime64 bug
+ if dtype == "datetime64[ns]":
+ index = date_range("2011/1/1", "2012/1/1", freq="W-FRI")
+ else:
+ index = timedelta_range("1 days", "10 days", freq="2D")
+
+ df = DataFrame()
+ other = DataFrame({"A": "foo", "B": index}, index=index)
+
+ result = df.append(other)
+ assert (result["B"] == index).all()
diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py
index 789510b452969..361be07a2c7a2 100644
--- a/pandas/tests/indexes/datetimes/test_datetime.py
+++ b/pandas/tests/indexes/datetimes/test_datetime.py
@@ -216,15 +216,6 @@ def test_groupby_function_tuple_1677(self):
result = monthly_group.mean()
assert isinstance(result.index[0], tuple)
- def test_append_numpy_bug_1681(self):
- # another datetime64 bug
- dr = date_range("2011/1/1", "2012/1/1", freq="W-FRI")
- a = DataFrame()
- c = DataFrame({"A": "foo", "B": dr}, index=dr)
-
- result = a.append(c)
- assert (result["B"] == dr).all()
-
def test_isin(self):
index = tm.makeDateIndex(4)
result = index.isin(index)
diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py
index a1bc50604d34b..9c9fa08dd2852 100644
--- a/pandas/tests/indexes/timedeltas/test_timedelta.py
+++ b/pandas/tests/indexes/timedeltas/test_timedelta.py
@@ -5,7 +5,6 @@
import pandas as pd
from pandas import (
- DataFrame,
Index,
Int64Index,
Series,
@@ -146,16 +145,6 @@ def test_pass_TimedeltaIndex_to_index(self):
tm.assert_numpy_array_equal(idx.values, expected.values)
- def test_append_numpy_bug_1681(self):
-
- td = timedelta_range("1 days", "10 days", freq="2D")
- a = DataFrame()
- c = DataFrame({"A": "foo", "B": td}, index=td)
- str(c)
-
- result = a.append(c)
- assert (result["B"] == td).all()
-
def test_fields(self):
rng = timedelta_range("1 days, 10:11:12.100123456", periods=2, freq="s")
tm.assert_index_equal(rng.days, Index([1, 1], dtype="int64"))
| https://api.github.com/repos/pandas-dev/pandas/pulls/38568 | 2020-12-18T22:00:13Z | 2020-12-19T02:10:11Z | 2020-12-19T02:10:11Z | 2020-12-19T02:13:08Z | |
BUG: .sparse.to_coo() with numeric col index without a 0 | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 3545dd8a89159..72317b1b7da63 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -270,6 +270,7 @@ Reshaping
Sparse
^^^^^^
+- Bug in :meth:`DataFrame.sparse.to_coo` raising ``KeyError`` with columns that are a numeric :class:`Index` without a 0 (:issue:`18414`)
-
-
diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py
index ec4b0fd89860c..12f29faab9574 100644
--- a/pandas/core/arrays/sparse/accessor.py
+++ b/pandas/core/arrays/sparse/accessor.py
@@ -329,7 +329,7 @@ def to_coo(self):
import_optional_dependency("scipy")
from scipy.sparse import coo_matrix
- dtype = find_common_type(self._parent.dtypes)
+ dtype = find_common_type(self._parent.dtypes.to_list())
if isinstance(dtype, SparseDtype):
dtype = dtype.subtype
diff --git a/pandas/tests/arrays/sparse/test_accessor.py b/pandas/tests/arrays/sparse/test_accessor.py
index 2a81b94ce779c..4c6781509f8af 100644
--- a/pandas/tests/arrays/sparse/test_accessor.py
+++ b/pandas/tests/arrays/sparse/test_accessor.py
@@ -68,11 +68,14 @@ def test_from_spmatrix_columns(self, columns):
expected = pd.DataFrame(mat.toarray(), columns=columns).astype(dtype)
tm.assert_frame_equal(result, expected)
+ @pytest.mark.parametrize("colnames", [("A", "B"), (1, 2), (1, pd.NA), (0.1, 0.2)])
@td.skip_if_no_scipy
- def test_to_coo(self):
+ def test_to_coo(self, colnames):
import scipy.sparse
- df = pd.DataFrame({"A": [0, 1, 0], "B": [1, 0, 0]}, dtype="Sparse[int64, 0]")
+ df = pd.DataFrame(
+ {colnames[0]: [0, 1, 0], colnames[1]: [1, 0, 0]}, dtype="Sparse[int64, 0]"
+ )
result = df.sparse.to_coo()
expected = scipy.sparse.coo_matrix(np.asarray(df))
assert (result != expected).nnz == 0
| - [x] closes #18414
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Added tests for some other column name types which raised before this change, if that's overkill I can just test the int case from the OP. | https://api.github.com/repos/pandas-dev/pandas/pulls/38567 | 2020-12-18T20:13:14Z | 2020-12-22T14:10:54Z | 2020-12-22T14:10:54Z | 2020-12-22T14:31:58Z |
Backport PR #38560 on branch 1.2.x (Revert "REF: remove special casing from Index.equals (always dispatchto subclass) (#35330)") | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 46a1646727bae..11d191597d61e 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4455,15 +4455,16 @@ def equals(self, other: object) -> bool:
if not isinstance(other, Index):
return False
- # If other is a subclass of self and defines its own equals method, we
- # dispatch to the subclass method. For instance for a MultiIndex,
- # a d-level MultiIndex can equal d-tuple Index.
- # Note: All EA-backed Index subclasses override equals
- if (
- isinstance(other, type(self))
- and type(other) is not type(self)
- and other.equals is not self.equals
- ):
+ if is_object_dtype(self.dtype) and not is_object_dtype(other.dtype):
+ # if other is not object, use other's logic for coercion
+ return other.equals(self)
+
+ if isinstance(other, ABCMultiIndex):
+ # d-level MultiIndex can equal d-tuple Index
+ return other.equals(self)
+
+ if is_extension_array_dtype(other.dtype):
+ # All EA-backed Index subclasses override equals
return other.equals(self)
return array_equivalent(self._values, other._values)
| Backport PR #38560: Revert "REF: remove special casing from Index.equals (always dispatchto subclass) (#35330)" | https://api.github.com/repos/pandas-dev/pandas/pulls/38565 | 2020-12-18T19:05:46Z | 2020-12-18T20:54:56Z | 2020-12-18T20:54:56Z | 2020-12-18T20:54:56Z |
TST: GH30999 Add match=msg to test_nat_comparisons_invalid | diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py
index 2ea7602b00206..5dc0c40ef42dd 100644
--- a/pandas/tests/scalar/test_nat.py
+++ b/pandas/tests/scalar/test_nat.py
@@ -558,20 +558,28 @@ def test_nat_comparisons_numpy(other):
assert not NaT >= other
-@pytest.mark.parametrize("other", ["foo", 2, 2.0])
-@pytest.mark.parametrize("op", [operator.le, operator.lt, operator.ge, operator.gt])
-def test_nat_comparisons_invalid(other, op):
+@pytest.mark.parametrize("other_and_type", [("foo", "str"), (2, "int"), (2.0, "float")])
+@pytest.mark.parametrize(
+ "symbol_and_op",
+ [("<=", operator.le), ("<", operator.lt), (">=", operator.ge), (">", operator.gt)],
+)
+def test_nat_comparisons_invalid(other_and_type, symbol_and_op):
# GH#35585
+ other, other_type = other_and_type
+ symbol, op = symbol_and_op
+
assert not NaT == other
assert not other == NaT
assert NaT != other
assert other != NaT
- with pytest.raises(TypeError):
+ msg = f"'{symbol}' not supported between instances of 'NaTType' and '{other_type}'"
+ with pytest.raises(TypeError, match=msg):
op(NaT, other)
- with pytest.raises(TypeError):
+ msg = f"'{symbol}' not supported between instances of '{other_type}' and 'NaTType'"
+ with pytest.raises(TypeError, match=msg):
op(other, NaT)
| This pull request xref #30999 to remove bare pytest.raises. It doesn't close that issue as I have only addressed one file: pandas/tests/scalar/test_nat.py . In that file there was only one test that had a bare pytest.raises and I added a message to the two instances of pytest.raises in that test. It required modifications to the test parameters in order to populate the message.
I did not add a whatsnew entry since it's only a tiny change to one test. Let me know if I should add one (and I am a bit unclear on how, i.e. what version this would end up in).
This is my first ever pull request to an open source project. I am expecting that I will have to make changes before it's accepted; thanks for your patience.
- [ ] xref #30999
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38564 | 2020-12-18T18:59:20Z | 2020-12-18T23:07:55Z | 2020-12-18T23:07:55Z | 2020-12-21T12:37:04Z |
REF: handle non-list_like cases upfront in sanitize_array | diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index 248963ca3c859..3dc7acc6cf0b5 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -449,6 +449,11 @@ def sanitize_array(
# extract ndarray or ExtensionArray, ensure we have no PandasArray
data = extract_array(data, extract_numpy=True)
+ if isinstance(data, np.ndarray) and data.ndim == 0:
+ if dtype is None:
+ dtype = data.dtype
+ data = lib.item_from_zerodim(data)
+
# GH#846
if isinstance(data, np.ndarray):
@@ -462,7 +467,7 @@ def sanitize_array(
else:
subarr = np.array(data, copy=False)
else:
- # we will try to copy be-definition here
+ # we will try to copy by-definition here
subarr = _try_cast(data, dtype, copy, raise_cast_failure)
elif isinstance(data, ABCExtensionArray):
@@ -491,30 +496,16 @@ def sanitize_array(
# GH#16804
arr = np.arange(data.start, data.stop, data.step, dtype="int64")
subarr = _try_cast(arr, dtype, copy, raise_cast_failure)
- elif lib.is_scalar(data) and index is not None and dtype is not None:
+
+ elif not is_list_like(data):
+ if index is None:
+ raise ValueError("index must be specified when data is not list-like")
subarr = construct_1d_arraylike_from_scalar(data, len(index), dtype)
+
else:
subarr = _try_cast(data, dtype, copy, raise_cast_failure)
- # scalar like, GH
- if getattr(subarr, "ndim", 0) == 0:
- if isinstance(data, list): # pragma: no cover
- subarr = np.array(data, dtype=object)
- elif index is not None:
- subarr = construct_1d_arraylike_from_scalar(data, len(index), dtype)
-
- else:
- return subarr.item()
-
- # the result that we want
- elif subarr.ndim == 1:
- subarr = _maybe_repeat(subarr, index)
-
- elif subarr.ndim > 1:
- if isinstance(data, np.ndarray):
- raise ValueError("Data must be 1-dimensional")
- else:
- subarr = com.asarray_tuplesafe(data, dtype=dtype)
+ subarr = _sanitize_ndim(subarr, data, dtype, index)
if not (is_extension_array_dtype(subarr.dtype) or is_extension_array_dtype(dtype)):
subarr = _sanitize_str_dtypes(subarr, data, dtype, copy)
@@ -528,6 +519,27 @@ def sanitize_array(
return subarr
+def _sanitize_ndim(
+ result: ArrayLike, data, dtype: Optional[DtypeObj], index: Optional[Index]
+) -> ArrayLike:
+ """
+ Ensure we have a 1-dimensional result array.
+ """
+ if getattr(result, "ndim", 0) == 0:
+ raise ValueError("result should be arraylike with ndim > 0")
+
+ elif result.ndim == 1:
+ # the result that we want
+ result = _maybe_repeat(result, index)
+
+ elif result.ndim > 1:
+ if isinstance(data, np.ndarray):
+ raise ValueError("Data must be 1-dimensional")
+ else:
+ result = com.asarray_tuplesafe(data, dtype=dtype)
+ return result
+
+
def _sanitize_str_dtypes(
result: np.ndarray, data, dtype: Optional[DtypeObj], copy: bool
) -> np.ndarray:
@@ -565,7 +577,7 @@ def _try_cast(arr, dtype: Optional[DtypeObj], copy: bool, raise_cast_failure: bo
Parameters
----------
- arr : ndarray, scalar, list, tuple, iterator (catchall)
+ arr : ndarray, list, tuple, iterator (catchall)
Excludes: ExtensionArray, Series, Index.
dtype : np.dtype, ExtensionDtype or None
copy : bool
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index abcc60a15c641..034fd927a8017 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1543,7 +1543,10 @@ def construct_1d_arraylike_from_scalar(
"""
if dtype is None:
- dtype, value = infer_dtype_from_scalar(value, pandas_dtype=True)
+ try:
+ dtype, value = infer_dtype_from_scalar(value, pandas_dtype=True)
+ except OutOfBoundsDatetime:
+ dtype = np.dtype(object)
if is_extension_array_dtype(dtype):
cls = dtype.construct_array_type()
| so we can rule them out later | https://api.github.com/repos/pandas-dev/pandas/pulls/38563 | 2020-12-18T18:34:33Z | 2020-12-18T23:16:07Z | 2020-12-18T23:16:07Z | 2020-12-18T23:31:55Z |
REF: Block._astype defer to astype_nansafe in more cases | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index ee1323b71f146..79ecf8620c70c 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -346,7 +346,7 @@ def astype(self, dtype, copy=True):
elif is_string_dtype(dtype) and not is_categorical_dtype(dtype):
if is_extension_array_dtype(dtype):
arr_cls = dtype.construct_array_type()
- return arr_cls._from_sequence(self, dtype=dtype)
+ return arr_cls._from_sequence(self, dtype=dtype, copy=copy)
else:
return self._format_native_types()
elif is_integer_dtype(dtype):
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index b072ac3cec52e..b76051e4dce80 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -589,10 +589,15 @@ def astype(self, dtype, copy=True):
if is_datetime64_ns_dtype(dtype) and not is_dtype_equal(dtype, self.dtype):
# GH#18951: datetime64_ns dtype but not equal means different tz
+ # FIXME: this doesn't match DatetimeBlock.astype, xref GH#33401
new_tz = getattr(dtype, "tz", None)
- if getattr(self.dtype, "tz", None) is None:
+ if self.tz is None:
return self.tz_localize(new_tz)
- result = self.tz_convert(new_tz)
+ elif new_tz is None:
+ result = self.tz_convert("UTC").tz_localize(None)
+ else:
+ result = self.tz_convert(new_tz)
+
if copy:
result = result.copy()
if new_tz is None:
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index abcc60a15c641..3302ae0d6b8cf 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -30,7 +30,6 @@
conversion,
iNaT,
ints_to_pydatetime,
- ints_to_pytimedelta,
)
from pandas._libs.tslibs.timezones import tz_compare
from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Scalar
@@ -987,15 +986,21 @@ def astype_nansafe(
elif not isinstance(dtype, np.dtype):
raise ValueError("dtype must be np.dtype or ExtensionDtype")
+ if arr.dtype.kind in ["m", "M"] and (
+ issubclass(dtype.type, str) or dtype == object
+ ):
+ from pandas.core.construction import ensure_wrapped_if_datetimelike
+
+ arr = ensure_wrapped_if_datetimelike(arr)
+ return arr.astype(dtype, copy=copy)
+
if issubclass(dtype.type, str):
return lib.ensure_string_array(
arr.ravel(), skipna=skipna, convert_na_value=False
).reshape(arr.shape)
elif is_datetime64_dtype(arr):
- if is_object_dtype(dtype):
- return ints_to_pydatetime(arr.view(np.int64))
- elif dtype == np.int64:
+ if dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
return arr.view(dtype)
@@ -1007,9 +1012,7 @@ def astype_nansafe(
raise TypeError(f"cannot astype a datetimelike from [{arr.dtype}] to [{dtype}]")
elif is_timedelta64_dtype(arr):
- if is_object_dtype(dtype):
- return ints_to_pytimedelta(arr.view(np.int64))
- elif dtype == np.int64:
+ if dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
return arr.view(dtype)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 9b0c3caa0b407..446186f8414ee 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5852,6 +5852,7 @@ def astype(
elif is_extension_array_dtype(dtype) and self.ndim > 1:
# GH 18099/22869: columnwise conversion to extension dtype
# GH 24704: use iloc to handle duplicate column names
+ # TODO(EA2D): special case not needed with 2D EAs
results = [
self.iloc[:, i].astype(dtype, copy=copy)
for i in range(len(self.columns))
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 59301391a7dad..0bd60931f9a7e 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -75,7 +75,7 @@
)
from pandas.core.base import PandasObject
import pandas.core.common as com
-from pandas.core.construction import array as pd_array, extract_array
+from pandas.core.construction import extract_array
from pandas.core.indexers import (
check_setitem_lengths,
is_empty_indexer,
@@ -676,24 +676,6 @@ def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike:
values = values.astype(dtype, copy=copy)
else:
- if issubclass(dtype.type, str):
- if values.dtype.kind in ["m", "M"]:
- # use native type formatting for datetime/tz/timedelta
- arr = pd_array(values)
- # Note: in the case where dtype is an np.dtype, i.e. not
- # StringDtype, this matches arr.astype(dtype), xref GH#36153
- values = arr._format_native_types(na_rep="NaT")
-
- elif is_object_dtype(dtype):
- if values.dtype.kind in ["m", "M"]:
- # Wrap in Timedelta/Timestamp
- arr = pd_array(values)
- values = arr.astype(object)
- else:
- values = values.astype(object)
- # We still need to go through astype_nansafe for
- # e.g. dtype = Sparse[object, 0]
-
values = astype_nansafe(values, dtype, copy=True)
return values
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index 7cc032e61e989..5365929213503 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -126,7 +126,12 @@ def test_string_methods(input, method, dtype, request):
def test_astype_roundtrip(dtype, request):
if dtype == "arrow_string":
reason = "ValueError: Could not convert object to NumPy datetime"
- mark = pytest.mark.xfail(reason=reason)
+ 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)
ser = pd.Series(pd.date_range("2000", periods=12))
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index 54559400e3510..3c65551aafd0f 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -611,3 +611,31 @@ def test_astype_tz_object_conversion(self, tz):
# do real test: object dtype to a specified tz, different from construction tz.
result = result.astype({"tz": "datetime64[ns, Europe/London]"})
tm.assert_frame_equal(result, expected)
+
+ def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture, request):
+ tz = tz_naive_fixture
+ if tz is None:
+ mark = pytest.mark.xfail(
+ reason="GH#36153 uses ndarray formatting instead of DTA formatting"
+ )
+ request.node.add_marker(mark)
+
+ dti = date_range("2016-01-01", periods=3, tz=tz)
+ dta = dti._data
+ dta[0] = NaT
+
+ obj = frame_or_series(dta)
+ result = obj.astype("string")
+
+ # Check that Series/DataFrame.astype matches DatetimeArray.astype
+ expected = frame_or_series(dta.astype("string"))
+ tm.assert_equal(result, expected)
+
+ item = result.iloc[0]
+ if frame_or_series is DataFrame:
+ item = item.iloc[0]
+ assert item is pd.NA
+
+ # For non-NA values, we should match what we get for non-EA str
+ alt = obj.astype(str)
+ assert np.all(alt.iloc[1:] == result.iloc[1:])
| Makes astype_nansafe for (td64|dt64) -> (object|str|string) match DTA/TDA/Series behavior.
Medium-term (weeks) the goal is to get rid of Block._astype altogether and just use astype_nansafe, which among other things will be helpful for ArrayManager.
This changes `Series[dt64].astype("string")` behavior in a way that causes a new xfail in test_astype_roundtrip, but as discussed in #36153 that test is already wrong for other reasons.
This also has a side-effect of changing Series(dt64, dtype="Sparse[object]") behavior, discussed in #38508 as possibly not-desirable. | https://api.github.com/repos/pandas-dev/pandas/pulls/38562 | 2020-12-18T18:30:09Z | 2020-12-21T16:38:25Z | 2020-12-21T16:38:25Z | 2021-05-10T11:06:10Z |
Move docstring of NDFrame.replace in preparation of #32542 | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 1bf40f782f666..78b2accf92752 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -180,6 +180,9 @@
"axis": """axis : {0 or 'index', 1 or 'columns'}, default 0
If 0 or 'index': apply function to each column.
If 1 or 'columns': apply function to each row.""",
+ "inplace": """
+ inplace : boolean, default False
+ If True, performs operation inplace and returns None.""",
"optional_by": """
by : str or list of str
Name or list of names to sort by.
@@ -193,6 +196,9 @@
"optional_axis": """axis : int or str, optional
Axis to target. Can be either the axis name ('index', 'columns')
or number (0, 1).""",
+ "replace_iloc": """
+ This differs from updating with ``.loc`` or ``.iloc``, which require
+ you to specify a location to update with some value.""",
}
_numeric_only_doc = """numeric_only : boolean, default None
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index f9aa5ca9e8ea9..8e2f21bba5dfd 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -133,9 +133,15 @@
"klass": "Series/DataFrame",
"axes_single_arg": "int or labels for object",
"args_transpose": "axes to permute (int or label for object)",
+ "inplace": """
+ inplace : boolean, default False
+ If True, performs operation inplace and returns None.""",
"optional_by": """
by : str or list of str
Name or list of names to sort by""",
+ "replace_iloc": """
+ This differs from updating with ``.loc`` or ``.iloc``, which require
+ you to specify a location to update with some value.""",
}
@@ -6469,7 +6475,12 @@ def bfill(
backfill = bfill
- @doc(klass=_shared_doc_kwargs["klass"])
+ @doc(
+ _shared_docs["replace"],
+ klass=_shared_doc_kwargs["klass"],
+ inplace=_shared_doc_kwargs["inplace"],
+ replace_iloc=_shared_doc_kwargs["replace_iloc"],
+ )
def replace(
self,
to_replace=None,
@@ -6479,282 +6490,6 @@ def replace(
regex=False,
method="pad",
):
- """
- Replace values given in `to_replace` with `value`.
-
- Values of the {klass} are replaced with other values dynamically.
- This differs from updating with ``.loc`` or ``.iloc``, which require
- you to specify a location to update with some value.
-
- Parameters
- ----------
- to_replace : str, regex, list, dict, Series, int, float, or None
- How to find the values that will be replaced.
-
- * numeric, str or regex:
-
- - numeric: numeric values equal to `to_replace` will be
- replaced with `value`
- - str: string exactly matching `to_replace` will be replaced
- with `value`
- - regex: regexs matching `to_replace` will be replaced with
- `value`
-
- * list of str, regex, or numeric:
-
- - First, if `to_replace` and `value` are both lists, they
- **must** be the same length.
- - Second, if ``regex=True`` then all of the strings in **both**
- lists will be interpreted as regexs otherwise they will match
- directly. This doesn't matter much for `value` since there
- are only a few possible substitution regexes you can use.
- - str, regex and numeric rules apply as above.
-
- * dict:
-
- - Dicts can be used to specify different replacement values
- for different existing values. For example,
- ``{{'a': 'b', 'y': 'z'}}`` replaces the value 'a' with 'b' and
- 'y' with 'z'. To use a dict in this way the `value`
- parameter should be `None`.
- - For a DataFrame a dict can specify that different values
- should be replaced in different columns. For example,
- ``{{'a': 1, 'b': 'z'}}`` looks for the value 1 in column 'a'
- and the value 'z' in column 'b' and replaces these values
- with whatever is specified in `value`. The `value` parameter
- should not be ``None`` in this case. You can treat this as a
- special case of passing two lists except that you are
- specifying the column to search in.
- - For a DataFrame nested dictionaries, e.g.,
- ``{{'a': {{'b': np.nan}}}}``, are read as follows: look in column
- 'a' for the value 'b' and replace it with NaN. The `value`
- parameter should be ``None`` to use a nested dict in this
- way. You can nest regular expressions as well. Note that
- column names (the top-level dictionary keys in a nested
- dictionary) **cannot** be regular expressions.
-
- * None:
-
- - This means that the `regex` argument must be a string,
- compiled regular expression, or list, dict, ndarray or
- Series of such elements. If `value` is also ``None`` then
- this **must** be a nested dictionary or Series.
-
- See the examples section for examples of each of these.
- value : scalar, dict, list, str, regex, default None
- Value to replace any values matching `to_replace` with.
- For a DataFrame a dict of values can be used to specify which
- value to use for each column (columns not in the dict will not be
- filled). Regular expressions, strings and lists or dicts of such
- objects are also allowed.
- inplace : bool, default False
- If True, in place. Note: this will modify any
- other views on this object (e.g. a column from a DataFrame).
- Returns the caller if this is True.
- limit : int or None, default None
- Maximum size gap to forward or backward fill.
- regex : bool or same types as `to_replace`, default False
- Whether to interpret `to_replace` and/or `value` as regular
- expressions. If this is ``True`` then `to_replace` *must* be a
- string. Alternatively, this could be a regular expression or a
- list, dict, or array of regular expressions in which case
- `to_replace` must be ``None``.
- method : {{'pad', 'ffill', 'bfill', `None`}}
- The method to use when for replacement, when `to_replace` is a
- scalar, list or tuple and `value` is ``None``.
-
- Returns
- -------
- {klass} or None
- Object after replacement or None if ``inplace=True``.
-
- Raises
- ------
- AssertionError
- * If `regex` is not a ``bool`` and `to_replace` is not
- ``None``.
-
- TypeError
- * If `to_replace` is not a scalar, array-like, ``dict``, or ``None``
- * If `to_replace` is a ``dict`` and `value` is not a ``list``,
- ``dict``, ``ndarray``, or ``Series``
- * If `to_replace` is ``None`` and `regex` is not compilable
- into a regular expression or is a list, dict, ndarray, or
- Series.
- * When replacing multiple ``bool`` or ``datetime64`` objects and
- the arguments to `to_replace` does not match the type of the
- value being replaced
-
- ValueError
- * If a ``list`` or an ``ndarray`` is passed to `to_replace` and
- `value` but they are not the same length.
-
- See Also
- --------
- {klass}.fillna : Fill NA values.
- {klass}.where : Replace values based on boolean condition.
- Series.str.replace : Simple string replacement.
-
- Notes
- -----
- * Regex substitution is performed under the hood with ``re.sub``. The
- rules for substitution for ``re.sub`` are the same.
- * Regular expressions will only substitute on strings, meaning you
- cannot provide, for example, a regular expression matching floating
- point numbers and expect the columns in your frame that have a
- numeric dtype to be matched. However, if those floating point
- numbers *are* strings, then you can do this.
- * This method has *a lot* of options. You are encouraged to experiment
- and play with this method to gain intuition about how it works.
- * When dict is used as the `to_replace` value, it is like
- key(s) in the dict are the to_replace part and
- value(s) in the dict are the value parameter.
-
- Examples
- --------
-
- **Scalar `to_replace` and `value`**
-
- >>> s = pd.Series([0, 1, 2, 3, 4])
- >>> s.replace(0, 5)
- 0 5
- 1 1
- 2 2
- 3 3
- 4 4
- dtype: int64
-
- >>> df = pd.DataFrame({{'A': [0, 1, 2, 3, 4],
- ... 'B': [5, 6, 7, 8, 9],
- ... 'C': ['a', 'b', 'c', 'd', 'e']}})
- >>> df.replace(0, 5)
- A B C
- 0 5 5 a
- 1 1 6 b
- 2 2 7 c
- 3 3 8 d
- 4 4 9 e
-
- **List-like `to_replace`**
-
- >>> df.replace([0, 1, 2, 3], 4)
- A B C
- 0 4 5 a
- 1 4 6 b
- 2 4 7 c
- 3 4 8 d
- 4 4 9 e
-
- >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])
- A B C
- 0 4 5 a
- 1 3 6 b
- 2 2 7 c
- 3 1 8 d
- 4 4 9 e
-
- >>> s.replace([1, 2], method='bfill')
- 0 0
- 1 3
- 2 3
- 3 3
- 4 4
- dtype: int64
-
- **dict-like `to_replace`**
-
- >>> df.replace({{0: 10, 1: 100}})
- A B C
- 0 10 5 a
- 1 100 6 b
- 2 2 7 c
- 3 3 8 d
- 4 4 9 e
-
- >>> df.replace({{'A': 0, 'B': 5}}, 100)
- A B C
- 0 100 100 a
- 1 1 6 b
- 2 2 7 c
- 3 3 8 d
- 4 4 9 e
-
- >>> df.replace({{'A': {{0: 100, 4: 400}}}})
- A B C
- 0 100 5 a
- 1 1 6 b
- 2 2 7 c
- 3 3 8 d
- 4 400 9 e
-
- **Regular expression `to_replace`**
-
- >>> df = pd.DataFrame({{'A': ['bat', 'foo', 'bait'],
- ... 'B': ['abc', 'bar', 'xyz']}})
- >>> df.replace(to_replace=r'^ba.$', value='new', regex=True)
- A B
- 0 new abc
- 1 foo new
- 2 bait xyz
-
- >>> df.replace({{'A': r'^ba.$'}}, {{'A': 'new'}}, regex=True)
- A B
- 0 new abc
- 1 foo bar
- 2 bait xyz
-
- >>> df.replace(regex=r'^ba.$', value='new')
- A B
- 0 new abc
- 1 foo new
- 2 bait xyz
-
- >>> df.replace(regex={{r'^ba.$': 'new', 'foo': 'xyz'}})
- A B
- 0 new abc
- 1 xyz new
- 2 bait xyz
-
- >>> df.replace(regex=[r'^ba.$', 'foo'], value='new')
- A B
- 0 new abc
- 1 new new
- 2 bait xyz
-
- Compare the behavior of ``s.replace({{'a': None}})`` and
- ``s.replace('a', None)`` to understand the peculiarities
- of the `to_replace` parameter:
-
- >>> s = pd.Series([10, 'a', 'a', 'b', 'a'])
-
- When one uses a dict as the `to_replace` value, it is like the
- value(s) in the dict are equal to the `value` parameter.
- ``s.replace({{'a': None}})`` is equivalent to
- ``s.replace(to_replace={{'a': None}}, value=None, method=None)``:
-
- >>> s.replace({{'a': None}})
- 0 10
- 1 None
- 2 None
- 3 b
- 4 None
- dtype: object
-
- When ``value=None`` and `to_replace` is a scalar, list or
- tuple, `replace` uses the method parameter (default 'pad') to do the
- replacement. So this is why the 'a' values are being replaced by 10
- in rows 1 and 2 and 'b' in row 4 in this case.
- The command ``s.replace('a', None)`` is actually equivalent to
- ``s.replace(to_replace='a', value=None, method='pad')``:
-
- >>> s.replace('a', None)
- 0 10
- 1 10
- 2 10
- 3 b
- 4 b
- dtype: object
- """
if not (
is_scalar(to_replace)
or is_re_compilable(to_replace)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 0e9476285c258..4351c21c5c7e5 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -125,6 +125,9 @@
"optional_mapper": "",
"optional_labels": "",
"optional_axis": "",
+ "replace_iloc": """
+ This differs from updating with ``.loc`` or ``.iloc``, which require
+ you to specify a location to update with some value.""",
}
@@ -4473,7 +4476,12 @@ def pop(self, item: Label) -> Any:
"""
return super().pop(item=item)
- @doc(NDFrame.replace, klass=_shared_doc_kwargs["klass"])
+ @doc(
+ NDFrame.replace,
+ klass=_shared_doc_kwargs["klass"],
+ inplace=_shared_doc_kwargs["inplace"],
+ replace_iloc=_shared_doc_kwargs["replace_iloc"],
+ )
def replace(
self,
to_replace=None,
diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py
index 6d3249802ee5e..ad2eafe7295b0 100644
--- a/pandas/core/shared_docs.py
+++ b/pandas/core/shared_docs.py
@@ -387,3 +387,281 @@
are forwarded to ``urllib`` as header options. For other URLs (e.g.
starting with "s3://", and "gcs://") the key-value pairs are forwarded to
``fsspec``. Please see ``fsspec`` and ``urllib`` for more details."""
+
+_shared_docs[
+ "replace"
+] = """
+ Replace values given in `to_replace` with `value`.
+
+ Values of the {klass} are replaced with other values dynamically.
+ {replace_iloc}
+
+ Parameters
+ ----------
+ to_replace : str, regex, list, dict, Series, int, float, or None
+ How to find the values that will be replaced.
+
+ * numeric, str or regex:
+
+ - numeric: numeric values equal to `to_replace` will be
+ replaced with `value`
+ - str: string exactly matching `to_replace` will be replaced
+ with `value`
+ - regex: regexs matching `to_replace` will be replaced with
+ `value`
+
+ * list of str, regex, or numeric:
+
+ - First, if `to_replace` and `value` are both lists, they
+ **must** be the same length.
+ - Second, if ``regex=True`` then all of the strings in **both**
+ lists will be interpreted as regexs otherwise they will match
+ directly. This doesn't matter much for `value` since there
+ are only a few possible substitution regexes you can use.
+ - str, regex and numeric rules apply as above.
+
+ * dict:
+
+ - Dicts can be used to specify different replacement values
+ for different existing values. For example,
+ ``{{'a': 'b', 'y': 'z'}}`` replaces the value 'a' with 'b' and
+ 'y' with 'z'. To use a dict in this way the `value`
+ parameter should be `None`.
+ - For a DataFrame a dict can specify that different values
+ should be replaced in different columns. For example,
+ ``{{'a': 1, 'b': 'z'}}`` looks for the value 1 in column 'a'
+ and the value 'z' in column 'b' and replaces these values
+ with whatever is specified in `value`. The `value` parameter
+ should not be ``None`` in this case. You can treat this as a
+ special case of passing two lists except that you are
+ specifying the column to search in.
+ - For a DataFrame nested dictionaries, e.g.,
+ ``{{'a': {{'b': np.nan}}}}``, are read as follows: look in column
+ 'a' for the value 'b' and replace it with NaN. The `value`
+ parameter should be ``None`` to use a nested dict in this
+ way. You can nest regular expressions as well. Note that
+ column names (the top-level dictionary keys in a nested
+ dictionary) **cannot** be regular expressions.
+
+ * None:
+
+ - This means that the `regex` argument must be a string,
+ compiled regular expression, or list, dict, ndarray or
+ Series of such elements. If `value` is also ``None`` then
+ this **must** be a nested dictionary or Series.
+
+ See the examples section for examples of each of these.
+ value : scalar, dict, list, str, regex, default None
+ Value to replace any values matching `to_replace` with.
+ For a DataFrame a dict of values can be used to specify which
+ value to use for each column (columns not in the dict will not be
+ filled). Regular expressions, strings and lists or dicts of such
+ objects are also allowed.
+ {inplace}
+ limit : int, default None
+ Maximum size gap to forward or backward fill.
+ regex : bool or same types as `to_replace`, default False
+ Whether to interpret `to_replace` and/or `value` as regular
+ expressions. If this is ``True`` then `to_replace` *must* be a
+ string. Alternatively, this could be a regular expression or a
+ list, dict, or array of regular expressions in which case
+ `to_replace` must be ``None``.
+ method : {{'pad', 'ffill', 'bfill', `None`}}
+ The method to use when for replacement, when `to_replace` is a
+ scalar, list or tuple and `value` is ``None``.
+
+ .. versionchanged:: 0.23.0
+ Added to DataFrame.
+
+ Returns
+ -------
+ {klass}
+ Object after replacement.
+
+ Raises
+ ------
+ AssertionError
+ * If `regex` is not a ``bool`` and `to_replace` is not
+ ``None``.
+
+ TypeError
+ * If `to_replace` is not a scalar, array-like, ``dict``, or ``None``
+ * If `to_replace` is a ``dict`` and `value` is not a ``list``,
+ ``dict``, ``ndarray``, or ``Series``
+ * If `to_replace` is ``None`` and `regex` is not compilable
+ into a regular expression or is a list, dict, ndarray, or
+ Series.
+ * When replacing multiple ``bool`` or ``datetime64`` objects and
+ the arguments to `to_replace` does not match the type of the
+ value being replaced
+
+ ValueError
+ * If a ``list`` or an ``ndarray`` is passed to `to_replace` and
+ `value` but they are not the same length.
+
+ See Also
+ --------
+ {klass}.fillna : Fill NA values.
+ {klass}.where : Replace values based on boolean condition.
+ Series.str.replace : Simple string replacement.
+
+ Notes
+ -----
+ * Regex substitution is performed under the hood with ``re.sub``. The
+ rules for substitution for ``re.sub`` are the same.
+ * Regular expressions will only substitute on strings, meaning you
+ cannot provide, for example, a regular expression matching floating
+ point numbers and expect the columns in your frame that have a
+ numeric dtype to be matched. However, if those floating point
+ numbers *are* strings, then you can do this.
+ * This method has *a lot* of options. You are encouraged to experiment
+ and play with this method to gain intuition about how it works.
+ * When dict is used as the `to_replace` value, it is like
+ key(s) in the dict are the to_replace part and
+ value(s) in the dict are the value parameter.
+
+ Examples
+ --------
+
+ **Scalar `to_replace` and `value`**
+
+ >>> s = pd.Series([0, 1, 2, 3, 4])
+ >>> s.replace(0, 5)
+ 0 5
+ 1 1
+ 2 2
+ 3 3
+ 4 4
+ dtype: int64
+
+ >>> df = pd.DataFrame({{'A': [0, 1, 2, 3, 4],
+ ... 'B': [5, 6, 7, 8, 9],
+ ... 'C': ['a', 'b', 'c', 'd', 'e']}})
+ >>> df.replace(0, 5)
+ A B C
+ 0 5 5 a
+ 1 1 6 b
+ 2 2 7 c
+ 3 3 8 d
+ 4 4 9 e
+
+ **List-like `to_replace`**
+
+ >>> df.replace([0, 1, 2, 3], 4)
+ A B C
+ 0 4 5 a
+ 1 4 6 b
+ 2 4 7 c
+ 3 4 8 d
+ 4 4 9 e
+
+ >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])
+ A B C
+ 0 4 5 a
+ 1 3 6 b
+ 2 2 7 c
+ 3 1 8 d
+ 4 4 9 e
+
+ >>> s.replace([1, 2], method='bfill')
+ 0 0
+ 1 3
+ 2 3
+ 3 3
+ 4 4
+ dtype: int64
+
+ **dict-like `to_replace`**
+
+ >>> df.replace({{0: 10, 1: 100}})
+ A B C
+ 0 10 5 a
+ 1 100 6 b
+ 2 2 7 c
+ 3 3 8 d
+ 4 4 9 e
+
+ >>> df.replace({{'A': 0, 'B': 5}}, 100)
+ A B C
+ 0 100 100 a
+ 1 1 6 b
+ 2 2 7 c
+ 3 3 8 d
+ 4 4 9 e
+
+ >>> df.replace({{'A': {{0: 100, 4: 400}}}})
+ A B C
+ 0 100 5 a
+ 1 1 6 b
+ 2 2 7 c
+ 3 3 8 d
+ 4 400 9 e
+
+ **Regular expression `to_replace`**
+
+ >>> df = pd.DataFrame({{'A': ['bat', 'foo', 'bait'],
+ ... 'B': ['abc', 'bar', 'xyz']}})
+ >>> df.replace(to_replace=r'^ba.$', value='new', regex=True)
+ A B
+ 0 new abc
+ 1 foo new
+ 2 bait xyz
+
+ >>> df.replace({{'A': r'^ba.$'}}, {{'A': 'new'}}, regex=True)
+ A B
+ 0 new abc
+ 1 foo bar
+ 2 bait xyz
+
+ >>> df.replace(regex=r'^ba.$', value='new')
+ A B
+ 0 new abc
+ 1 foo new
+ 2 bait xyz
+
+ >>> df.replace(regex={{r'^ba.$': 'new', 'foo': 'xyz'}})
+ A B
+ 0 new abc
+ 1 xyz new
+ 2 bait xyz
+
+ >>> df.replace(regex=[r'^ba.$', 'foo'], value='new')
+ A B
+ 0 new abc
+ 1 new new
+ 2 bait xyz
+
+ Compare the behavior of ``s.replace({{'a': None}})`` and
+ ``s.replace('a', None)`` to understand the peculiarities
+ of the `to_replace` parameter:
+
+ >>> s = pd.Series([10, 'a', 'a', 'b', 'a'])
+
+ When one uses a dict as the `to_replace` value, it is like the
+ value(s) in the dict are equal to the `value` parameter.
+ ``s.replace({{'a': None}})`` is equivalent to
+ ``s.replace(to_replace={{'a': None}}, value=None, method=None)``:
+
+ >>> s.replace({{'a': None}})
+ 0 10
+ 1 None
+ 2 None
+ 3 b
+ 4 None
+ dtype: object
+
+ When ``value=None`` and `to_replace` is a scalar, list or
+ tuple, `replace` uses the method parameter (default 'pad') to do the
+ replacement. So this is why the 'a' values are being replaced by 10
+ in rows 1 and 2 and 'b' in row 4 in this case.
+ The command ``s.replace('a', None)`` is actually equivalent to
+ ``s.replace(to_replace='a', value=None, method='pad')``:
+
+ >>> s.replace('a', None)
+ 0 10
+ 1 10
+ 2 10
+ 3 b
+ 4 b
+ dtype: object
+"""
| This is a pre-cursor PR for #32542 as requested by @jreback [here](https://github.com/pandas-dev/pandas/pull/32542#issuecomment-744043100).
It moves the docstring of `replace()` method(s) to `pandas.core.shared_docs` so that we can reuse most of it for index classes. | https://api.github.com/repos/pandas-dev/pandas/pulls/38561 | 2020-12-18T15:55:35Z | 2020-12-22T23:21:10Z | 2020-12-22T23:21:10Z | 2020-12-23T06:47:41Z |
Revert "REF: remove special casing from Index.equals (always dispatchto subclass) (#35330)" | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 8d38e7f173594..6e2bbc5e3a0e6 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4442,15 +4442,16 @@ def equals(self, other: object) -> bool:
if not isinstance(other, Index):
return False
- # If other is a subclass of self and defines its own equals method, we
- # dispatch to the subclass method. For instance for a MultiIndex,
- # a d-level MultiIndex can equal d-tuple Index.
- # Note: All EA-backed Index subclasses override equals
- if (
- isinstance(other, type(self))
- and type(other) is not type(self)
- and other.equals is not self.equals
- ):
+ if is_object_dtype(self.dtype) and not is_object_dtype(other.dtype):
+ # if other is not object, use other's logic for coercion
+ return other.equals(self)
+
+ if isinstance(other, ABCMultiIndex):
+ # d-level MultiIndex can equal d-tuple Index
+ return other.equals(self)
+
+ if is_extension_array_dtype(other.dtype):
+ # All EA-backed Index subclasses override equals
return other.equals(self)
return array_equivalent(self._values, other._values)
| This reverts commit 0b90685f4df2024754748b992d5eaaa352e7caa5.
- [ ] closes #35804
- [ ] closes #35805
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
```
before after ratio
[54682234] [05c97adb]
<master> <revert-35330>
- 293±5ms 3.75±0.2μs 0.00 index_object.IndexEquals.time_non_object_equals_multiindex
SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.
PERFORMANCE INCREASED.
```
```
before after ratio
[54682234] [05c97adb]
<master> <revert-35330>
- 1.44±0.1ms 800±20μs 0.56 reindex.LevelAlign.time_reindex_level
SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.
PERFORMANCE INCREASED.
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/38560 | 2020-12-18T13:08:58Z | 2020-12-18T16:44:51Z | 2020-12-18T16:44:50Z | 2020-12-18T19:05:32Z |
Backport PR #38514 on branch 1.2.x (CI: un-xfail) | diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index fe3ca0d0937b3..99e7c3061d670 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -671,12 +671,7 @@ def test_s3_roundtrip(self, df_compat, s3_resource, pa, s3so):
@pytest.mark.parametrize(
"partition_col",
[
- pytest.param(
- ["A"],
- marks=pytest.mark.xfail(
- PY38, reason="Getting back empty DataFrame", raises=AssertionError
- ),
- ),
+ ["A"],
[],
],
)
| Backport PR #38514: CI: un-xfail | https://api.github.com/repos/pandas-dev/pandas/pulls/38559 | 2020-12-18T12:07:24Z | 2020-12-18T14:14:33Z | 2020-12-18T14:14:33Z | 2020-12-18T14:14:33Z |
Backport PR #38526 on branch 1.2.x (CI: pin xlrd<2.0) | diff --git a/ci/deps/azure-37-slow.yaml b/ci/deps/azure-37-slow.yaml
index 50fccf86b6340..05b33fa351ac9 100644
--- a/ci/deps/azure-37-slow.yaml
+++ b/ci/deps/azure-37-slow.yaml
@@ -31,7 +31,7 @@ dependencies:
- moto>=1.3.14
- scipy
- sqlalchemy
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/azure-38-locale.yaml b/ci/deps/azure-38-locale.yaml
index f879111a32e67..90cd11037e472 100644
--- a/ci/deps/azure-38-locale.yaml
+++ b/ci/deps/azure-38-locale.yaml
@@ -30,7 +30,7 @@ dependencies:
- pytz
- scipy
- xarray
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/azure-macos-37.yaml b/ci/deps/azure-macos-37.yaml
index 31e0ffca81424..0b8aff83fe230 100644
--- a/ci/deps/azure-macos-37.yaml
+++ b/ci/deps/azure-macos-37.yaml
@@ -26,7 +26,7 @@ dependencies:
- python-dateutil==2.7.3
- pytz
- xarray
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- pip
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index 16b4bd72683b4..ad72b9c8577e9 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -33,7 +33,7 @@ dependencies:
- s3fs>=0.4.2
- scipy
- sqlalchemy
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- pyreadstat
diff --git a/ci/deps/azure-windows-38.yaml b/ci/deps/azure-windows-38.yaml
index 449bbd05991bf..08693e02aa8d3 100644
--- a/ci/deps/azure-windows-38.yaml
+++ b/ci/deps/azure-windows-38.yaml
@@ -31,6 +31,6 @@ dependencies:
- pytz
- s3fs>=0.4.0
- scipy
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
diff --git a/ci/deps/travis-37-cov.yaml b/ci/deps/travis-37-cov.yaml
index c89b42ef06a2e..b68ff0672888a 100644
--- a/ci/deps/travis-37-cov.yaml
+++ b/ci/deps/travis-37-cov.yaml
@@ -43,7 +43,7 @@ dependencies:
- sqlalchemy
- statsmodels
- xarray
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- pip
diff --git a/ci/deps/travis-37-locale.yaml b/ci/deps/travis-37-locale.yaml
index 4e442b10482a7..60a92c4dfd3c6 100644
--- a/ci/deps/travis-37-locale.yaml
+++ b/ci/deps/travis-37-locale.yaml
@@ -35,7 +35,7 @@ dependencies:
- pytables>=3.5.1
- scipy
- xarray=0.12.3
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/travis-38-slow.yaml b/ci/deps/travis-38-slow.yaml
index e4b719006a11e..2b4339cf12658 100644
--- a/ci/deps/travis-38-slow.yaml
+++ b/ci/deps/travis-38-slow.yaml
@@ -30,7 +30,7 @@ dependencies:
- moto>=1.3.14
- scipy
- sqlalchemy
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
| Backport PR #38526: CI: pin xlrd<2.0 | https://api.github.com/repos/pandas-dev/pandas/pulls/38557 | 2020-12-18T10:17:00Z | 2020-12-18T12:49:04Z | 2020-12-18T12:49:04Z | 2020-12-18T12:49:05Z |
Backport PR #38504: REG: DataFrame.shift with axis=1 and CategoricalIndex columns | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index a1582a57e9a71..396108bab47b7 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4572,20 +4572,23 @@ def shift(
if axis == 1 and periods != 0 and fill_value is lib.no_default and ncols > 0:
# We will infer fill_value to match the closest column
+ # Use a column that we know is valid for our column's dtype GH#38434
+ label = self.columns[0]
+
if periods > 0:
result = self.iloc[:, :-periods]
for col in range(min(ncols, abs(periods))):
# TODO(EA2D): doing this in a loop unnecessary with 2D EAs
# Define filler inside loop so we get a copy
filler = self.iloc[:, 0].shift(len(self))
- result.insert(0, col, filler, allow_duplicates=True)
+ result.insert(0, label, filler, allow_duplicates=True)
else:
result = self.iloc[:, -periods:]
for col in range(min(ncols, abs(periods))):
# Define filler inside loop so we get a copy
filler = self.iloc[:, -1].shift(len(self))
result.insert(
- len(result.columns), col, filler, allow_duplicates=True
+ len(result.columns), label, filler, allow_duplicates=True
)
result.columns = self.columns.copy()
diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py
index 2e21ce8ec2256..40b3f1e89c015 100644
--- a/pandas/tests/frame/methods/test_shift.py
+++ b/pandas/tests/frame/methods/test_shift.py
@@ -2,7 +2,7 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Series, date_range, offsets
+from pandas import CategoricalIndex, DataFrame, Index, Series, date_range, offsets
import pandas._testing as tm
@@ -292,3 +292,25 @@ def test_shift_dt64values_int_fill_deprecated(self):
expected = DataFrame({"A": [pd.Timestamp(0), pd.Timestamp(0)], "B": df2["A"]})
tm.assert_frame_equal(result, expected)
+
+ def test_shift_axis1_categorical_columns(self):
+ # GH#38434
+ ci = CategoricalIndex(["a", "b", "c"])
+ df = DataFrame(
+ {"a": [1, 3], "b": [2, 4], "c": [5, 6]}, index=ci[:-1], columns=ci
+ )
+ result = df.shift(axis=1)
+
+ expected = DataFrame(
+ {"a": [np.nan, np.nan], "b": [1, 3], "c": [2, 4]}, index=ci[:-1], columns=ci
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # periods != 1
+ result = df.shift(2, axis=1)
+ expected = DataFrame(
+ {"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 3]},
+ index=ci[:-1],
+ columns=ci,
+ )
+ tm.assert_frame_equal(result, expected)
| Backport PR #38504 | https://api.github.com/repos/pandas-dev/pandas/pulls/38555 | 2020-12-18T09:33:46Z | 2020-12-18T15:05:04Z | 2020-12-18T15:05:04Z | 2020-12-18T15:05:08Z |
DOC: add Comparison with Excel | diff --git a/doc/source/_static/excel_pivot.png b/doc/source/_static/excel_pivot.png
new file mode 100644
index 0000000000000..beacc90bc313e
Binary files /dev/null and b/doc/source/_static/excel_pivot.png differ
diff --git a/doc/source/_static/logo_excel.svg b/doc/source/_static/logo_excel.svg
new file mode 100644
index 0000000000000..ffb25108df67c
--- /dev/null
+++ b/doc/source/_static/logo_excel.svg
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Generator: Adobe Illustrator 23.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg version="1.1" id="Livello_1" xmlns:x="http://ns.adobe.com/Extensibility/1.0/" xmlns:i="http://ns.adobe.com/AdobeIllustrator/10.0/" xmlns:graph="http://ns.adobe.com/Graphs/1.0/" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 2289.75 2130" enable-background="new 0 0 2289.75 2130" xml:space="preserve">
+<metadata>
+ <sfw xmlns="http://ns.adobe.com/SaveForWeb/1.0/">
+ <slices/>
+ <sliceSourceBounds bottomLeftOrigin="true" height="2130" width="2289.75" x="-1147.5" y="-1041"/>
+ </sfw>
+</metadata>
+<path fill="#185C37" d="M1437.75,1011.75L532.5,852v1180.393c0,53.907,43.7,97.607,97.607,97.607l0,0h1562.036 c53.907,0,97.607-43.7,97.607-97.607l0,0V1597.5L1437.75,1011.75z"/>
+<path fill="#21A366" d="M1437.75,0H630.107C576.2,0,532.5,43.7,532.5,97.607c0,0,0,0,0,0V532.5l905.25,532.5L1917,1224.75 L2289.75,1065V532.5L1437.75,0z"/>
+<path fill="#107C41" d="M532.5,532.5h905.25V1065H532.5V532.5z"/>
+<path opacity="0.1" enable-background="new " d="M1180.393,426H532.5v1331.25h647.893c53.834-0.175,97.432-43.773,97.607-97.607 V523.607C1277.825,469.773,1234.227,426.175,1180.393,426z"/>
+<path opacity="0.2" enable-background="new " d="M1127.143,479.25H532.5V1810.5h594.643 c53.834-0.175,97.432-43.773,97.607-97.607V576.857C1224.575,523.023,1180.977,479.425,1127.143,479.25z"/>
+<path opacity="0.2" enable-background="new " d="M1127.143,479.25H532.5V1704h594.643c53.834-0.175,97.432-43.773,97.607-97.607 V576.857C1224.575,523.023,1180.977,479.425,1127.143,479.25z"/>
+<path opacity="0.2" enable-background="new " d="M1073.893,479.25H532.5V1704h541.393c53.834-0.175,97.432-43.773,97.607-97.607 V576.857C1171.325,523.023,1127.727,479.425,1073.893,479.25z"/>
+<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="203.5132" y1="1729.0183" x2="967.9868" y2="404.9817" gradientTransform="matrix(1 0 0 -1 0 2132)">
+ <stop offset="0" style="stop-color:#18884F"/>
+ <stop offset="0.5" style="stop-color:#117E43"/>
+ <stop offset="1" style="stop-color:#0B6631"/>
+</linearGradient>
+<path fill="url(#SVGID_1_)" d="M97.607,479.25h976.285c53.907,0,97.607,43.7,97.607,97.607v976.285 c0,53.907-43.7,97.607-97.607,97.607H97.607C43.7,1650.75,0,1607.05,0,1553.143V576.857C0,522.95,43.7,479.25,97.607,479.25z"/>
+<path fill="#FFFFFF" d="M302.3,1382.264l205.332-318.169L319.5,747.683h151.336l102.666,202.35 c9.479,19.223,15.975,33.494,19.49,42.919h1.331c6.745-15.336,13.845-30.228,21.3-44.677L725.371,747.79h138.929l-192.925,314.548 L869.2,1382.263H721.378L602.79,1160.158c-5.586-9.45-10.326-19.376-14.164-29.66h-1.757c-3.474,10.075-8.083,19.722-13.739,28.755 l-122.102,223.011H302.3z"/>
+<path fill="#33C481" d="M2192.143,0H1437.75v532.5h852V97.607C2289.75,43.7,2246.05,0,2192.143,0L2192.143,0z"/>
+<path fill="#107C41" d="M1437.75,1065h852v532.5h-852V1065z"/>
+</svg>
\ No newline at end of file
diff --git a/doc/source/getting_started/comparison/comparison_boilerplate.rst b/doc/source/getting_started/comparison/comparison_boilerplate.rst
new file mode 100644
index 0000000000000..aedf2875dc452
--- /dev/null
+++ b/doc/source/getting_started/comparison/comparison_boilerplate.rst
@@ -0,0 +1,9 @@
+If you're new to pandas, you might want to first read through :ref:`10 Minutes to pandas<10min>`
+to familiarize yourself with the library.
+
+As is customary, we import pandas and NumPy as follows:
+
+.. ipython:: python
+
+ import pandas as pd
+ import numpy as np
diff --git a/doc/source/getting_started/comparison/comparison_with_sas.rst b/doc/source/getting_started/comparison/comparison_with_sas.rst
index ae9f1caebd556..c6f508aae0e21 100644
--- a/doc/source/getting_started/comparison/comparison_with_sas.rst
+++ b/doc/source/getting_started/comparison/comparison_with_sas.rst
@@ -8,16 +8,7 @@ For potential users coming from `SAS <https://en.wikipedia.org/wiki/SAS_(softwar
this page is meant to demonstrate how different SAS operations would be
performed in pandas.
-If you're new to pandas, you might want to first read through :ref:`10 Minutes to pandas<10min>`
-to familiarize yourself with the library.
-
-As is customary, we import pandas and NumPy as follows:
-
-.. ipython:: python
-
- import pandas as pd
- import numpy as np
-
+.. include:: comparison_boilerplate.rst
.. note::
@@ -48,14 +39,17 @@ General terminology translation
``NaN``, ``.``
-``DataFrame`` / ``Series``
-~~~~~~~~~~~~~~~~~~~~~~~~~~
+``DataFrame``
+~~~~~~~~~~~~~
A ``DataFrame`` in pandas is analogous to a SAS data set - a two-dimensional
data source with labeled columns that can be of different types. As will be
shown in this document, almost any operation that can be applied to a data set
using SAS's ``DATA`` step, can also be accomplished in pandas.
+``Series``
+~~~~~~~~~~
+
A ``Series`` is the data structure that represents one column of a
``DataFrame``. SAS doesn't have a separate data structure for a single column,
but in general, working with a ``Series`` is analogous to referencing a column
diff --git a/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst b/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst
new file mode 100644
index 0000000000000..73645d429cc66
--- /dev/null
+++ b/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst
@@ -0,0 +1,253 @@
+.. _compare_with_spreadsheets:
+
+{{ header }}
+
+Comparison with spreadsheets
+****************************
+
+Since many potential pandas users have some familiarity with spreadsheet programs like
+`Excel <https://support.microsoft.com/en-us/excel>`_, this page is meant to provide some examples
+of how various spreadsheet operations would be performed using pandas. This page will use
+terminology and link to documentation for Excel, but much will be the same/similar in
+`Google Sheets <https://support.google.com/a/users/answer/9282959>`_,
+`LibreOffice Calc <https://help.libreoffice.org/latest/en-US/text/scalc/main0000.html?DbPAR=CALC>`_,
+`Apple Numbers <https://www.apple.com/mac/numbers/compatibility/functions.html>`_, and other
+Excel-compatible spreadsheet software.
+
+.. include:: comparison_boilerplate.rst
+
+Data structures
+---------------
+
+General terminology translation
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. csv-table::
+ :header: "pandas", "Excel"
+ :widths: 20, 20
+
+ ``DataFrame``, worksheet
+ ``Series``, column
+ ``Index``, row headings
+ row, row
+ ``NaN``, empty cell
+
+``DataFrame``
+~~~~~~~~~~~~~
+
+A ``DataFrame`` in pandas is analogous to an Excel worksheet. While an Excel worksheet can contain
+multiple worksheets, pandas ``DataFrame``\s exist independently.
+
+``Series``
+~~~~~~~~~~
+
+A ``Series`` is the data structure that represents one column of a ``DataFrame``. Working with a
+``Series`` is analogous to referencing a column of a spreadsheet.
+
+``Index``
+~~~~~~~~~
+
+Every ``DataFrame`` and ``Series`` has an ``Index``, which are labels on the *rows* of the data. In
+pandas, if no index is specified, a :class:`~pandas.RangeIndex` is used by default (first row = 0,
+second row = 1, and so on), analogous to row headings/numbers in spreadsheets.
+
+In pandas, indexes can be set to one (or multiple) unique values, which is like having a column that
+use use as the row identifier in a worksheet. Unlike spreadsheets, these ``Index`` values can actually be
+used to reference the rows. For example, in spreadsheets, you would reference the first row as ``A1:Z1``,
+while in pandas you could use ``populations.loc['Chicago']``.
+
+Index values are also persistent, so if you re-order the rows in a ``DataFrame``, the label for a
+particular row don't change.
+
+See the :ref:`indexing documentation<indexing>` for much more on how to use an ``Index``
+effectively.
+
+Commonly used spreadsheet functionalities
+-----------------------------------------
+
+Importing data
+~~~~~~~~~~~~~~
+
+Both `Excel <https://support.microsoft.com/en-us/office/import-data-from-external-data-sources-power-query-be4330b3-5356-486c-a168-b68e9e616f5a>`__
+and :ref:`pandas <10min_tut_02_read_write>` can import data from various sources in various
+formats.
+
+Excel files
+'''''''''''
+
+Excel opens `various Excel file formats <https://support.microsoft.com/en-us/office/file-formats-that-are-supported-in-excel-0943ff2c-6014-4e8d-aaea-b83d51d46247>`_
+by double-clicking them, or using `the Open menu <https://support.microsoft.com/en-us/office/open-files-from-the-file-menu-97f087d8-3136-4485-8e86-c5b12a8c4176>`_.
+In pandas, you use :ref:`special methods for reading and writing from/to Excel files <io.excel>`.
+
+CSV
+'''
+
+Let's load and display the `tips <https://github.com/pandas-dev/pandas/blob/master/pandas/tests/io/data/csv/tips.csv>`_
+dataset from the pandas tests, which is a CSV file. In Excel, you would download and then
+`open the CSV <https://support.microsoft.com/en-us/office/import-or-export-text-txt-or-csv-files-5250ac4c-663c-47ce-937b-339e391393ba>`_.
+In pandas, you pass the URL or local path of the CSV file to :func:`~pandas.read_csv`:
+
+.. ipython:: python
+
+ url = (
+ "https://raw.github.com/pandas-dev"
+ "/pandas/master/pandas/tests/io/data/csv/tips.csv"
+ )
+ tips = pd.read_csv(url)
+ tips
+
+Fill Handle
+~~~~~~~~~~~
+
+Create a series of numbers following a set pattern in a certain set of cells. In
+a spreadsheet, this would be done by shift+drag after entering the first number or by
+entering the first two or three values and then dragging.
+
+This can be achieved by creating a series and assigning it to the desired cells.
+
+.. ipython:: python
+
+ df = pd.DataFrame({"AAA": [1] * 8, "BBB": list(range(0, 8))})
+ df
+
+ series = list(range(1, 5))
+ series
+
+ df.loc[2:5, "AAA"] = series
+
+ df
+
+Filters
+~~~~~~~
+
+Filters can be achieved by using slicing.
+
+The examples filter by 0 on column AAA, and also show how to filter by multiple
+values.
+
+.. ipython:: python
+
+ df[df.AAA == 0]
+
+ df[(df.AAA == 0) | (df.AAA == 2)]
+
+
+Drop Duplicates
+~~~~~~~~~~~~~~~
+
+Excel has built-in functionality for `removing duplicate values <https://support.microsoft.com/en-us/office/find-and-remove-duplicates-00e35bea-b46a-4d5d-b28e-66a552dc138d>`_.
+This is supported in pandas via :meth:`~DataFrame.drop_duplicates`.
+
+.. ipython:: python
+
+ df = pd.DataFrame(
+ {
+ "class": ["A", "A", "A", "B", "C", "D"],
+ "student_count": [42, 35, 42, 50, 47, 45],
+ "all_pass": ["Yes", "Yes", "Yes", "No", "No", "Yes"],
+ }
+ )
+
+ df.drop_duplicates()
+
+ df.drop_duplicates(["class", "student_count"])
+
+
+Pivot Tables
+~~~~~~~~~~~~
+
+`PivotTables <https://support.microsoft.com/en-us/office/create-a-pivottable-to-analyze-worksheet-data-a9a84538-bfe9-40a9-a8e9-f99134456576>`_
+from spreadsheets can be replicated in pandas through :ref:`reshaping`. Using the ``tips`` dataset again,
+let's find the average gratuity by size of the party and sex of the server.
+
+In Excel, we use the following configuration for the PivotTable:
+
+.. image:: ../../_static/excel_pivot.png
+ :align: center
+
+The equivalent in pandas:
+
+.. ipython:: python
+
+ pd.pivot_table(
+ tips, values="tip", index=["size"], columns=["sex"], aggfunc=np.average
+ )
+
+Formulas
+~~~~~~~~
+
+In spreadsheets, `formulas <https://support.microsoft.com/en-us/office/overview-of-formulas-in-excel-ecfdc708-9162-49e8-b993-c311f47ca173>`_
+are often created in individual cells and then `dragged <https://support.microsoft.com/en-us/office/copy-a-formula-by-dragging-the-fill-handle-in-excel-for-mac-dd928259-622b-473f-9a33-83aa1a63e218>`_
+into other cells to compute them for other columns. In pandas, you'll be doing more operations on
+full columns.
+
+As an example, let's create a new column "girls_count" and try to compute the number of boys in
+each class.
+
+.. ipython:: python
+
+ df["girls_count"] = [21, 12, 21, 31, 23, 17]
+ df
+ df["boys_count"] = df["student_count"] - df["girls_count"]
+ df
+
+Note that we aren't having to tell it to do that subtraction cell-by-cell — pandas handles that for
+us. See :ref:`how to create new columns derived from existing columns <10min_tut_05_columns>`.
+
+VLOOKUP
+~~~~~~~
+
+.. ipython:: python
+
+ import random
+
+ first_names = [
+ "harry",
+ "ron",
+ "hermione",
+ "rubius",
+ "albus",
+ "severus",
+ "luna",
+ ]
+ keys = [1, 2, 3, 4, 5, 6, 7]
+ df1 = pd.DataFrame({"keys": keys, "first_names": first_names})
+ df1
+
+ surnames = [
+ "hadrid",
+ "malfoy",
+ "lovegood",
+ "dumbledore",
+ "grindelwald",
+ "granger",
+ "weasly",
+ "riddle",
+ "longbottom",
+ "snape",
+ ]
+ keys = [random.randint(1, 7) for x in range(0, 10)]
+ random_names = pd.DataFrame({"surnames": surnames, "keys": keys})
+
+ random_names
+
+ random_names.merge(df1, on="keys", how="left")
+
+Adding a row
+~~~~~~~~~~~~
+
+To appended a row, we can just assign values to an index using :meth:`~DataFrame.loc`.
+
+NOTE: If the index already exists, the values in that index will be over written.
+
+.. ipython:: python
+
+ df1.loc[7] = [8, "tonks"]
+ df1
+
+
+Search and Replace
+~~~~~~~~~~~~~~~~~~
+
+The ``replace`` method that comes associated with the ``DataFrame`` object can perform
+this function. Please see `pandas.DataFrame.replace <https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html>`__ for examples.
diff --git a/doc/source/getting_started/comparison/comparison_with_sql.rst b/doc/source/getting_started/comparison/comparison_with_sql.rst
index 6848d8df2e46b..4fe7b7e96cf50 100644
--- a/doc/source/getting_started/comparison/comparison_with_sql.rst
+++ b/doc/source/getting_started/comparison/comparison_with_sql.rst
@@ -8,15 +8,7 @@ Since many potential pandas users have some familiarity with
`SQL <https://en.wikipedia.org/wiki/SQL>`_, this page is meant to provide some examples of how
various SQL operations would be performed using pandas.
-If you're new to pandas, you might want to first read through :ref:`10 Minutes to pandas<10min>`
-to familiarize yourself with the library.
-
-As is customary, we import pandas and NumPy as follows:
-
-.. ipython:: python
-
- import pandas as pd
- import numpy as np
+.. include:: comparison_boilerplate.rst
Most of the examples will utilize the ``tips`` dataset found within pandas tests. We'll read
the data into a DataFrame called ``tips`` and assume we have a database table of the same name and
diff --git a/doc/source/getting_started/comparison/comparison_with_stata.rst b/doc/source/getting_started/comparison/comparison_with_stata.rst
index 014506cc18327..b3ed9b1ba630f 100644
--- a/doc/source/getting_started/comparison/comparison_with_stata.rst
+++ b/doc/source/getting_started/comparison/comparison_with_stata.rst
@@ -8,17 +8,7 @@ For potential users coming from `Stata <https://en.wikipedia.org/wiki/Stata>`__
this page is meant to demonstrate how different Stata operations would be
performed in pandas.
-If you're new to pandas, you might want to first read through :ref:`10 Minutes to pandas<10min>`
-to familiarize yourself with the library.
-
-As is customary, we import pandas and NumPy as follows. This means that we can refer to the
-libraries as ``pd`` and ``np``, respectively, for the rest of the document.
-
-.. ipython:: python
-
- import pandas as pd
- import numpy as np
-
+.. include:: comparison_boilerplate.rst
.. note::
@@ -48,14 +38,17 @@ General terminology translation
``NaN``, ``.``
-``DataFrame`` / ``Series``
-~~~~~~~~~~~~~~~~~~~~~~~~~~
+``DataFrame``
+~~~~~~~~~~~~~
A ``DataFrame`` in pandas is analogous to a Stata data set -- a two-dimensional
data source with labeled columns that can be of different types. As will be
shown in this document, almost any operation that can be applied to a data set
in Stata can also be accomplished in pandas.
+``Series``
+~~~~~~~~~~
+
A ``Series`` is the data structure that represents one column of a
``DataFrame``. Stata doesn't have a separate data structure for a single column,
but in general, working with a ``Series`` is analogous to referencing a column
diff --git a/doc/source/getting_started/comparison/index.rst b/doc/source/getting_started/comparison/index.rst
index 998706ce0c639..c3f58ce1f3d6d 100644
--- a/doc/source/getting_started/comparison/index.rst
+++ b/doc/source/getting_started/comparison/index.rst
@@ -11,5 +11,6 @@ Comparison with other tools
comparison_with_r
comparison_with_sql
+ comparison_with_spreadsheets
comparison_with_sas
comparison_with_stata
diff --git a/doc/source/getting_started/index.rst b/doc/source/getting_started/index.rst
index 6f6eeada0cfed..de47bd5b72148 100644
--- a/doc/source/getting_started/index.rst
+++ b/doc/source/getting_started/index.rst
@@ -619,6 +619,22 @@ the pandas-equivalent operations compared to software you already know:
:ref:`Learn more <compare_with_stata>`
+.. raw:: html
+
+ </div>
+ </div>
+ </div>
+ <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12 d-flex">
+ <div class="card text-center intro-card shadow">
+ <img src="../_static/logo_excel.svg" class="card-img-top" alt="Excel logo" height="52">
+ <div class="card-body flex-fill">
+ <p class="card-text">Users of <a href="https://en.wikipedia.org/wiki/Microsoft_Excel">Excel</a>
+ or other spreadsheet programs will find that many of the concepts are transferrable to pandas.</p>
+
+.. container:: custom-button
+
+ :ref:`Learn more <compare_with_spreadsheets>`
+
.. raw:: html
</div>
diff --git a/doc/source/getting_started/intro_tutorials/05_add_columns.rst b/doc/source/getting_started/intro_tutorials/05_add_columns.rst
index a99c2c49585c5..6c7c6faf69114 100644
--- a/doc/source/getting_started/intro_tutorials/05_add_columns.rst
+++ b/doc/source/getting_started/intro_tutorials/05_add_columns.rst
@@ -107,11 +107,13 @@ values in each row*.
</li>
</ul>
-Also other mathematical operators (+, -, \*, /) or
-logical operators (<, >, =,…) work element wise. The latter was already
+Also other mathematical operators (``+``, ``-``, ``\*``, ``/``) or
+logical operators (``<``, ``>``, ``=``,…) work element wise. The latter was already
used in the :ref:`subset data tutorial <10min_tut_03_subset>` to filter
rows of a table using a conditional expression.
+If you need more advanced logic, you can use arbitrary Python code via :meth:`~DataFrame.apply`.
+
.. raw:: html
<ul class="task-bullet">
| - [x] closes https://github.com/pandas-dev/pandas/issues/22993
- [x] tests added / passed
- [ ] ~~passes `black pandas`~~
- [ ] ~~passes `git diff upstream/master -u -- "*.py" | flake8 --diff`~~
- [ ] ~~whatsnew entry~~
## Background
I teach [a class on pandas for public policy students](https://github.com/afeld/python-public-policy/blob/master/syllabus.md#readme), and for many of them, spreadsheets are the only point of reference they have for working with tabular data. It would be very helpful to have (official) document comparing the two to point them to.
This is my first contribution to pandas and first time using reStructuredText, so feedback welcome. Thanks in advance!
## TODOs
Making a running checklist to show what I've done already, and what else I plan to do. Hoping for some preliminary feedback (like is there still interest in having this page) before spending too much more time on it.
Happy to continue in this pull request until complete with all of them, or get this merged sooner than later and take care of the others in follow-up pull requests. Slight preference for the latter (some documentation being better than none, less to review at once, etc.), but open to whatever.
- [x] start with what @rotuna did in https://github.com/pandas-dev/pandas/pull/23042
- [x] add links to canonical Excel documentation, as [previously requested](https://github.com/pandas-dev/pandas/pull/23042#discussion_r224289676)
- [x] fix for CI
- [x] link from Getting Started pages
- [ ] incorporate structure from [SAS](https://pandas.pydata.org/pandas-docs/stable/getting_started/comparison/comparison_with_sas.html)/[STATA](https://pandas.pydata.org/pandas-docs/stable/getting_started/comparison/comparison_with_stata.html) comparison pages
- [x] Data structures
- [ ] Data input / output
- [x] Mention `read_excel()`
- [ ] Data operations
- [ ] String processing
- [ ] Merging
- [ ] Missing data
- [ ] GroupBy
- [ ] Other considerations
- [ ] convert examples to use [`tips` dataset](https://raw.github.com/pandas-dev/pandas/master/pandas/tests/io/data/csv/tips.csv)
- [ ] add info about charting
## Questions
- [x] Which whatsnew file should I add to?
- [x] I noticed that [`doc/source/_static` is in the `.gitignore`](https://github.com/pandas-dev/pandas/blob/54682234e3a3e89e246313bf8f9a53f98b199e7b/.gitignore#L113), but [there are files checked into that folder](https://github.com/pandas-dev/pandas/tree/master/doc/source/_static). Is that intentional? - https://github.com/pandas-dev/pandas/pull/38739
- [ ] Some of the comparison documentation refers to "columns", while other refer to "Series". Is there a preference, or can they be used interchangeably?
- [x] Since spreadsheet software is largely interchangeable/compatible, would it make sense to make the page more general as "Comparison to spreadsheets"?
- [ ] Thoughts about including [slightly more subjective content](https://colab.research.google.com/github/afeld/python-public-policy/blob/main/pandas_crash_course.ipynb#scrollTo=efp6dYYtL-Je), such as _why_ one might want to use spreadsheets vs. pandas? | https://api.github.com/repos/pandas-dev/pandas/pulls/38554 | 2020-12-18T05:22:13Z | 2020-12-28T16:52:14Z | 2020-12-28T16:52:14Z | 2020-12-30T21:40:47Z |
REF: helpers for sanitize_array | diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index a8ca457cdf2a7..248963ca3c859 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -508,11 +508,7 @@ def sanitize_array(
# the result that we want
elif subarr.ndim == 1:
- if index is not None:
-
- # a 1-element ndarray
- if len(subarr) != len(index) and len(subarr) == 1:
- subarr = subarr.repeat(len(index))
+ subarr = _maybe_repeat(subarr, index)
elif subarr.ndim > 1:
if isinstance(data, np.ndarray):
@@ -521,16 +517,7 @@ def sanitize_array(
subarr = com.asarray_tuplesafe(data, dtype=dtype)
if not (is_extension_array_dtype(subarr.dtype) or is_extension_array_dtype(dtype)):
- # This is to prevent mixed-type Series getting all casted to
- # NumPy string type, e.g. NaN --> '-1#IND'.
- if issubclass(subarr.dtype.type, str):
- # GH#16605
- # If not empty convert the data to dtype
- # GH#19853: If data is a scalar, subarr has already the result
- if not lib.is_scalar(data):
- if not np.all(isna(data)):
- data = np.array(data, dtype=dtype, copy=False)
- subarr = np.array(data, dtype=object, copy=copy)
+ subarr = _sanitize_str_dtypes(subarr, data, dtype, copy)
is_object_or_str_dtype = is_object_dtype(dtype) or is_string_dtype(dtype)
if is_object_dtype(subarr.dtype) and not is_object_or_str_dtype:
@@ -541,6 +528,37 @@ def sanitize_array(
return subarr
+def _sanitize_str_dtypes(
+ result: np.ndarray, data, dtype: Optional[DtypeObj], copy: bool
+) -> np.ndarray:
+ """
+ Ensure we have a dtype that is supported by pandas.
+ """
+
+ # This is to prevent mixed-type Series getting all casted to
+ # NumPy string type, e.g. NaN --> '-1#IND'.
+ if issubclass(result.dtype.type, str):
+ # GH#16605
+ # If not empty convert the data to dtype
+ # GH#19853: If data is a scalar, result has already the result
+ if not lib.is_scalar(data):
+ if not np.all(isna(data)):
+ data = np.array(data, dtype=dtype, copy=False)
+ result = np.array(data, dtype=object, copy=copy)
+ return result
+
+
+def _maybe_repeat(arr: ArrayLike, index: Optional[Index]) -> ArrayLike:
+ """
+ If we have a length-1 array and an index describing how long we expect
+ the result to be, repeat the array.
+ """
+ if index is not None:
+ if 1 == len(arr) != len(index):
+ arr = arr.repeat(len(index))
+ return arr
+
+
def _try_cast(arr, dtype: Optional[DtypeObj], copy: bool, raise_cast_failure: bool):
"""
Convert input to numpy ndarray and optionally cast to a given dtype.
| https://api.github.com/repos/pandas-dev/pandas/pulls/38553 | 2020-12-18T03:47:02Z | 2020-12-18T18:29:00Z | 2020-12-18T18:29:00Z | 2020-12-18T18:32:15Z | |
BUG: Index([date]).astype("category").astype(object) roundtrip | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index fbd2c2b5345fc..874ce40f36a9f 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -172,7 +172,8 @@ Categorical
^^^^^^^^^^^
- Bug in ``CategoricalIndex.reindex`` failed when ``Index`` passed with elements all in category (:issue:`28690`)
--
+- Bug where construcing a :class:`Categorical` from an object-dtype array of ``date`` objects did not round-trip correctly with ``astype`` (:issue:`38552`)
+
Datetimelike
^^^^^^^^^^^^
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 24cbbd9ec6ac9..002f36f7949e5 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -331,7 +331,7 @@ def __init__(
elif not isinstance(values, (ABCIndex, ABCSeries, ExtensionArray)):
# sanitize_array coerces np.nan to a string under certain versions
# of numpy
- values = maybe_infer_to_datetimelike(values, convert_dates=True)
+ values = maybe_infer_to_datetimelike(values)
if not isinstance(values, (np.ndarray, ExtensionArray)):
values = com.convert_to_list_like(values)
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py
index 25b5be2ccc918..59d4700874810 100644
--- a/pandas/tests/arrays/categorical/test_constructors.py
+++ b/pandas/tests/arrays/categorical/test_constructors.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+from datetime import date, datetime
import numpy as np
import pytest
@@ -346,6 +346,14 @@ def test_constructor_from_index_series_datetimetz(self):
result = Categorical(Series(idx))
tm.assert_index_equal(result.categories, idx)
+ def test_constructor_date_objects(self):
+ # we dont cast date objects to timestamps, matching Index constructor
+ v = date.today()
+
+ cat = Categorical([v, v])
+ assert cat.categories.dtype == object
+ assert type(cat.categories[0]) is date
+
def test_constructor_from_index_series_timedelta(self):
idx = timedelta_range("1 days", freq="D", periods=3)
idx = idx._with_freq(None) # freq not preserved in result.categories
diff --git a/pandas/tests/indexes/categorical/test_astype.py b/pandas/tests/indexes/categorical/test_astype.py
index 44c4bcc951194..48a90652a2c06 100644
--- a/pandas/tests/indexes/categorical/test_astype.py
+++ b/pandas/tests/indexes/categorical/test_astype.py
@@ -1,3 +1,5 @@
+from datetime import date
+
import numpy as np
import pytest
@@ -64,3 +66,16 @@ def test_astype_category(self, name, dtype_ordered, index_ordered):
result = index.astype("category")
expected = index
tm.assert_index_equal(result, expected)
+
+ def test_categorical_date_roundtrip(self):
+ # astype to categorical and back should preserve date objects
+ v = date.today()
+
+ obj = Index([v, v])
+ assert obj.dtype == object
+
+ cat = obj.astype("category")
+
+ rtrip = cat.astype(object)
+ assert rtrip.dtype == object
+ assert type(rtrip[0]) is date
diff --git a/pandas/tests/indexes/multi/test_constructors.py b/pandas/tests/indexes/multi/test_constructors.py
index ca6387938d747..7666e9670e6a6 100644
--- a/pandas/tests/indexes/multi/test_constructors.py
+++ b/pandas/tests/indexes/multi/test_constructors.py
@@ -774,7 +774,7 @@ def test_datetimeindex():
# from datetime combos
# GH 7888
- date1 = date.today()
+ date1 = np.datetime64("today")
date2 = datetime.today()
date3 = Timestamp.today()
@@ -783,6 +783,12 @@ def test_datetimeindex():
assert isinstance(index.levels[0], pd.DatetimeIndex)
assert isinstance(index.levels[1], pd.DatetimeIndex)
+ # but NOT date objects, matching Index behavior
+ date4 = date.today()
+ index = MultiIndex.from_product([[date4], [date2]])
+ assert not isinstance(index.levels[0], pd.DatetimeIndex)
+ assert isinstance(index.levels[1], pd.DatetimeIndex)
+
def test_constructor_with_tz():
@@ -804,3 +810,26 @@ def test_constructor_with_tz():
assert result.names == ["dt1", "dt2"]
tm.assert_index_equal(result.levels[0], index)
tm.assert_index_equal(result.levels[1], columns)
+
+
+def test_multiindex_inference_consistency():
+ # check that inference behavior matches the base class
+
+ v = date.today()
+
+ arr = [v, v]
+
+ idx = Index(arr)
+ assert idx.dtype == object
+
+ mi = MultiIndex.from_arrays([arr])
+ lev = mi.levels[0]
+ assert lev.dtype == object
+
+ mi = MultiIndex.from_product([arr])
+ lev = mi.levels[0]
+ assert lev.dtype == object
+
+ mi = MultiIndex.from_tuples([(x,) for x in arr])
+ lev = mi.levels[0]
+ assert lev.dtype == object
diff --git a/pandas/tests/reshape/concat/test_datetimes.py b/pandas/tests/reshape/concat/test_datetimes.py
index 44a5e7f806309..92181e7dffc50 100644
--- a/pandas/tests/reshape/concat/test_datetimes.py
+++ b/pandas/tests/reshape/concat/test_datetimes.py
@@ -130,12 +130,17 @@ def test_concat_datetimeindex_freq(self):
def test_concat_multiindex_datetime_object_index(self):
# https://github.com/pandas-dev/pandas/issues/11058
+ idx = Index(
+ [dt.date(2013, 1, 1), dt.date(2014, 1, 1), dt.date(2015, 1, 1)],
+ dtype="object",
+ )
+
s = Series(
["a", "b"],
index=MultiIndex.from_arrays(
[
[1, 2],
- Index([dt.date(2013, 1, 1), dt.date(2014, 1, 1)], dtype="object"),
+ idx[:-1],
],
names=["first", "second"],
),
@@ -143,26 +148,19 @@ def test_concat_multiindex_datetime_object_index(self):
s2 = Series(
["a", "b"],
index=MultiIndex.from_arrays(
- [
- [1, 2],
- Index([dt.date(2013, 1, 1), dt.date(2015, 1, 1)], dtype="object"),
- ],
+ [[1, 2], idx[::2]],
names=["first", "second"],
),
)
+ mi = MultiIndex.from_arrays(
+ [[1, 2, 2], idx],
+ names=["first", "second"],
+ )
+ assert mi.levels[1].dtype == object
+
expected = DataFrame(
[["a", "a"], ["b", np.nan], [np.nan, "b"]],
- index=MultiIndex.from_arrays(
- [
- [1, 2, 2],
- DatetimeIndex(
- ["2013-01-01", "2014-01-01", "2015-01-01"],
- dtype="datetime64[ns]",
- freq=None,
- ),
- ],
- names=["first", "second"],
- ),
+ index=mi,
)
result = concat([s, s2], axis=1)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 73d94f4e5a432..d430856776269 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -1811,9 +1811,9 @@ def test_dtype_on_categorical_dates(self):
expected_outer = DataFrame(
[
- [pd.Timestamp("2001-01-01"), 1.1, 1.3],
- [pd.Timestamp("2001-01-02"), 1.3, np.nan],
- [pd.Timestamp("2001-01-03"), np.nan, 1.4],
+ [pd.Timestamp("2001-01-01").date(), 1.1, 1.3],
+ [pd.Timestamp("2001-01-02").date(), 1.3, np.nan],
+ [pd.Timestamp("2001-01-03").date(), np.nan, 1.4],
],
columns=["date", "num2", "num4"],
)
@@ -1821,7 +1821,8 @@ def test_dtype_on_categorical_dates(self):
tm.assert_frame_equal(result_outer, expected_outer)
expected_inner = DataFrame(
- [[pd.Timestamp("2001-01-01"), 1.1, 1.3]], columns=["date", "num2", "num4"]
+ [[pd.Timestamp("2001-01-01").date(), 1.1, 1.3]],
+ columns=["date", "num2", "num4"],
)
result_inner = pd.merge(df, df2, how="inner", on=["date"])
tm.assert_frame_equal(result_inner, expected_inner)
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
This also makes some MultiIndex constructor behavior consistent with Index behavior, with the side-effect of fixing the thorny cases in #36131 | https://api.github.com/repos/pandas-dev/pandas/pulls/38552 | 2020-12-18T00:53:45Z | 2020-12-23T14:17:46Z | 2020-12-23T14:17:46Z | 2020-12-23T15:52:12Z |
ENH: Map pandas integer to optimal SQLAlchemy integer type (GH35076) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index c3d896166fabe..c7573ee860744 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -44,6 +44,7 @@ Other enhancements
- Improve error message when ``usecols`` and ``names`` do not match for :func:`read_csv` and ``engine="c"`` (:issue:`29042`)
- Improved consistency of error message when passing an invalid ``win_type`` argument in :class:`Window` (:issue:`15969`)
- :func:`pandas.read_sql_query` now accepts a ``dtype`` argument to cast the columnar data from the SQL database based on user input (:issue:`10285`)
+- Improved integer type mapping from pandas to SQLAlchemy when using :meth:`DataFrame.to_sql` (:issue:`35076`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 0ad9140f2a757..d4aab05b22adf 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -1124,6 +1124,7 @@ def _sqlalchemy_type(self, col):
DateTime,
Float,
Integer,
+ SmallInteger,
Text,
Time,
)
@@ -1154,8 +1155,13 @@ def _sqlalchemy_type(self, col):
else:
return Float(precision=53)
elif col_type == "integer":
- if col.dtype == "int32":
+ # GH35076 Map pandas integer to optimal SQLAlchemy integer type
+ if col.dtype.name.lower() in ("int8", "uint8", "int16"):
+ return SmallInteger
+ elif col.dtype.name.lower() in ("uint16", "int32"):
return Integer
+ elif col.dtype.name.lower() == "uint64":
+ raise ValueError("Unsigned 64 bit integer datatype is not supported")
else:
return BigInteger
elif col_type == "boolean":
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index fdd42ec0cc5ab..df0815fc52bba 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -1160,6 +1160,45 @@ def test_sqlalchemy_type_mapping(self):
# GH 9086: TIMESTAMP is the suggested type for datetimes with timezones
assert isinstance(table.table.c["time"].type, sqltypes.TIMESTAMP)
+ @pytest.mark.parametrize(
+ "integer, expected",
+ [
+ ("int8", "SMALLINT"),
+ ("Int8", "SMALLINT"),
+ ("uint8", "SMALLINT"),
+ ("UInt8", "SMALLINT"),
+ ("int16", "SMALLINT"),
+ ("Int16", "SMALLINT"),
+ ("uint16", "INTEGER"),
+ ("UInt16", "INTEGER"),
+ ("int32", "INTEGER"),
+ ("Int32", "INTEGER"),
+ ("uint32", "BIGINT"),
+ ("UInt32", "BIGINT"),
+ ("int64", "BIGINT"),
+ ("Int64", "BIGINT"),
+ (int, "BIGINT" if np.dtype(int).name == "int64" else "INTEGER"),
+ ],
+ )
+ def test_sqlalchemy_integer_mapping(self, integer, expected):
+ # GH35076 Map pandas integer to optimal SQLAlchemy integer type
+ df = DataFrame([0, 1], columns=["a"], dtype=integer)
+ db = sql.SQLDatabase(self.conn)
+ table = sql.SQLTable("test_type", db, frame=df)
+
+ result = str(table.table.c.a.type)
+ assert result == expected
+
+ @pytest.mark.parametrize("integer", ["uint64", "UInt64"])
+ def test_sqlalchemy_integer_overload_mapping(self, integer):
+ # GH35076 Map pandas integer to optimal SQLAlchemy integer type
+ df = DataFrame([0, 1], columns=["a"], dtype=integer)
+ db = sql.SQLDatabase(self.conn)
+ with pytest.raises(
+ ValueError, match="Unsigned 64 bit integer datatype is not supported"
+ ):
+ sql.SQLTable("test_type", db, frame=df)
+
def test_database_uri_string(self):
# Test read_sql and .to_sql method with a database URI (GH10654)
| - [x] closes #35076
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38548 | 2020-12-17T20:38:54Z | 2020-12-24T18:51:42Z | 2020-12-24T18:51:42Z | 2020-12-24T18:51:51Z |
patch wsl compatibility | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 990c87eab5a8d..44d97fffe1731 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -240,6 +240,7 @@ I/O
- Bug in :func:`read_csv` raising ``IndexError`` with multiple header columns and ``index_col`` specified when file has no data rows (:issue:`38292`)
- Bug in :func:`read_csv` not accepting ``usecols`` with different length than ``names`` for ``engine="python"`` (:issue:`16469`)
- Bug in :func:`read_csv` raising ``TypeError`` when ``names`` and ``parse_dates`` is specified for ``engine="c"`` (:issue:`33699`)
+- Bug in :func:`read_clipboard`, :func:`DataFrame.to_clipboard` not working in WSL (:issue:`38527`)
- Allow custom error values for parse_dates argument of :func:`read_sql`, :func:`read_sql_query` and :func:`read_sql_table` (:issue:`35185`)
-
diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py
index a8020f4bb4e4f..2d253d93295dd 100644
--- a/pandas/io/clipboard/__init__.py
+++ b/pandas/io/clipboard/__init__.py
@@ -45,6 +45,7 @@
import contextlib
import ctypes
from ctypes import c_size_t, c_wchar, c_wchar_p, get_errno, sizeof
+import distutils.spawn
import os
import platform
import subprocess
@@ -521,9 +522,8 @@ def determine_clipboard():
return init_windows_clipboard()
if platform.system() == "Linux":
- with open("/proc/version") as f:
- if "Microsoft" in f.read():
- return init_wsl_clipboard()
+ if distutils.spawn.find_executable("wslconfig.exe"):
+ return init_wsl_clipboard()
# Setup for the MAC OS X platform:
if os.name == "mac" or platform.system() == "Darwin":
| Change wsl check to something more universal and consistent
- [x] closes #38527
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38546 | 2020-12-17T17:52:56Z | 2020-12-23T14:08:08Z | 2020-12-23T14:08:08Z | 2020-12-23T14:08:11Z |
BENCH: Increase sample of CategoricalIndexIndexing.time_get_indexer_list benchmark | diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py
index 38d1f64bd5f4e..e95e5bec5849c 100644
--- a/asv_bench/benchmarks/indexing.py
+++ b/asv_bench/benchmarks/indexing.py
@@ -3,6 +3,7 @@
lower-level methods directly on Index and subclasses, see index_object.py,
indexing_engine.py, and index_cached.py
"""
+import itertools
import string
import warnings
@@ -256,7 +257,9 @@ def setup(self, index):
"non_monotonic": CategoricalIndex(list("abc" * N)),
}
self.data = indices[index]
- self.data_unique = CategoricalIndex(list(string.printable))
+ self.data_unique = CategoricalIndex(
+ ["".join(perm) for perm in itertools.permutations(string.printable, 3)]
+ )
self.int_scalar = 10000
self.int_list = list(range(10000))
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
xref https://github.com/pandas-dev/pandas/pull/38476#discussion_r543329205 | https://api.github.com/repos/pandas-dev/pandas/pulls/38545 | 2020-12-17T17:30:47Z | 2020-12-17T22:45:03Z | 2020-12-17T22:45:03Z | 2020-12-17T23:17:29Z |
DEPR: datetimelike.astype(int) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 65bfd8289fe3d..0c86d1da55233 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -145,6 +145,7 @@ Other API changes
Deprecations
~~~~~~~~~~~~
- Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`,:issue:`21311`,:issue:`22315`,:issue:`26974`)
+- Deprecated ``astype`` of datetimelike (``timedelta64[ns]``, ``datetime64[ns]``, ``Datetime64TZDtype``, ``PeriodDtype``) to integer dtypes, use ``values.view(...)`` instead (:issue:`38544`)
-
-
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 79ecf8620c70c..a25bc590f4d83 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -352,6 +352,14 @@ def astype(self, dtype, copy=True):
elif is_integer_dtype(dtype):
# we deliberately ignore int32 vs. int64 here.
# See https://github.com/pandas-dev/pandas/issues/24381 for more.
+ warnings.warn(
+ f"casting {self.dtype} values to int64 with .astype(...) is "
+ "deprecated and will raise in a future version. "
+ "Use .view(...) instead.",
+ FutureWarning,
+ stacklevel=3,
+ )
+
values = self.asi8
if is_unsigned_integer_dtype(dtype):
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index d1c16de05ce55..1c6e378d07e20 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1,7 +1,6 @@
"""
Routines for casting.
"""
-
from contextlib import suppress
from datetime import datetime, timedelta
from typing import (
@@ -17,6 +16,7 @@
Type,
Union,
)
+import warnings
import numpy as np
@@ -997,6 +997,14 @@ def astype_nansafe(
elif is_datetime64_dtype(arr):
if dtype == np.int64:
+ warnings.warn(
+ f"casting {arr.dtype} values to int64 with .astype(...) "
+ "is deprecated and will raise in a future version. "
+ "Use .view(...) instead.",
+ FutureWarning,
+ # stacklevel chosen to be correct when reached via Series.astype
+ stacklevel=7,
+ )
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
return arr.view(dtype)
@@ -1009,6 +1017,14 @@ def astype_nansafe(
elif is_timedelta64_dtype(arr):
if dtype == np.int64:
+ warnings.warn(
+ f"casting {arr.dtype} values to int64 with .astype(...) "
+ "is deprecated and will raise in a future version. "
+ "Use .view(...) instead.",
+ FutureWarning,
+ # stacklevel chosen to be correct when reached via Series.astype
+ stacklevel=7,
+ )
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
return arr.view(dtype)
diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py
index c8db0157ba219..52f71f8c8f505 100644
--- a/pandas/tests/arrays/test_datetimes.py
+++ b/pandas/tests/arrays/test_datetimes.py
@@ -184,13 +184,18 @@ def test_astype_copies(self, dtype, other):
@pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])
def test_astype_int(self, dtype):
arr = DatetimeArray._from_sequence([pd.Timestamp("2000"), pd.Timestamp("2001")])
- result = arr.astype(dtype)
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ result = arr.astype(dtype)
if np.dtype(dtype).kind == "u":
expected_dtype = np.dtype("uint64")
else:
expected_dtype = np.dtype("int64")
- expected = arr.astype(expected_dtype)
+
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ expected = arr.astype(expected_dtype)
assert result.dtype == expected_dtype
tm.assert_numpy_array_equal(result, expected)
diff --git a/pandas/tests/arrays/test_period.py b/pandas/tests/arrays/test_period.py
index f96a15d5b2e7c..8fca2a6d83393 100644
--- a/pandas/tests/arrays/test_period.py
+++ b/pandas/tests/arrays/test_period.py
@@ -123,13 +123,18 @@ def test_astype(dtype):
# We choose to ignore the sign and size of integers for
# Period/Datetime/Timedelta astype
arr = period_array(["2000", "2001", None], freq="D")
- result = arr.astype(dtype)
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ result = arr.astype(dtype)
if np.dtype(dtype).kind == "u":
expected_dtype = np.dtype("uint64")
else:
expected_dtype = np.dtype("int64")
- expected = arr.astype(expected_dtype)
+
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ expected = arr.astype(expected_dtype)
assert result.dtype == expected_dtype
tm.assert_numpy_array_equal(result, expected)
@@ -137,12 +142,17 @@ def test_astype(dtype):
def test_astype_copies():
arr = period_array(["2000", "2001", None], freq="D")
- result = arr.astype(np.int64, copy=False)
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ result = arr.astype(np.int64, copy=False)
+
# Add the `.base`, since we now use `.asi8` which returns a view.
# We could maybe override it in PeriodArray to return ._data directly.
assert result.base is arr._data
- result = arr.astype(np.int64, copy=True)
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ result = arr.astype(np.int64, copy=True)
assert result is not arr._data
tm.assert_numpy_array_equal(result, arr._data.view("i8"))
diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py
index c0567209ff91b..9d9ca41779b5a 100644
--- a/pandas/tests/arrays/test_timedeltas.py
+++ b/pandas/tests/arrays/test_timedeltas.py
@@ -82,13 +82,18 @@ def test_from_sequence_dtype(self):
@pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])
def test_astype_int(self, dtype):
arr = TimedeltaArray._from_sequence([Timedelta("1H"), Timedelta("2H")])
- result = arr.astype(dtype)
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ result = arr.astype(dtype)
if np.dtype(dtype).kind == "u":
expected_dtype = np.dtype("uint64")
else:
expected_dtype = np.dtype("int64")
- expected = arr.astype(expected_dtype)
+
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ expected = arr.astype(expected_dtype)
assert result.dtype == expected_dtype
tm.assert_numpy_array_equal(result, expected)
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py
index 9e75ba0864e76..54bac7deded6c 100644
--- a/pandas/tests/dtypes/test_common.py
+++ b/pandas/tests/dtypes/test_common.py
@@ -719,7 +719,9 @@ def test_astype_nansafe(val, typ):
msg = "Cannot convert NaT values to integer"
with pytest.raises(ValueError, match=msg):
- astype_nansafe(arr, dtype=typ)
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ # datetimelike astype(int64) deprecated
+ astype_nansafe(arr, dtype=typ)
@pytest.mark.parametrize("from_type", [np.datetime64, np.timedelta64])
diff --git a/pandas/tests/indexes/datetimes/methods/test_astype.py b/pandas/tests/indexes/datetimes/methods/test_astype.py
index 2f22236d55ff3..98d5e074091de 100644
--- a/pandas/tests/indexes/datetimes/methods/test_astype.py
+++ b/pandas/tests/indexes/datetimes/methods/test_astype.py
@@ -29,7 +29,8 @@ def test_astype(self):
)
tm.assert_index_equal(result, expected)
- result = idx.astype(int)
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ result = idx.astype(int)
expected = Int64Index(
[1463356800000000000] + [-9223372036854775808] * 3,
dtype=np.int64,
@@ -38,7 +39,8 @@ def test_astype(self):
tm.assert_index_equal(result, expected)
rng = date_range("1/1/2000", periods=10, name="idx")
- result = rng.astype("i8")
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ result = rng.astype("i8")
tm.assert_index_equal(result, Index(rng.asi8, name="idx"))
tm.assert_numpy_array_equal(result.values, rng.asi8)
@@ -48,9 +50,9 @@ def test_astype_uint(self):
np.array([946684800000000000, 946771200000000000], dtype="uint64"),
name="idx",
)
-
- tm.assert_index_equal(arr.astype("uint64"), expected)
- tm.assert_index_equal(arr.astype("uint32"), expected)
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ tm.assert_index_equal(arr.astype("uint64"), expected)
+ tm.assert_index_equal(arr.astype("uint32"), expected)
def test_astype_with_tz(self):
diff --git a/pandas/tests/indexes/interval/test_astype.py b/pandas/tests/indexes/interval/test_astype.py
index b4af1cb5859f0..34ce810e32273 100644
--- a/pandas/tests/indexes/interval/test_astype.py
+++ b/pandas/tests/indexes/interval/test_astype.py
@@ -197,10 +197,13 @@ def index(self, request):
@pytest.mark.parametrize("subtype", ["int64", "uint64"])
def test_subtype_integer(self, index, subtype):
dtype = IntervalDtype(subtype)
- result = index.astype(dtype)
- expected = IntervalIndex.from_arrays(
- index.left.astype(subtype), index.right.astype(subtype), closed=index.closed
- )
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ result = index.astype(dtype)
+ expected = IntervalIndex.from_arrays(
+ index.left.astype(subtype),
+ index.right.astype(subtype),
+ closed=index.closed,
+ )
tm.assert_index_equal(result, expected)
def test_subtype_float(self, index):
diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py
index 6182df8429e8b..409b9419cc464 100644
--- a/pandas/tests/indexes/interval/test_constructors.py
+++ b/pandas/tests/indexes/interval/test_constructors.py
@@ -72,13 +72,21 @@ def test_constructor(self, constructor, breaks, closed, name):
)
def test_constructor_dtype(self, constructor, breaks, subtype):
# GH 19262: conversion via dtype parameter
- expected_kwargs = self.get_kwargs_from_breaks(breaks.astype(subtype))
+ warn = None
+ if subtype == "int64" and breaks.dtype.kind in ["M", "m"]:
+ # astype(int64) deprecated
+ warn = FutureWarning
+
+ with tm.assert_produces_warning(warn, check_stacklevel=False):
+ expected_kwargs = self.get_kwargs_from_breaks(breaks.astype(subtype))
expected = constructor(**expected_kwargs)
result_kwargs = self.get_kwargs_from_breaks(breaks)
iv_dtype = IntervalDtype(subtype)
for dtype in (iv_dtype, str(iv_dtype)):
- result = constructor(dtype=dtype, **result_kwargs)
+ with tm.assert_produces_warning(warn, check_stacklevel=False):
+
+ result = constructor(dtype=dtype, **result_kwargs)
tm.assert_index_equal(result, expected)
@pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning")
diff --git a/pandas/tests/indexes/period/methods/test_astype.py b/pandas/tests/indexes/period/methods/test_astype.py
index 674d09c6a7a8c..943b2605363c7 100644
--- a/pandas/tests/indexes/period/methods/test_astype.py
+++ b/pandas/tests/indexes/period/methods/test_astype.py
@@ -37,7 +37,8 @@ def test_astype_conversion(self):
)
tm.assert_index_equal(result, expected)
- result = idx.astype(np.int64)
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ result = idx.astype(np.int64)
expected = Int64Index(
[16937] + [-9223372036854775808] * 3, dtype=np.int64, name="idx"
)
@@ -48,15 +49,17 @@ def test_astype_conversion(self):
tm.assert_index_equal(result, expected)
idx = period_range("1990", "2009", freq="A", name="idx")
- result = idx.astype("i8")
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ result = idx.astype("i8")
tm.assert_index_equal(result, Index(idx.asi8, name="idx"))
tm.assert_numpy_array_equal(result.values, idx.asi8)
def test_astype_uint(self):
arr = period_range("2000", periods=2, name="idx")
expected = UInt64Index(np.array([10957, 10958], dtype="uint64"), name="idx")
- tm.assert_index_equal(arr.astype("uint64"), expected)
- tm.assert_index_equal(arr.astype("uint32"), expected)
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ tm.assert_index_equal(arr.astype("uint64"), expected)
+ tm.assert_index_equal(arr.astype("uint32"), expected)
def test_astype_object(self):
idx = PeriodIndex([], freq="M")
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index 4bd4c9f4d10fc..dce2e0172556a 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -341,9 +341,14 @@ def test_astype_preserves_name(self, index, dtype):
else:
index.name = "idx"
+ warn = None
+ if dtype in ["int64", "uint64"]:
+ if needs_i8_conversion(index.dtype):
+ warn = FutureWarning
try:
# Some of these conversions cannot succeed so we use a try / except
- result = index.astype(dtype)
+ with tm.assert_produces_warning(warn, check_stacklevel=False):
+ result = index.astype(dtype)
except (ValueError, TypeError, NotImplementedError, SystemError):
return
diff --git a/pandas/tests/indexes/timedeltas/methods/test_astype.py b/pandas/tests/indexes/timedeltas/methods/test_astype.py
index 6f82e77faca7a..a849ffa98324c 100644
--- a/pandas/tests/indexes/timedeltas/methods/test_astype.py
+++ b/pandas/tests/indexes/timedeltas/methods/test_astype.py
@@ -55,7 +55,8 @@ def test_astype(self):
)
tm.assert_index_equal(result, expected)
- result = idx.astype(int)
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ result = idx.astype(int)
expected = Int64Index(
[100000000000000] + [-9223372036854775808] * 3, dtype=np.int64, name="idx"
)
@@ -66,7 +67,8 @@ def test_astype(self):
tm.assert_index_equal(result, expected)
rng = timedelta_range("1 days", periods=10)
- result = rng.astype("i8")
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ result = rng.astype("i8")
tm.assert_index_equal(result, Index(rng.asi8))
tm.assert_numpy_array_equal(rng.asi8, result.values)
@@ -75,9 +77,9 @@ def test_astype_uint(self):
expected = pd.UInt64Index(
np.array([3600000000000, 90000000000000], dtype="uint64")
)
-
- tm.assert_index_equal(arr.astype("uint64"), expected)
- tm.assert_index_equal(arr.astype("uint32"), expected)
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ tm.assert_index_equal(arr.astype("uint64"), expected)
+ tm.assert_index_equal(arr.astype("uint32"), expected)
def test_astype_timedelta64(self):
# GH 13149, GH 13209
diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index d7580e9f8610e..9b032da1f20ea 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -454,6 +454,9 @@ def test_astype(self, t):
# coerce all
mgr = create_mgr("c: f4; d: f2; e: f8")
+ warn = FutureWarning if t == "int64" else None
+ # datetimelike.astype(int64) deprecated
+
t = np.dtype(t)
tmgr = mgr.astype(t)
assert tmgr.iget(0).dtype.type == t
@@ -464,7 +467,8 @@ def test_astype(self, t):
mgr = create_mgr("a,b: object; c: bool; d: datetime; e: f4; f: f2; g: f8")
t = np.dtype(t)
- tmgr = mgr.astype(t, errors="ignore")
+ with tm.assert_produces_warning(warn):
+ tmgr = mgr.astype(t, errors="ignore")
assert tmgr.iget(2).dtype.type == t
assert tmgr.iget(4).dtype.type == t
assert tmgr.iget(5).dtype.type == t
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 5b13091470b09..eabd6a1eb0743 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -785,7 +785,7 @@ def test_constructor_dtype_datetime64(self):
dtype="datetime64[ns]",
)
- result = Series(Series(dates).astype(np.int64) / 1000000, dtype="M8[ms]")
+ result = Series(Series(dates).view(np.int64) / 1000000, dtype="M8[ms]")
tm.assert_series_equal(result, expected)
result = Series(dates, dtype="datetime64[ns]")
@@ -800,7 +800,9 @@ def test_constructor_dtype_datetime64(self):
dts = Series(dates, dtype="datetime64[ns]")
# valid astype
- dts.astype("int64")
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ # astype(np.int64) deprecated
+ dts.astype("int64")
# invalid casting
msg = r"cannot astype a datetimelike from \[datetime64\[ns\]\] to \[int32\]"
@@ -810,8 +812,10 @@ def test_constructor_dtype_datetime64(self):
# ints are ok
# we test with np.int64 to get similar results on
# windows / 32-bit platforms
- result = Series(dts, dtype=np.int64)
- expected = Series(dts.astype(np.int64))
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ # astype(np.int64) deprecated
+ result = Series(dts, dtype=np.int64)
+ expected = Series(dts.astype(np.int64))
tm.assert_series_equal(result, expected)
# invalid dates can be help as object
@@ -1287,13 +1291,16 @@ def test_constructor_dtype_timedelta64(self):
td = Series([np.timedelta64(1, "s")])
assert td.dtype == "timedelta64[ns]"
+ # FIXME: dont leave commented-out
# these are frequency conversion astypes
# for t in ['s', 'D', 'us', 'ms']:
# with pytest.raises(TypeError):
# td.astype('m8[%s]' % t)
# valid astype
- td.astype("int64")
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int64) deprecated
+ td.astype("int64")
# invalid casting
msg = r"cannot astype a timedelta from \[timedelta64\[ns\]\] to \[int32\]"
@@ -1410,8 +1417,10 @@ def test_constructor_cant_cast_datetimelike(self, index):
# ints are ok
# we test with np.int64 to get similar results on
# windows / 32-bit platforms
- result = Series(index, dtype=np.int64)
- expected = Series(index.astype(np.int64))
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ # asype(np.int64) deprecated, use .view(np.int64) instead
+ result = Series(index, dtype=np.int64)
+ expected = Series(index.astype(np.int64))
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
| - [x] closes #24381
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Sits on top of #38535 | https://api.github.com/repos/pandas-dev/pandas/pulls/38544 | 2020-12-17T16:50:42Z | 2020-12-23T19:24:36Z | 2020-12-23T19:24:36Z | 2021-09-16T15:35:51Z |
BUG: fix array conversion from Arrow for slided array | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index e2521cedb64cc..4816e45861f4c 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -747,6 +747,7 @@ I/O
- :meth:`DataFrame.to_html` was ignoring ``formatters`` argument for ``ExtensionDtype`` columns (:issue:`36525`)
- Bumped minimum xarray version to 0.12.3 to avoid reference to the removed ``Panel`` class (:issue:`27101`)
- :meth:`DataFrame.to_csv` was re-opening file-like handles that also implement ``os.PathLike`` (:issue:`38125`)
+- Bug in the conversion of a sliced ``pyarrow.Table`` with missing values to a DataFrame (:issue:`38525`)
Period
^^^^^^
diff --git a/pandas/core/arrays/_arrow_utils.py b/pandas/core/arrays/_arrow_utils.py
index c89f5554d0715..959a13d9c107d 100644
--- a/pandas/core/arrays/_arrow_utils.py
+++ b/pandas/core/arrays/_arrow_utils.py
@@ -30,7 +30,7 @@ def pyarrow_array_to_numpy_and_mask(arr, dtype):
bitmask = buflist[0]
if bitmask is not None:
mask = pyarrow.BooleanArray.from_buffers(
- pyarrow.bool_(), len(arr), [None, bitmask]
+ pyarrow.bool_(), len(arr), [None, bitmask], offset=arr.offset
)
mask = np.asarray(mask)
else:
diff --git a/pandas/tests/arrays/masked/test_arrow_compat.py b/pandas/tests/arrays/masked/test_arrow_compat.py
index ca6fb1cf9dca0..8bb32dec2cc0e 100644
--- a/pandas/tests/arrays/masked/test_arrow_compat.py
+++ b/pandas/tests/arrays/masked/test_arrow_compat.py
@@ -52,3 +52,15 @@ def test_arrow_from_arrow_uint():
expected = pd.array([1, 2, 3, 4, None], dtype="UInt32")
tm.assert_extension_array_equal(result, expected)
+
+
+@td.skip_if_no("pyarrow", min_version="0.16.0")
+def test_arrow_sliced():
+ # https://github.com/pandas-dev/pandas/issues/38525
+ import pyarrow as pa
+
+ df = pd.DataFrame({"a": pd.array([0, None, 2, 3, None], dtype="Int64")})
+ table = pa.table(df)
+ result = table.slice(2, None).to_pandas()
+ expected = df.iloc[2:].reset_index(drop=True)
+ tm.assert_frame_equal(result, expected)
| Closes #38525 | https://api.github.com/repos/pandas-dev/pandas/pulls/38539 | 2020-12-17T11:26:21Z | 2020-12-21T13:54:38Z | 2020-12-21T13:54:38Z | 2020-12-21T13:58:38Z |
TYP: pandas/io/sql.py (easy: bool/str) | diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 23f992ceb009a..836c16c109b57 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -7,7 +7,7 @@
from datetime import date, datetime, time
from functools import partial
import re
-from typing import Iterator, List, Optional, Union, overload
+from typing import Any, Dict, Iterator, List, Optional, Sequence, Union, overload
import warnings
import numpy as np
@@ -77,7 +77,9 @@ def _process_parse_dates_argument(parse_dates):
return parse_dates
-def _handle_date_column(col, utc=None, format=None):
+def _handle_date_column(
+ col, utc: Optional[bool] = None, format: Optional[Union[str, Dict[str, Any]]] = None
+):
if isinstance(format, dict):
# GH35185 Allow custom error values in parse_dates argument of
# read_sql like functions.
@@ -124,7 +126,13 @@ def _parse_date_columns(data_frame, parse_dates):
return data_frame
-def _wrap_result(data, columns, index_col=None, coerce_float=True, parse_dates=None):
+def _wrap_result(
+ data,
+ columns,
+ index_col=None,
+ coerce_float: bool = True,
+ parse_dates=None,
+):
"""Wrap result set of query in a DataFrame."""
frame = DataFrame.from_records(data, columns=columns, coerce_float=coerce_float)
@@ -197,11 +205,11 @@ def read_sql_table(
def read_sql_table(
- table_name,
+ table_name: str,
con,
- schema=None,
- index_col=None,
- coerce_float=True,
+ schema: Optional[str] = None,
+ index_col: Optional[Union[str, Sequence[str]]] = None,
+ coerce_float: bool = True,
parse_dates=None,
columns=None,
chunksize: Optional[int] = None,
@@ -321,7 +329,7 @@ def read_sql_query(
sql,
con,
index_col=None,
- coerce_float=True,
+ coerce_float: bool = True,
params=None,
parse_dates=None,
chunksize: Optional[int] = None,
@@ -420,8 +428,8 @@ def read_sql(
def read_sql(
sql,
con,
- index_col=None,
- coerce_float=True,
+ index_col: Optional[Union[str, Sequence[str]]] = None,
+ coerce_float: bool = True,
params=None,
parse_dates=None,
columns=None,
@@ -582,15 +590,15 @@ def read_sql(
def to_sql(
frame,
- name,
+ name: str,
con,
- schema=None,
- if_exists="fail",
- index=True,
+ schema: Optional[str] = None,
+ if_exists: str = "fail",
+ index: bool = True,
index_label=None,
- chunksize=None,
+ chunksize: Optional[int] = None,
dtype=None,
- method=None,
+ method: Optional[str] = None,
) -> None:
"""
Write records stored in a DataFrame to a SQL database.
@@ -663,7 +671,7 @@ def to_sql(
)
-def has_table(table_name, con, schema=None):
+def has_table(table_name: str, con, schema: Optional[str] = None):
"""
Check if DataBase has named table.
@@ -708,7 +716,9 @@ def _engine_builder(con):
return con
-def pandasSQL_builder(con, schema=None, meta=None, is_cursor=False):
+def pandasSQL_builder(
+ con, schema: Optional[str] = None, meta=None, is_cursor: bool = False
+):
"""
Convenience function to return the correct PandasSQL subclass based on the
provided parameters.
@@ -737,7 +747,7 @@ class SQLTable(PandasObject):
def __init__(
self,
- name,
+ name: str,
pandas_sql_engine,
frame=None,
index=True,
@@ -795,7 +805,7 @@ def create(self):
else:
self._execute_create()
- def _execute_insert(self, conn, keys, data_iter):
+ def _execute_insert(self, conn, keys: List[str], data_iter):
"""
Execute SQL statement inserting data
@@ -810,7 +820,7 @@ def _execute_insert(self, conn, keys, data_iter):
data = [dict(zip(keys, row)) for row in data_iter]
conn.execute(self.table.insert(), data)
- def _execute_insert_multi(self, conn, keys, data_iter):
+ def _execute_insert_multi(self, conn, keys: List[str], data_iter):
"""
Alternative to _execute_insert for DBs support multivalue INSERT.
@@ -857,7 +867,7 @@ def insert_data(self):
return column_names, data_list
- def insert(self, chunksize=None, method=None):
+ def insert(self, chunksize: Optional[int] = None, method: Optional[str] = None):
# set insert method
if method is None:
@@ -894,7 +904,12 @@ def insert(self, chunksize=None, method=None):
exec_insert(conn, keys, chunk_iter)
def _query_iterator(
- self, result, chunksize, columns, coerce_float=True, parse_dates=None
+ self,
+ result,
+ chunksize: Optional[str],
+ columns,
+ coerce_float: bool = True,
+ parse_dates=None,
):
"""Return generator through chunked result set."""
while True:
@@ -1203,7 +1218,7 @@ class SQLDatabase(PandasSQL):
"""
- def __init__(self, engine, schema=None, meta=None):
+ def __init__(self, engine, schema: Optional[str] = None, meta=None):
self.connectable = engine
if not meta:
from sqlalchemy.schema import MetaData
@@ -1228,13 +1243,13 @@ def execute(self, *args, **kwargs):
def read_table(
self,
- table_name,
- index_col=None,
- coerce_float=True,
+ table_name: str,
+ index_col: Optional[Union[str, Sequence[str]]] = None,
+ coerce_float: bool = True,
parse_dates=None,
columns=None,
- schema=None,
- chunksize=None,
+ schema: Optional[str] = None,
+ chunksize: Optional[int] = None,
):
"""
Read SQL database table into a DataFrame.
@@ -1288,7 +1303,12 @@ def read_table(
@staticmethod
def _query_iterator(
- result, chunksize, columns, index_col=None, coerce_float=True, parse_dates=None
+ result,
+ chunksize: int,
+ columns,
+ index_col=None,
+ coerce_float=True,
+ parse_dates=None,
):
"""Return generator through chunked result set"""
while True:
@@ -1306,12 +1326,12 @@ def _query_iterator(
def read_query(
self,
- sql,
- index_col=None,
- coerce_float=True,
+ sql: str,
+ index_col: Optional[str] = None,
+ coerce_float: bool = True,
parse_dates=None,
params=None,
- chunksize=None,
+ chunksize: Optional[int] = None,
):
"""
Read SQL query into a DataFrame.
@@ -1490,12 +1510,12 @@ def to_sql(
def tables(self):
return self.meta.tables
- def has_table(self, name, schema=None):
+ def has_table(self, name: str, schema: Optional[str] = None):
return self.connectable.run_callable(
self.connectable.dialect.has_table, name, schema or self.meta.schema
)
- def get_table(self, table_name, schema=None):
+ def get_table(self, table_name: str, schema: Optional[str] = None):
schema = schema or self.meta.schema
if schema:
tbl = self.meta.tables.get(".".join([schema, table_name]))
@@ -1511,7 +1531,7 @@ def get_table(self, table_name, schema=None):
return tbl
- def drop_table(self, table_name, schema=None):
+ def drop_table(self, table_name: str, schema: Optional[str] = None):
schema = schema or self.meta.schema
if self.has_table(table_name, schema):
self.meta.reflect(only=[table_name], schema=schema)
@@ -1608,7 +1628,7 @@ def _execute_create(self):
for stmt in self.table:
conn.execute(stmt)
- def insert_statement(self, *, num_rows):
+ def insert_statement(self, *, num_rows: int):
names = list(map(str, self.frame.columns))
wld = "?" # wildcard char
escape = _get_valid_sqlite_name
@@ -1737,7 +1757,7 @@ class SQLiteDatabase(PandasSQL):
"""
- def __init__(self, con, is_cursor=False):
+ def __init__(self, con, is_cursor: bool = False):
self.is_cursor = is_cursor
self.con = con
@@ -1775,7 +1795,12 @@ def execute(self, *args, **kwargs):
@staticmethod
def _query_iterator(
- cursor, chunksize, columns, index_col=None, coerce_float=True, parse_dates=None
+ cursor,
+ chunksize: int,
+ columns,
+ index_col=None,
+ coerce_float: bool = True,
+ parse_dates=None,
):
"""Return generator through chunked result set"""
while True:
@@ -1798,10 +1823,10 @@ def read_query(
self,
sql,
index_col=None,
- coerce_float=True,
+ coerce_float: bool = True,
params=None,
parse_dates=None,
- chunksize=None,
+ chunksize: Optional[int] = None,
):
args = _convert_params(sql, params)
@@ -1908,7 +1933,7 @@ def to_sql(
table.create()
table.insert(chunksize, method)
- def has_table(self, name, schema=None):
+ def has_table(self, name: str, schema: Optional[str] = None):
# TODO(wesm): unused?
# escape = _get_valid_sqlite_name
# esc_name = escape(name)
@@ -1918,14 +1943,21 @@ def has_table(self, name, schema=None):
return len(self.execute(query, [name]).fetchall()) > 0
- def get_table(self, table_name, schema=None):
+ def get_table(self, table_name: str, schema: Optional[str] = None):
return None # not supported in fallback mode
- def drop_table(self, name, schema=None):
+ def drop_table(self, name: str, schema: Optional[str] = None):
drop_sql = f"DROP TABLE {_get_valid_sqlite_name(name)}"
self.execute(drop_sql)
- def _create_sql_schema(self, frame, table_name, keys=None, dtype=None, schema=None):
+ def _create_sql_schema(
+ self,
+ frame,
+ table_name: str,
+ keys=None,
+ dtype=None,
+ schema: Optional[str] = None,
+ ):
table = SQLiteTable(
table_name,
self,
@@ -1938,7 +1970,9 @@ def _create_sql_schema(self, frame, table_name, keys=None, dtype=None, schema=No
return str(table.sql_schema())
-def get_schema(frame, name, keys=None, con=None, dtype=None, schema=None):
+def get_schema(
+ frame, name: str, keys=None, con=None, dtype=None, schema: Optional[str] = None
+):
"""
Get the SQL db table schema for the given frame.
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38537 | 2020-12-17T07:26:33Z | 2020-12-21T23:45:23Z | 2020-12-21T23:45:23Z | 2020-12-21T23:45:28Z |
Added Documentation to specify that DataFrame.last() needs the index to be sorted to deliver the expected results | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index f9aa5ca9e8ea9..9b0c3caa0b407 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8439,8 +8439,8 @@ def last(self: FrameOrSeries, offset) -> FrameOrSeries:
"""
Select final periods of time series data based on a date offset.
- When having a DataFrame with dates as index, this function can
- select the last few rows based on a date offset.
+ For a DataFrame with a sorted DatetimeIndex, this function
+ selects the last few rows based on a date offset.
Parameters
----------
| Added Documentation mentioning that DataFrame.last() needs the index to be sorted to deliver the expected results
Haven't yet worked on raising an error will work as advised
- [ ] closes #38000
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38536 | 2020-12-17T05:40:31Z | 2020-12-17T16:54:24Z | 2020-12-17T16:54:23Z | 2021-09-27T23:40:01Z |
CLN: use .view(i8) instead of .astype(i8) for datetimelike values | diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py
index f8237a436f436..0fc6c8a23f5f2 100644
--- a/pandas/core/window/ewm.py
+++ b/pandas/core/window/ewm.py
@@ -12,6 +12,7 @@
from pandas.util._decorators import Appender, Substitution, doc
from pandas.core.dtypes.common import is_datetime64_ns_dtype
+from pandas.core.dtypes.missing import isna
import pandas.core.common as common
from pandas.core.util.numba_ import maybe_use_numba
@@ -252,7 +253,9 @@ def __init__(
raise ValueError(
"halflife must be a string or datetime.timedelta object"
)
- self.times = np.asarray(times.astype(np.int64))
+ if isna(times).any():
+ raise ValueError("Cannot convert NaT values to integer")
+ self.times = np.asarray(times.view(np.int64))
self.halflife = Timedelta(halflife).value
# Halflife is no longer applicable when calculating COM
# But allow COM to still be calculated if the user passes other decay args
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 527ee51873631..2620c562aefeb 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -1739,7 +1739,7 @@ def get_format_timedelta64(
If box, then show the return in quotes
"""
- values_int = values.astype(np.int64)
+ values_int = values.view(np.int64)
consider_values = values_int != iNaT
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 853a982536d40..88485f99c07aa 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -371,15 +371,15 @@ def parse_dates_safe(dates, delta=False, year=False, days=False):
if is_datetime64_dtype(dates.dtype):
if delta:
time_delta = dates - stata_epoch
- d["delta"] = time_delta._values.astype(np.int64) // 1000 # microseconds
+ d["delta"] = time_delta._values.view(np.int64) // 1000 # microseconds
if days or year:
date_index = DatetimeIndex(dates)
d["year"] = date_index._data.year
d["month"] = date_index._data.month
if days:
- days_in_ns = dates.astype(np.int64) - to_datetime(
+ days_in_ns = dates.view(np.int64) - to_datetime(
d["year"], format="%Y"
- ).astype(np.int64)
+ ).view(np.int64)
d["days"] = days_in_ns // NS_PER_DAY
elif infer_dtype(dates, skipna=False) == "datetime":
diff --git a/pandas/tests/indexes/period/test_constructors.py b/pandas/tests/indexes/period/test_constructors.py
index 678967db72a0b..75c8c766b0e67 100644
--- a/pandas/tests/indexes/period/test_constructors.py
+++ b/pandas/tests/indexes/period/test_constructors.py
@@ -329,7 +329,7 @@ def test_constructor_simple_new(self):
msg = "Should be numpy array of type i8"
with pytest.raises(AssertionError, match=msg):
# Need ndarray, not Int64Index
- type(idx._data)._simple_new(idx.astype("i8"), freq=idx.freq)
+ type(idx._data)._simple_new(idx._int64index, freq=idx.freq)
arr = type(idx._data)._simple_new(idx.asi8, freq=idx.freq)
result = idx._simple_new(arr, name="p")
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index ce95eb59ed3c4..8f9b6699503ee 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -112,7 +112,7 @@ def test_frame_non_unique_columns(self, orient, data):
# in milliseconds; these are internally stored in nanosecond,
# so divide to get where we need
# TODO: a to_epoch method would also solve; see GH 14772
- expected.iloc[:, 0] = expected.iloc[:, 0].astype(np.int64) // 1000000
+ expected.iloc[:, 0] = expected.iloc[:, 0].view(np.int64) // 1000000
elif orient == "split":
expected = df
@@ -254,7 +254,7 @@ def test_roundtrip_timestamp(self, orient, convert_axes, numpy, datetime_frame):
if not convert_axes: # one off for ts handling
# DTI gets converted to epoch values
- idx = expected.index.astype(np.int64) // 1000000
+ idx = expected.index.view(np.int64) // 1000000
if orient != "split": # TODO: handle consistently across orients
idx = idx.astype(str)
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 497039de99196..4442d47c9f535 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -841,7 +841,7 @@ def test_timedelta(self):
with tm.assert_produces_warning(UserWarning):
df.to_sql("test_timedelta", self.conn)
result = sql.read_sql_query("SELECT * FROM test_timedelta", self.conn)
- tm.assert_series_equal(result["foo"], df["foo"].astype("int64"))
+ tm.assert_series_equal(result["foo"], df["foo"].view("int64"))
def test_complex_raises(self):
df = DataFrame({"a": [1 + 1j, 2j]})
diff --git a/pandas/tests/window/test_ewm.py b/pandas/tests/window/test_ewm.py
index c026f52e94482..6b57d2f55e4ff 100644
--- a/pandas/tests/window/test_ewm.py
+++ b/pandas/tests/window/test_ewm.py
@@ -127,3 +127,11 @@ def test_ewma_with_times_variable_spacing(tz_aware_fixture):
result = df.ewm(halflife=halflife, times=times).mean()
expected = DataFrame([0.0, 0.5674161888241773, 1.545239952073459])
tm.assert_frame_equal(result, expected)
+
+
+def test_ewm_with_nat_raises(halflife_with_times):
+ # GH#38535
+ ser = Series(range(1))
+ times = DatetimeIndex(["NaT"])
+ with pytest.raises(ValueError, match="Cannot convert NaT values to integer"):
+ ser.ewm(com=0.1, halflife=halflife_with_times, times=times)
| prelude to deprecating the astype behavior | https://api.github.com/repos/pandas-dev/pandas/pulls/38535 | 2020-12-17T03:07:24Z | 2020-12-19T02:21:41Z | 2020-12-19T02:21:41Z | 2020-12-19T02:39:37Z |
BUG&TST: HTML formatting error in Styler.render() in rowspan attribute | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index e2521cedb64cc..c4e1ecaf57c19 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -766,6 +766,10 @@ Plotting
- Bug in :meth:`DataFrame.plot` and :meth:`Series.plot` was overwriting matplotlib's shared y axes behaviour when no ``sharey`` parameter was passed (:issue:`37942`)
- Bug in :meth:`DataFrame.plot` was raising a ``TypeError`` with ``ExtensionDtype`` columns (:issue:`32073`)
+Styler
+^^^^^^
+
+- Bug in :meth:`Styler.render` HTML was generated incorrectly beacause of formatting error in rowspan attribute, it now matches with w3 syntax. (:issue:`38234`)
Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 4557c10927a15..6ed31f38893dc 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -389,7 +389,7 @@ def format_attr(pair):
rowspan = idx_lengths.get((c, r), 0)
if rowspan > 1:
es["attributes"] = [
- format_attr({"key": "rowspan", "value": rowspan})
+ format_attr({"key": "rowspan", "value": f'"{rowspan}"'})
]
row_es.append(es)
diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py
index 64fe8a7730ae2..0bb422658df25 100644
--- a/pandas/tests/io/formats/test_style.py
+++ b/pandas/tests/io/formats/test_style.py
@@ -1411,7 +1411,7 @@ def test_mi_sparse(self):
"display_value": "a",
"is_visible": True,
"type": "th",
- "attributes": ["rowspan=2"],
+ "attributes": ['rowspan="2"'],
"class": "row_heading level0 row0",
"id": "level0_row0",
}
@@ -1740,6 +1740,15 @@ def test_colspan_w3(self):
s = Styler(df, uuid="_", cell_ids=False)
assert '<th class="col_heading level0 col0" colspan="2">l0</th>' in s.render()
+ def test_rowspan_w3(self):
+ # GH 38533
+ df = DataFrame(data=[[1, 2]], index=[["l0", "l0"], ["l1a", "l1b"]])
+ s = Styler(df, uuid="_", cell_ids=False)
+ assert (
+ '<th id="T___level0_row0" class="row_heading '
+ 'level0 row0" rowspan="2">l0</th>' in s.render()
+ )
+
@pytest.mark.parametrize("len_", [1, 5, 32, 33, 100])
def test_uuid_len(self, len_):
# GH 36345
| - [x] closes [#38234](https://github.com/pandas-dev/pandas/issues/38234)
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38533 | 2020-12-17T00:27:41Z | 2020-12-22T20:33:37Z | 2020-12-22T20:33:37Z | 2020-12-22T20:34:02Z |
BUG: Regression in logical ops raising ValueError with Categorical columns with unused categories | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index e2521cedb64cc..372dfa0f8ad42 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -859,7 +859,7 @@ Other
- Bug in :meth:`RangeIndex.difference` returning :class:`Int64Index` in some cases where it should return :class:`RangeIndex` (:issue:`38028`)
- Fixed bug in :func:`assert_series_equal` when comparing a datetime-like array with an equivalent non extension dtype array (:issue:`37609`)
- Bug in :func:`.is_bool_dtype` would raise when passed a valid string such as ``"boolean"`` (:issue:`38386`)
-
+- Fixed regression in logical operators raising ``ValueError`` when columns of :class:`DataFrame` are a :class:`CategoricalIndex` with unused categories (:issue:`38367`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py
index d8b5dba424cbf..7b14a5c636abe 100644
--- a/pandas/core/ops/__init__.py
+++ b/pandas/core/ops/__init__.py
@@ -309,11 +309,11 @@ def should_reindex_frame_op(
if fill_value is None and level is None and axis is default_axis:
# TODO: any other cases we should handle here?
- cols = left.columns.intersection(right.columns)
# Intersection is always unique so we have to check the unique columns
left_uniques = left.columns.unique()
right_uniques = right.columns.unique()
+ cols = left_uniques.intersection(right_uniques)
if len(cols) and not (cols.equals(left_uniques) and cols.equals(right_uniques)):
# TODO: is there a shortcut available when len(cols) == 0?
return True
diff --git a/pandas/tests/frame/test_logical_ops.py b/pandas/tests/frame/test_logical_ops.py
index efabc666993ee..dca12c632a418 100644
--- a/pandas/tests/frame/test_logical_ops.py
+++ b/pandas/tests/frame/test_logical_ops.py
@@ -4,7 +4,7 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import CategoricalIndex, DataFrame, Interval, Series, isnull
import pandas._testing as tm
@@ -162,3 +162,24 @@ def test_logical_with_nas(self):
result = d["a"].fillna(False, downcast=False) | d["b"]
expected = Series([True, True])
tm.assert_series_equal(result, expected)
+
+ def test_logical_ops_categorical_columns(self):
+ # GH#38367
+ intervals = [Interval(1, 2), Interval(3, 4)]
+ data = DataFrame(
+ [[1, np.nan], [2, np.nan]],
+ columns=CategoricalIndex(
+ intervals, categories=intervals + [Interval(5, 6)]
+ ),
+ )
+ mask = DataFrame(
+ [[False, False], [False, False]], columns=data.columns, dtype=bool
+ )
+ result = mask | isnull(data)
+ expected = DataFrame(
+ [[False, True], [False, True]],
+ columns=CategoricalIndex(
+ intervals, categories=intervals + [Interval(5, 6)]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
| - [x] closes #38367
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
@simonjayhawkins
This would fix the issue, but is pretty dirty. If we decide to merge this, we should remove this again with #38140 Also test would have to be adjusted (expected remove unused category) | https://api.github.com/repos/pandas-dev/pandas/pulls/38532 | 2020-12-16T22:51:44Z | 2020-12-21T13:55:18Z | 2020-12-21T13:55:18Z | 2020-12-21T15:50:24Z |
CLN: share .values | diff --git a/pandas/_testing.py b/pandas/_testing.py
index 73b1dcf31979f..964c8d4d3d61a 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -834,7 +834,9 @@ def _get_ilevel_values(index, level):
# skip exact index checking when `check_categorical` is False
if check_exact and check_categorical:
if not left.equals(right):
- diff = np.sum((left.values != right.values).astype(int)) * 100.0 / len(left)
+ diff = (
+ np.sum((left._values != right._values).astype(int)) * 100.0 / len(left)
+ )
msg = f"{obj} values are different ({np.round(diff, 5)} %)"
raise_assert_detail(obj, msg, left, right)
else:
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 2101893d39dc9..70696a0991c90 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -27,7 +27,7 @@
from pandas._libs.lib import is_datetime_array, no_default
from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime, Timestamp
from pandas._libs.tslibs.timezones import tz_compare
-from pandas._typing import AnyArrayLike, Dtype, DtypeObj, Label, Shape, final
+from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Label, Shape, final
from pandas.compat.numpy import function as nv
from pandas.errors import DuplicateLabelError, InvalidIndexError
from pandas.util._decorators import Appender, cache_readonly, doc
@@ -1164,7 +1164,7 @@ def to_series(self, index=None, name=None):
if name is None:
name = self.name
- return Series(self.values.copy(), index=index, name=name)
+ return Series(self._values.copy(), index=index, name=name)
def to_frame(self, index: bool = True, name=None):
"""
@@ -4036,7 +4036,7 @@ def _wrap_joined_index(
# Uncategorized Methods
@property
- def values(self) -> np.ndarray:
+ def values(self) -> ArrayLike:
"""
Return an array representing the data in the Index.
@@ -4055,7 +4055,7 @@ def values(self) -> np.ndarray:
Index.array : Reference to the underlying data.
Index.to_numpy : A NumPy array representing the underlying data.
"""
- return self._data.view(np.ndarray)
+ return self._data
@cache_readonly
@doc(IndexOpsMixin.array)
@@ -5322,7 +5322,7 @@ def _maybe_cast_slice_bound(self, label, side: str_t, kind):
# wish to have special treatment for floats/ints, e.g. Float64Index and
# datetimelike Indexes
# reject them, if index does not contain label
- if (is_float(label) or is_integer(label)) and label not in self.values:
+ if (is_float(label) or is_integer(label)) and label not in self._values:
raise self._invalid_indexer("slice", label)
return label
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index e2a7752cf3f0d..bf4047ddf29b1 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -357,11 +357,6 @@ def _format_with_header(self, header: List[str], na_rep: str = "NaN") -> List[st
def inferred_type(self) -> str:
return "categorical"
- @property
- def values(self):
- """ return the underlying data, which is a Categorical """
- return self._data
-
@doc(Index.__contains__)
def __contains__(self, key: Any) -> bool:
# if key is a NaN, check if any NaN is in self.
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 23363e2c6e32a..1416f3afd60b3 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -348,13 +348,6 @@ def __contains__(self, key: Any) -> bool:
def _multiindex(self) -> MultiIndex:
return MultiIndex.from_arrays([self.left, self.right], names=["left", "right"])
- @cache_readonly
- def values(self) -> IntervalArray:
- """
- Return the IntervalIndex's data as an IntervalArray.
- """
- return self._data
-
def __array_wrap__(self, result, context=None):
# we don't want the superclass implementation
return result
| https://api.github.com/repos/pandas-dev/pandas/pulls/38531 | 2020-12-16T22:32:47Z | 2020-12-17T15:06:34Z | 2020-12-17T15:06:34Z | 2020-12-17T15:42:21Z | |
REF: avoid special-casing Categorical astype | diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index ecf77a9987bee..059c36a901297 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -354,11 +354,6 @@ def __contains__(self, key: Any) -> bool:
return contains(self, key, container=self._engine)
- @doc(Index.astype)
- def astype(self, dtype, copy=True):
- res_data = self._data.astype(dtype, copy=copy)
- return Index(res_data, name=self.name)
-
@doc(Index.fillna)
def fillna(self, value, downcast=None):
value = self._require_scalar(value)
diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py
index 73f96b2f6ad41..661adde44089c 100644
--- a/pandas/core/indexes/extension.py
+++ b/pandas/core/indexes/extension.py
@@ -11,7 +11,7 @@
from pandas.errors import AbstractMethodError
from pandas.util._decorators import cache_readonly, doc
-from pandas.core.dtypes.common import is_dtype_equal, is_object_dtype
+from pandas.core.dtypes.common import is_dtype_equal, is_object_dtype, pandas_dtype
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
from pandas.core.arrays import ExtensionArray
@@ -294,9 +294,12 @@ def map(self, mapper, na_action=None):
@doc(Index.astype)
def astype(self, dtype, copy=True):
- if is_dtype_equal(self.dtype, dtype) and copy is False:
- # Ensure that self.astype(self.dtype) is self
- return self
+ dtype = pandas_dtype(dtype)
+ if is_dtype_equal(self.dtype, dtype):
+ if not copy:
+ # Ensure that self.astype(self.dtype) is self
+ return self
+ return self.copy()
new_values = self._data.astype(dtype, copy=copy)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 0bd60931f9a7e..6500cfcd9ea5a 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -649,15 +649,7 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike:
values = self.values
- if is_categorical_dtype(dtype):
-
- if is_categorical_dtype(values.dtype):
- # GH#10696/GH#18593: update an existing categorical efficiently
- return values.astype(dtype, copy=copy)
-
- return Categorical(values, dtype=dtype)
-
- elif is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype):
+ if is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype):
# if we are passed a datetime64[ns, tz]
if copy:
# this should be the only copy
| Sits on top of #38516 | https://api.github.com/repos/pandas-dev/pandas/pulls/38530 | 2020-12-16T22:28:54Z | 2020-12-22T20:44:49Z | 2020-12-22T20:44:49Z | 2020-12-22T20:53:45Z |
CLN: remove CategoricalIndex._engine | diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index e2a7752cf3f0d..7c826000d035a 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -8,7 +8,7 @@
from pandas._libs import index as libindex
from pandas._libs.lib import no_default
from pandas._typing import ArrayLike, Label
-from pandas.util._decorators import Appender, cache_readonly, doc
+from pandas.util._decorators import Appender, doc
from pandas.core.dtypes.common import (
ensure_platform_int,
@@ -381,14 +381,6 @@ def fillna(self, value, downcast=None):
cat = self._data.fillna(value)
return type(self)._simple_new(cat, name=self.name)
- @cache_readonly
- def _engine(self):
- # we are going to look things up with the codes themselves.
- # To avoid a reference cycle, bind `codes` to a local variable, so
- # `self` is not passed into the lambda.
- codes = self.codes
- return self._engine_type(lambda: codes, len(self))
-
@doc(Index.unique)
def unique(self, level=None):
if level is not None:
| https://api.github.com/repos/pandas-dev/pandas/pulls/38529 | 2020-12-16T22:25:52Z | 2020-12-17T01:23:33Z | 2020-12-17T01:23:33Z | 2020-12-17T01:27:13Z | |
CI: pin xlrd<2.0 | diff --git a/ci/deps/azure-37-slow.yaml b/ci/deps/azure-37-slow.yaml
index 50fccf86b6340..05b33fa351ac9 100644
--- a/ci/deps/azure-37-slow.yaml
+++ b/ci/deps/azure-37-slow.yaml
@@ -31,7 +31,7 @@ dependencies:
- moto>=1.3.14
- scipy
- sqlalchemy
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/azure-38-locale.yaml b/ci/deps/azure-38-locale.yaml
index f879111a32e67..90cd11037e472 100644
--- a/ci/deps/azure-38-locale.yaml
+++ b/ci/deps/azure-38-locale.yaml
@@ -30,7 +30,7 @@ dependencies:
- pytz
- scipy
- xarray
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/azure-macos-37.yaml b/ci/deps/azure-macos-37.yaml
index 31e0ffca81424..0b8aff83fe230 100644
--- a/ci/deps/azure-macos-37.yaml
+++ b/ci/deps/azure-macos-37.yaml
@@ -26,7 +26,7 @@ dependencies:
- python-dateutil==2.7.3
- pytz
- xarray
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- pip
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index 16b4bd72683b4..ad72b9c8577e9 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -33,7 +33,7 @@ dependencies:
- s3fs>=0.4.2
- scipy
- sqlalchemy
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- pyreadstat
diff --git a/ci/deps/azure-windows-38.yaml b/ci/deps/azure-windows-38.yaml
index 449bbd05991bf..08693e02aa8d3 100644
--- a/ci/deps/azure-windows-38.yaml
+++ b/ci/deps/azure-windows-38.yaml
@@ -31,6 +31,6 @@ dependencies:
- pytz
- s3fs>=0.4.0
- scipy
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
diff --git a/ci/deps/travis-37-cov.yaml b/ci/deps/travis-37-cov.yaml
index c89b42ef06a2e..b68ff0672888a 100644
--- a/ci/deps/travis-37-cov.yaml
+++ b/ci/deps/travis-37-cov.yaml
@@ -43,7 +43,7 @@ dependencies:
- sqlalchemy
- statsmodels
- xarray
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- pip
diff --git a/ci/deps/travis-37-locale.yaml b/ci/deps/travis-37-locale.yaml
index 4e442b10482a7..60a92c4dfd3c6 100644
--- a/ci/deps/travis-37-locale.yaml
+++ b/ci/deps/travis-37-locale.yaml
@@ -35,7 +35,7 @@ dependencies:
- pytables>=3.5.1
- scipy
- xarray=0.12.3
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/travis-38-slow.yaml b/ci/deps/travis-38-slow.yaml
index e4b719006a11e..2b4339cf12658 100644
--- a/ci/deps/travis-38-slow.yaml
+++ b/ci/deps/travis-38-slow.yaml
@@ -30,7 +30,7 @@ dependencies:
- moto>=1.3.14
- scipy
- sqlalchemy
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
| - [ ] closes #38524
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38526 | 2020-12-16T17:43:14Z | 2020-12-16T19:26:04Z | 2020-12-16T19:26:03Z | 2021-11-20T23:21:03Z |
REF: use astype_nansafe in Index.astype | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index bafb37775cbb1..2101893d39dc9 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -33,6 +33,7 @@
from pandas.util._decorators import Appender, cache_readonly, doc
from pandas.core.dtypes.cast import (
+ astype_nansafe,
find_common_type,
maybe_cast_to_integer_array,
maybe_promote,
@@ -693,22 +694,21 @@ def astype(self, dtype, copy=True):
if is_dtype_equal(self.dtype, dtype):
return self.copy() if copy else self
- elif is_categorical_dtype(dtype):
- from pandas.core.indexes.category import CategoricalIndex
-
- return CategoricalIndex(
- self._values, name=self.name, dtype=dtype, copy=copy
+ if needs_i8_conversion(dtype) and is_float_dtype(self.dtype):
+ # We can't put this into astype_nansafe bc astype_nansafe allows
+ # casting np.nan to NaT
+ raise TypeError(
+ f"Cannot convert {type(self).__name__} to dtype {dtype}; integer "
+ "values are required for conversion"
)
- elif is_extension_array_dtype(dtype):
- return Index(np.asarray(self), name=self.name, dtype=dtype, copy=copy)
-
try:
- casted = self._values.astype(dtype, copy=copy)
- except (TypeError, ValueError) as err:
+ casted = astype_nansafe(self._values, dtype=dtype, copy=True)
+ except TypeError as err:
raise TypeError(
f"Cannot cast {type(self).__name__} to dtype {dtype}"
) from err
+
return Index(casted, name=self.name, dtype=dtype)
_index_shared_docs[
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py
index 91d27d9922aa5..d6f91c9a06739 100644
--- a/pandas/core/indexes/numeric.py
+++ b/pandas/core/indexes/numeric.py
@@ -7,12 +7,10 @@
from pandas._typing import Dtype, DtypeObj, Label
from pandas.util._decorators import doc
-from pandas.core.dtypes.cast import astype_nansafe
from pandas.core.dtypes.common import (
is_bool,
is_bool_dtype,
is_dtype_equal,
- is_extension_array_dtype,
is_float,
is_float_dtype,
is_integer_dtype,
@@ -21,8 +19,6 @@
is_scalar,
is_signed_integer_dtype,
is_unsigned_integer_dtype,
- needs_i8_conversion,
- pandas_dtype,
)
from pandas.core.dtypes.generic import ABCSeries
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
@@ -332,21 +328,6 @@ def inferred_type(self) -> str:
"""
return "floating"
- @doc(Index.astype)
- def astype(self, dtype, copy=True):
- dtype = pandas_dtype(dtype)
- if needs_i8_conversion(dtype):
- raise TypeError(
- f"Cannot convert Float64Index to dtype {dtype}; integer "
- "values are required for conversion"
- )
- elif is_integer_dtype(dtype) and not is_extension_array_dtype(dtype):
- # TODO(jreback); this can change once we have an EA Index type
- # GH 13149
- arr = astype_nansafe(self._values, dtype=dtype)
- return Int64Index(arr, name=self.name)
- return super().astype(dtype, copy=copy)
-
# ----------------------------------------------------------------
# Indexing Methods
| https://api.github.com/repos/pandas-dev/pandas/pulls/38518 | 2020-12-16T04:09:54Z | 2020-12-16T22:32:24Z | 2020-12-16T22:32:24Z | 2020-12-16T23:09:11Z | |
BUG: read_excel forward-filling MI names | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 931ec895cc73f..09b7bff31d323 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -267,6 +267,7 @@ I/O
- Bug in :func:`to_hdf` raising ``KeyError`` when trying to apply
for subclasses of ``DataFrame`` or ``Series`` (:issue:`33748`).
- Bug in :func:`json_normalize` resulting in the first element of a generator object not being included in the returned ``DataFrame`` (:issue:`35923`)
+- Bug in :func:`read_excel` forward filling :class:`MultiIndex` names with multiple header and index columns specified (:issue:`34673`)
Period
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 57e4e87644fed..b23b5fe5b34a8 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -504,6 +504,8 @@ def parse(
header_name, _ = pop_header_name(data[row], index_col)
header_names.append(header_name)
+ has_index_names = is_list_like(header) and len(header) > 1
+
if is_list_like(index_col):
# Forward fill values for MultiIndex index.
if header is None:
@@ -513,6 +515,12 @@ def parse(
else:
offset = 1 + max(header)
+ # GH34673: if MultiIndex names present and not defined in the header,
+ # offset needs to be incremented so that forward filling starts
+ # from the first MI value instead of the name
+ if has_index_names:
+ offset += 1
+
# Check if we have an empty dataset
# before trying to collect data.
if offset < len(data):
@@ -525,8 +533,6 @@ def parse(
else:
last = data[row][col]
- has_index_names = is_list_like(header) and len(header) > 1
-
# GH 12292 : error when read one empty column from excel file
try:
parser = TextParser(
diff --git a/pandas/tests/io/data/excel/testmultiindex.ods b/pandas/tests/io/data/excel/testmultiindex.ods
index b7f03900e6617..deb88bdad1694 100644
Binary files a/pandas/tests/io/data/excel/testmultiindex.ods and b/pandas/tests/io/data/excel/testmultiindex.ods differ
diff --git a/pandas/tests/io/data/excel/testmultiindex.xls b/pandas/tests/io/data/excel/testmultiindex.xls
index 4329992642c8c..08dc78ea34d56 100644
Binary files a/pandas/tests/io/data/excel/testmultiindex.xls and b/pandas/tests/io/data/excel/testmultiindex.xls differ
diff --git a/pandas/tests/io/data/excel/testmultiindex.xlsb b/pandas/tests/io/data/excel/testmultiindex.xlsb
index b66d6dab17ee0..f5f62d305640f 100644
Binary files a/pandas/tests/io/data/excel/testmultiindex.xlsb and b/pandas/tests/io/data/excel/testmultiindex.xlsb differ
diff --git a/pandas/tests/io/data/excel/testmultiindex.xlsm b/pandas/tests/io/data/excel/testmultiindex.xlsm
index ebbca4856562f..8bd16b016608c 100644
Binary files a/pandas/tests/io/data/excel/testmultiindex.xlsm and b/pandas/tests/io/data/excel/testmultiindex.xlsm differ
diff --git a/pandas/tests/io/data/excel/testmultiindex.xlsx b/pandas/tests/io/data/excel/testmultiindex.xlsx
index afe1758a7a132..56fc6f20b711a 100644
Binary files a/pandas/tests/io/data/excel/testmultiindex.xlsx and b/pandas/tests/io/data/excel/testmultiindex.xlsx differ
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 8b1a96f694e71..110b79adb5646 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -841,6 +841,43 @@ def test_read_excel_multiindex(self, read_ext):
)
tm.assert_frame_equal(actual, expected)
+ @pytest.mark.parametrize(
+ "sheet_name,idx_lvl2",
+ [
+ ("both_name_blank_after_mi_name", [np.nan, "b", "a", "b"]),
+ ("both_name_multiple_blanks", [np.nan] * 4),
+ ],
+ )
+ def test_read_excel_multiindex_blank_after_name(
+ self, read_ext, sheet_name, idx_lvl2
+ ):
+ # GH34673
+ if pd.read_excel.keywords["engine"] == "pyxlsb":
+ pytest.xfail("Sheets containing datetimes not supported by pyxlsb (GH4679")
+
+ mi_file = "testmultiindex" + read_ext
+ mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]], names=["c1", "c2"])
+ expected = DataFrame(
+ [
+ [1, 2.5, pd.Timestamp("2015-01-01"), True],
+ [2, 3.5, pd.Timestamp("2015-01-02"), False],
+ [3, 4.5, pd.Timestamp("2015-01-03"), False],
+ [4, 5.5, pd.Timestamp("2015-01-04"), True],
+ ],
+ columns=mi,
+ index=MultiIndex.from_arrays(
+ (["foo", "foo", "bar", "bar"], idx_lvl2),
+ names=["ilvl1", "ilvl2"],
+ ),
+ )
+ result = pd.read_excel(
+ mi_file,
+ sheet_name=sheet_name,
+ index_col=[0, 1],
+ header=[0, 1],
+ )
+ tm.assert_frame_equal(result, expected)
+
def test_read_excel_multiindex_header_only(self, read_ext):
# see gh-11733.
#
| - [x] closes #34673
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Added test with OP's issue as a sheet in the style of existing sheets in `tests/io/data/excel/testmultiindex.*`
(the same as the "both_name" sheet, but with the cell below the MI name empty)
New sheet looks like:
<img width="393" alt="Screen Shot 2020-12-15 at 9 50 02 PM" src="https://user-images.githubusercontent.com/37011898/102298700-961dbf00-3f1f-11eb-9c98-034268ad9d68.png">
In master without this change, the empty cell was being filled with the index name `ilvl2` | https://api.github.com/repos/pandas-dev/pandas/pulls/38517 | 2020-12-16T02:58:53Z | 2021-01-01T19:45:28Z | 2021-01-01T19:45:27Z | 2021-01-01T20:02:32Z |
API: CategoricalDtype.__eq__ with categories=None stricter | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index ce64940d964ca..fbd2c2b5345fc 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -133,7 +133,7 @@ See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for mor
Other API changes
^^^^^^^^^^^^^^^^^
-
+- Partially initialized :class:`CategoricalDtype` (i.e. those with ``categories=None`` objects will no longer compare as equal to fully initialized dtype objects.
-
-
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 413309b3d01ad..24cbbd9ec6ac9 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -36,6 +36,7 @@
is_scalar,
is_timedelta64_dtype,
needs_i8_conversion,
+ pandas_dtype,
)
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.generic import ABCIndex, ABCSeries
@@ -409,6 +410,7 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
If copy is set to False and dtype is categorical, the original
object is returned.
"""
+ dtype = pandas_dtype(dtype)
if self.dtype is dtype:
result = self.copy() if copy else self
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 081339583e3fd..5869b2cf22516 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -639,6 +639,19 @@ def is_dtype_equal(source, target) -> bool:
>>> is_dtype_equal(DatetimeTZDtype(tz="UTC"), "datetime64")
False
"""
+ if isinstance(target, str):
+ if not isinstance(source, str):
+ # GH#38516 ensure we get the same behavior from
+ # is_dtype_equal(CDT, "category") and CDT == "category"
+ try:
+ src = get_dtype(source)
+ if isinstance(src, ExtensionDtype):
+ return src == target
+ except (TypeError, AttributeError):
+ return False
+ elif isinstance(source, str):
+ return is_dtype_equal(target, source)
+
try:
source = get_dtype(source)
target = get_dtype(target)
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index 0de8a07abbec3..75f3b511bc57d 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -354,12 +354,10 @@ def __eq__(self, other: Any) -> bool:
elif not (hasattr(other, "ordered") and hasattr(other, "categories")):
return False
elif self.categories is None or other.categories is None:
- # We're forced into a suboptimal corner thanks to math and
- # backwards compatibility. We require that `CDT(...) == 'category'`
- # for all CDTs **including** `CDT(None, ...)`. Therefore, *all*
- # CDT(., .) = CDT(None, False) and *all*
- # CDT(., .) = CDT(None, True).
- return True
+ # For non-fully-initialized dtypes, these are only equal to
+ # - the string "category" (handled above)
+ # - other CategoricalDtype with categories=None
+ return self.categories is other.categories
elif self.ordered or other.ordered:
# At least one has ordered=True; equal if both have ordered=True
# and the same values for categories in the same order.
diff --git a/pandas/tests/arrays/categorical/test_dtypes.py b/pandas/tests/arrays/categorical/test_dtypes.py
index 12654388de904..a2192b2810596 100644
--- a/pandas/tests/arrays/categorical/test_dtypes.py
+++ b/pandas/tests/arrays/categorical/test_dtypes.py
@@ -127,7 +127,7 @@ def test_astype(self, ordered):
expected = np.array(cat)
tm.assert_numpy_array_equal(result, expected)
- msg = r"Cannot cast object dtype to <class 'float'>"
+ msg = r"Cannot cast object dtype to float64"
with pytest.raises(ValueError, match=msg):
cat.astype(float)
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py
index 0d0601aa542b4..9e75ba0864e76 100644
--- a/pandas/tests/dtypes/test_common.py
+++ b/pandas/tests/dtypes/test_common.py
@@ -641,7 +641,6 @@ def test_is_complex_dtype():
(pd.CategoricalIndex(["a", "b"]).dtype, CategoricalDtype(["a", "b"])),
(pd.CategoricalIndex(["a", "b"]), CategoricalDtype(["a", "b"])),
(CategoricalDtype(), CategoricalDtype()),
- (CategoricalDtype(["a", "b"]), CategoricalDtype()),
(pd.DatetimeIndex([1, 2]), np.dtype("=M8[ns]")),
(pd.DatetimeIndex([1, 2]).dtype, np.dtype("=M8[ns]")),
("<M8[ns]", np.dtype("<M8[ns]")),
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index 872dd03768833..8ba8562affb67 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -90,9 +90,20 @@ def test_hash_vs_equality(self, dtype):
assert hash(dtype) == hash(dtype2)
def test_equality(self, dtype):
+ assert dtype == "category"
assert is_dtype_equal(dtype, "category")
+ assert "category" == dtype
+ assert is_dtype_equal("category", dtype)
+
+ assert dtype == CategoricalDtype()
assert is_dtype_equal(dtype, CategoricalDtype())
+ assert CategoricalDtype() == dtype
+ assert is_dtype_equal(CategoricalDtype(), dtype)
+
+ assert dtype != "foo"
assert not is_dtype_equal(dtype, "foo")
+ assert "foo" != dtype
+ assert not is_dtype_equal("foo", dtype)
def test_construction_from_string(self, dtype):
result = CategoricalDtype.construct_from_string("category")
@@ -834,10 +845,27 @@ def test_categorical_equality(self, ordered1, ordered2):
c1 = CategoricalDtype(list("abc"), ordered1)
c2 = CategoricalDtype(None, ordered2)
c3 = CategoricalDtype(None, ordered1)
- assert c1 == c2
- assert c2 == c1
+ assert c1 != c2
+ assert c2 != c1
assert c2 == c3
+ def test_categorical_dtype_equality_requires_categories(self):
+ # CategoricalDtype with categories=None is *not* equal to
+ # any fully-initialized CategoricalDtype
+ first = CategoricalDtype(["a", "b"])
+ second = CategoricalDtype()
+ third = CategoricalDtype(ordered=True)
+
+ assert second == second
+ assert third == third
+
+ assert first != second
+ assert second != first
+ assert first != third
+ assert third != first
+ assert second == third
+ assert third == second
+
@pytest.mark.parametrize("categories", [list("abc"), None])
@pytest.mark.parametrize("other", ["category", "not a category"])
def test_categorical_equality_strings(self, categories, ordered, other):
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index f43ae58fbcc2f..e11edabb2f468 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -1622,7 +1622,7 @@ def test_identical(self, left):
merged = pd.merge(left, left, on="X")
result = merged.dtypes.sort_index()
expected = Series(
- [CategoricalDtype(), np.dtype("O"), np.dtype("O")],
+ [CategoricalDtype(categories=["foo", "bar"]), np.dtype("O"), np.dtype("O")],
index=["X", "Y_x", "Y_y"],
)
tm.assert_series_equal(result, expected)
@@ -1633,7 +1633,11 @@ def test_basic(self, left, right):
merged = pd.merge(left, right, on="X")
result = merged.dtypes.sort_index()
expected = Series(
- [CategoricalDtype(), np.dtype("O"), np.dtype("int64")],
+ [
+ CategoricalDtype(categories=["foo", "bar"]),
+ np.dtype("O"),
+ np.dtype("int64"),
+ ],
index=["X", "Y", "Z"],
)
tm.assert_series_equal(result, expected)
@@ -1713,7 +1717,11 @@ def test_other_columns(self, left, right):
merged = pd.merge(left, right, on="X")
result = merged.dtypes.sort_index()
expected = Series(
- [CategoricalDtype(), np.dtype("O"), CategoricalDtype()],
+ [
+ CategoricalDtype(categories=["foo", "bar"]),
+ np.dtype("O"),
+ CategoricalDtype(categories=[1, 2]),
+ ],
index=["X", "Y", "Z"],
)
tm.assert_series_equal(result, expected)
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
xref #37929
This will allow us to remove special-casing for Categorical in Block._astype, Index.astype, and Categorical.astype. | https://api.github.com/repos/pandas-dev/pandas/pulls/38516 | 2020-12-16T02:35:21Z | 2020-12-22T17:35:58Z | 2020-12-22T17:35:58Z | 2020-12-22T17:45:47Z |
CI: un-xfail | diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index fe3ca0d0937b3..99e7c3061d670 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -671,12 +671,7 @@ def test_s3_roundtrip(self, df_compat, s3_resource, pa, s3so):
@pytest.mark.parametrize(
"partition_col",
[
- pytest.param(
- ["A"],
- marks=pytest.mark.xfail(
- PY38, reason="Getting back empty DataFrame", raises=AssertionError
- ),
- ),
+ ["A"],
[],
],
)
| No idea why this stopped failing, but not going to look a gift horse in the mouth. | https://api.github.com/repos/pandas-dev/pandas/pulls/38514 | 2020-12-15T23:30:15Z | 2020-12-16T01:02:11Z | 2020-12-16T01:02:11Z | 2021-01-21T14:50:03Z |
BUG: .item() incorrectly casts td64/dt64 to int | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 63445d0e1598d..29d3130aa3316 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -733,7 +733,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj,
raise ValueError(msg)
dtype = val.dtype
- val = val.item()
+ val = lib.item_from_zerodim(val)
elif isinstance(val, str):
diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py
index 5a69f5e4b012f..0a274dcfd1d73 100644
--- a/pandas/core/tools/timedeltas.py
+++ b/pandas/core/tools/timedeltas.py
@@ -4,6 +4,7 @@
import numpy as np
+from pandas._libs import lib
from pandas._libs.tslibs import NaT
from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit
@@ -117,7 +118,7 @@ def to_timedelta(arg, unit=None, errors="raise"):
return _convert_listlike(arg, unit=unit, errors=errors, name=arg.name)
elif isinstance(arg, np.ndarray) and arg.ndim == 0:
# extract array scalar and process below
- arg = arg.item()
+ arg = lib.item_from_zerodim(arg)
elif is_list_like(arg) and getattr(arg, "ndim", 1) == 1:
return _convert_listlike(arg, unit=unit, errors=errors)
elif getattr(arg, "ndim", 1) > 1:
diff --git a/pandas/tests/dtypes/cast/test_infer_dtype.py b/pandas/tests/dtypes/cast/test_infer_dtype.py
index 65da8985843f9..16fb6f327a4d5 100644
--- a/pandas/tests/dtypes/cast/test_infer_dtype.py
+++ b/pandas/tests/dtypes/cast/test_infer_dtype.py
@@ -3,7 +3,11 @@
import numpy as np
import pytest
-from pandas.core.dtypes.cast import infer_dtype_from_array, infer_dtype_from_scalar
+from pandas.core.dtypes.cast import (
+ infer_dtype_from,
+ infer_dtype_from_array,
+ infer_dtype_from_scalar,
+)
from pandas.core.dtypes.common import is_dtype_equal
from pandas import (
@@ -171,3 +175,17 @@ def test_infer_dtype_from_scalar_errors():
def test_infer_dtype_from_array(arr, expected, pandas_dtype):
dtype, _ = infer_dtype_from_array(arr, pandas_dtype=pandas_dtype)
assert is_dtype_equal(dtype, expected)
+
+
+@pytest.mark.parametrize("cls", [np.datetime64, np.timedelta64])
+def test_infer_dtype_from_scalar_zerodim_datetimelike(cls):
+ # ndarray.item() can incorrectly return int instead of td64/dt64
+ val = cls(1234, "ns")
+ arr = np.array(val)
+
+ dtype, res = infer_dtype_from_scalar(arr)
+ assert dtype.type is cls
+ assert isinstance(res, cls)
+
+ dtype, res = infer_dtype_from(arr)
+ assert dtype.type is cls
diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py
index 585ad4a7fab51..c0196549cee33 100644
--- a/pandas/tests/tools/test_to_timedelta.py
+++ b/pandas/tests/tools/test_to_timedelta.py
@@ -227,3 +227,20 @@ def test_to_timedelta_precision_over_nanos(self, input, expected, func):
expected = pd.Timedelta(expected)
result = func(input)
assert result == expected
+
+ def test_to_timedelta_zerodim(self):
+ # ndarray.item() incorrectly returns int for dt64[ns] and td64[ns]
+ dt64 = pd.Timestamp.now().to_datetime64()
+ arg = np.array(dt64)
+
+ msg = (
+ "Value must be Timedelta, string, integer, float, timedelta "
+ "or convertible, not datetime64"
+ )
+ with pytest.raises(ValueError, match=msg):
+ to_timedelta(arg)
+
+ arg2 = arg.view("m8[ns]")
+ result = to_timedelta(arg2)
+ assert isinstance(result, pd.Timedelta)
+ assert result.value == dt64.view("i8")
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38512 | 2020-12-15T22:32:47Z | 2020-12-16T02:36:56Z | 2020-12-16T02:36:56Z | 2020-12-16T02:45:48Z |
BUG: MultiIndex.equals returning incorrectly True when Indexes contains NaN | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 57dd1d05a274e..af96269019ca4 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -232,7 +232,7 @@ MultiIndex
^^^^^^^^^^
- Bug in :meth:`DataFrame.drop` raising ``TypeError`` when :class:`MultiIndex` is non-unique and no level is provided (:issue:`36293`)
--
+- Bug in :meth:`MultiIndex.equals` incorrectly returning ``True`` when :class:`MultiIndex` containing ``NaN`` even when they are differntly ordered (:issue:`38439`)
I/O
^^^
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 1edd98e980a2d..78e7a8516178a 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3454,13 +3454,17 @@ def equals(self, other: object) -> bool:
for i in range(self.nlevels):
self_codes = self.codes[i]
- self_codes = self_codes[self_codes != -1]
+ other_codes = other.codes[i]
+ self_mask = self_codes == -1
+ other_mask = other_codes == -1
+ if not np.array_equal(self_mask, other_mask):
+ return False
+ self_codes = self_codes[~self_mask]
self_values = algos.take_nd(
np.asarray(self.levels[i]._values), self_codes, allow_fill=False
)
- other_codes = other.codes[i]
- other_codes = other_codes[other_codes != -1]
+ other_codes = other_codes[~other_mask]
other_values = algos.take_nd(
np.asarray(other.levels[i]._values), other_codes, allow_fill=False
)
diff --git a/pandas/tests/indexes/multi/test_equivalence.py b/pandas/tests/indexes/multi/test_equivalence.py
index c31c2416ff722..bb34760e28d96 100644
--- a/pandas/tests/indexes/multi/test_equivalence.py
+++ b/pandas/tests/indexes/multi/test_equivalence.py
@@ -209,6 +209,16 @@ def test_equals_missing_values():
assert not result
+def test_equals_missing_values_differently_sorted():
+ # GH#38439
+ mi1 = pd.MultiIndex.from_tuples([(81.0, np.nan), (np.nan, np.nan)])
+ mi2 = pd.MultiIndex.from_tuples([(np.nan, np.nan), (81.0, np.nan)])
+ assert not mi1.equals(mi2)
+
+ mi2 = pd.MultiIndex.from_tuples([(81.0, np.nan), (np.nan, np.nan)])
+ assert mi1.equals(mi2)
+
+
def test_is_():
mi = MultiIndex.from_tuples(zip(range(10), range(10)))
assert mi.is_(mi)
| - [x] xref #38439
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Depending on the expected behavior of align, this may have hidden an additional bug in align in the referenced issue. | https://api.github.com/repos/pandas-dev/pandas/pulls/38511 | 2020-12-15T22:29:30Z | 2020-12-17T02:12:43Z | 2020-12-17T02:12:42Z | 2020-12-17T16:11:00Z |
REF: handle ravel inside astype_nansafe | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 63445d0e1598d..2f35f34f838ec 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -973,6 +973,14 @@ def astype_nansafe(
ValueError
The dtype was a datetime64/timedelta64 dtype, but it had no unit.
"""
+ if arr.ndim > 1:
+ # Make sure we are doing non-copy ravel and reshape.
+ flags = arr.flags
+ flat = arr.ravel("K")
+ result = astype_nansafe(flat, dtype, copy=copy, skipna=skipna)
+ order = "F" if flags.f_contiguous else "C"
+ return result.reshape(arr.shape, order=order)
+
# dispatch on extension dtype if needed
if isinstance(dtype, ExtensionDtype):
return dtype.construct_array_type()._from_sequence(arr, dtype=dtype, copy=copy)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index b9558daf05ad2..2630c07814bb2 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -629,10 +629,6 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
else:
raise
- if isinstance(new_values, np.ndarray):
- # TODO(EA2D): special case not needed with 2D EAs
- new_values = new_values.reshape(self.shape)
-
newb = self.make_block(new_values)
if newb.is_numeric and self.is_numeric:
if newb.shape != self.shape:
@@ -691,9 +687,7 @@ def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike:
# We still need to go through astype_nansafe for
# e.g. dtype = Sparse[object, 0]
- # astype_nansafe works with 1-d only
- vals1d = values.ravel()
- values = astype_nansafe(vals1d, dtype, copy=True)
+ values = astype_nansafe(values, dtype, copy=True)
return values
| https://api.github.com/repos/pandas-dev/pandas/pulls/38507 | 2020-12-15T18:59:45Z | 2020-12-16T00:50:30Z | 2020-12-16T00:50:30Z | 2020-12-16T01:14:31Z | |
REF: require listlike in maybe_cast_to_datetime | diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index 3dc7acc6cf0b5..5f67db0244a4a 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -481,6 +481,7 @@ def sanitize_array(
return subarr
elif isinstance(data, (list, tuple, abc.Set, abc.ValuesView)) and len(data) > 0:
+ # TODO: deque, array.array
if isinstance(data, set):
# Raise only for unordered sets, e.g., not for dict_keys
raise TypeError("Set type is unordered")
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 034fd927a8017..1725a8de53e67 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1339,6 +1339,9 @@ def maybe_cast_to_datetime(value, dtype: Optional[DtypeObj]):
from pandas.core.tools.datetimes import to_datetime
from pandas.core.tools.timedeltas import to_timedelta
+ if not is_list_like(value):
+ raise TypeError("value must be listlike")
+
if dtype is not None:
is_datetime64 = is_datetime64_dtype(dtype)
is_datetime64tz = is_datetime64tz_dtype(dtype)
@@ -1367,13 +1370,6 @@ def maybe_cast_to_datetime(value, dtype: Optional[DtypeObj]):
raise TypeError(
f"cannot convert datetimelike to dtype [{dtype}]"
)
- elif is_datetime64tz:
-
- # our NaT doesn't support tz's
- # this will coerce to DatetimeIndex with
- # a matching dtype below
- if is_scalar(value) and isna(value):
- value = [value]
elif is_timedelta64 and not is_dtype_equal(dtype, TD64NS_DTYPE):
@@ -1386,9 +1382,7 @@ def maybe_cast_to_datetime(value, dtype: Optional[DtypeObj]):
else:
raise TypeError(f"cannot convert timedeltalike to dtype [{dtype}]")
- if is_scalar(value):
- value = maybe_unbox_datetimelike(value, dtype)
- elif not is_sparse(value):
+ if not is_sparse(value):
value = np.array(value, copy=False)
# have a scalar array-like (e.g. NaT)
| https://api.github.com/repos/pandas-dev/pandas/pulls/38505 | 2020-12-15T17:51:59Z | 2020-12-22T00:58:35Z | 2020-12-22T00:58:35Z | 2020-12-22T01:02:40Z | |
REG: DataFrame.shift with axis=1 and CategoricalIndex columns | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 57dd1d05a274e..d6dd1872c3e7e 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -195,7 +195,6 @@ Numeric
^^^^^^^
- Bug in :meth:`DataFrame.quantile`, :meth:`DataFrame.sort_values` causing incorrect subsequent indexing behavior (:issue:`38351`)
- Bug in :meth:`DataFrame.select_dtypes` with ``include=np.number`` now retains numeric ``ExtensionDtype`` columns (:issue:`35340`)
--
Conversion
^^^^^^^^^^
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 1bf40f782f666..86a40f0845fd9 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4586,20 +4586,23 @@ def shift(
if axis == 1 and periods != 0 and fill_value is lib.no_default and ncols > 0:
# We will infer fill_value to match the closest column
+ # Use a column that we know is valid for our column's dtype GH#38434
+ label = self.columns[0]
+
if periods > 0:
result = self.iloc[:, :-periods]
for col in range(min(ncols, abs(periods))):
# TODO(EA2D): doing this in a loop unnecessary with 2D EAs
# Define filler inside loop so we get a copy
filler = self.iloc[:, 0].shift(len(self))
- result.insert(0, col, filler, allow_duplicates=True)
+ result.insert(0, label, filler, allow_duplicates=True)
else:
result = self.iloc[:, -periods:]
for col in range(min(ncols, abs(periods))):
# Define filler inside loop so we get a copy
filler = self.iloc[:, -1].shift(len(self))
result.insert(
- len(result.columns), col, filler, allow_duplicates=True
+ len(result.columns), label, filler, allow_duplicates=True
)
result.columns = self.columns.copy()
diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py
index 2e21ce8ec2256..40b3f1e89c015 100644
--- a/pandas/tests/frame/methods/test_shift.py
+++ b/pandas/tests/frame/methods/test_shift.py
@@ -2,7 +2,7 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Series, date_range, offsets
+from pandas import CategoricalIndex, DataFrame, Index, Series, date_range, offsets
import pandas._testing as tm
@@ -292,3 +292,25 @@ def test_shift_dt64values_int_fill_deprecated(self):
expected = DataFrame({"A": [pd.Timestamp(0), pd.Timestamp(0)], "B": df2["A"]})
tm.assert_frame_equal(result, expected)
+
+ def test_shift_axis1_categorical_columns(self):
+ # GH#38434
+ ci = CategoricalIndex(["a", "b", "c"])
+ df = DataFrame(
+ {"a": [1, 3], "b": [2, 4], "c": [5, 6]}, index=ci[:-1], columns=ci
+ )
+ result = df.shift(axis=1)
+
+ expected = DataFrame(
+ {"a": [np.nan, np.nan], "b": [1, 3], "c": [2, 4]}, index=ci[:-1], columns=ci
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # periods != 1
+ result = df.shift(2, axis=1)
+ expected = DataFrame(
+ {"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 3]},
+ index=ci[:-1],
+ columns=ci,
+ )
+ tm.assert_frame_equal(result, expected)
| - [x] closes #38434
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38504 | 2020-12-15T16:33:25Z | 2020-12-17T13:46:46Z | 2020-12-17T13:46:45Z | 2020-12-18T09:35:17Z |
DOC: Corrected Out-of-date list of sort algorithms | diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index bd5cf43e19e9f..918d96cd03112 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -561,7 +561,7 @@ def argsort(
ascending : bool, default True
Whether the indices should result in an ascending
or descending sort.
- kind : {'quicksort', 'mergesort', 'heapsort'}, optional
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
Sorting algorithm.
*args, **kwargs:
Passed through to :func:`numpy.argsort`.
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 1bb5556663c29..0940920bb3dbe 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -1484,7 +1484,7 @@ def argsort(self, ascending=True, kind="quicksort", **kwargs):
ascending : bool, default True
Whether the indices should result in an ascending
or descending sort.
- kind : {'quicksort', 'mergesort', 'heapsort'}, optional
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
Sorting algorithm.
**kwargs:
passed through to :func:`numpy.argsort`.
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 7f295a73a82e6..cc89823cd7817 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5526,9 +5526,9 @@ def sort_index(
sort direction can be controlled for each level individually.
inplace : bool, default False
If True, perform operation in-place.
- kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'
- Choice of sorting algorithm. See also ndarray.np.sort for more
- information. `mergesort` is the only stable algorithm. For
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
+ Choice of sorting algorithm. See also :func:`numpy.sort` for more
+ information. `mergesort` and `stable` are the only stable algorithms. For
DataFrames, this option is only applied when sorting on a single
column or label.
na_position : {'first', 'last'}, default 'last'
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 4b0d524782924..a7dfdb3cfbd97 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -4383,11 +4383,11 @@ def sort_values(
the by.
inplace : bool, default False
If True, perform operation in-place.
- kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'
- Choice of sorting algorithm. See also ndarray.np.sort for more
- information. `mergesort` is the only stable algorithm. For
- DataFrames, if sorting by multiple columns or labels, this
- argument is ignored, defaulting to a stable sorting algorithm.
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
+ Choice of sorting algorithm. See also :func:`numpy.sort` for more
+ information. `mergesort` and `stable` are the only stable algorithms. For
+ DataFrames, this option is only applied when sorting on a single
+ column or label.
na_position : {'first', 'last'}, default 'last'
Puts NaNs at the beginning if `first`; `last` puts NaNs at the
end.
diff --git a/pandas/core/series.py b/pandas/core/series.py
index d4ae5c2245b5b..cb753e887b0f8 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -3066,9 +3066,9 @@ def sort_values(
If True, sort values in ascending order, otherwise descending.
inplace : bool, default False
If True, perform operation in-place.
- kind : {'quicksort', 'mergesort' or 'heapsort'}, default 'quicksort'
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
Choice of sorting algorithm. See also :func:`numpy.sort` for more
- information. 'mergesort' is the only stable algorithm.
+ information. 'mergesort' and 'stable' are the only stable algorithms.
na_position : {'first' or 'last'}, default 'last'
Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at
the end.
@@ -3279,9 +3279,9 @@ def sort_index(
sort direction can be controlled for each level individually.
inplace : bool, default False
If True, perform operation in-place.
- kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
Choice of sorting algorithm. See also :func:`numpy.sort` for more
- information. 'mergesort' is the only stable algorithm. For
+ information. 'mergesort' and 'stable' are the only stable algorithms. For
DataFrames, this option is only applied when sorting on a single
column or label.
na_position : {'first', 'last'}, default 'last'
@@ -3420,9 +3420,9 @@ def argsort(self, axis=0, kind="quicksort", order=None) -> "Series":
----------
axis : {0 or "index"}
Has no effect but is accepted for compatibility with numpy.
- kind : {'mergesort', 'quicksort', 'heapsort'}, default 'quicksort'
- Choice of sorting algorithm. See np.sort for more
- information. 'mergesort' is the only stable algorithm.
+ kind : {'mergesort', 'quicksort', 'heapsort', 'stable'}, default 'quicksort'
+ Choice of sorting algorithm. See :func:`numpy.sort` for more
+ information. 'mergesort' and 'stable' are the only stable algorithms.
order : None
Has no effect but is accepted for compatibility with numpy.
diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py
index 0a1cbc6de1cda..90396f1be0755 100644
--- a/pandas/core/sorting.py
+++ b/pandas/core/sorting.py
@@ -54,7 +54,7 @@ def get_indexer_indexer(
target : Index
level : int or level name or list of ints or list of level names
ascending : bool or list of bools, default True
- kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
na_position : {'first', 'last'}, default 'last'
sort_remaining : bool, default True
key : callable, optional
diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py
index 6c6be1506255a..ccaa8a797e312 100644
--- a/pandas/tests/series/methods/test_sort_index.py
+++ b/pandas/tests/series/methods/test_sort_index.py
@@ -7,6 +7,11 @@
import pandas._testing as tm
+@pytest.fixture(params=["quicksort", "mergesort", "heapsort", "stable"])
+def sort_kind(request):
+ return request.param
+
+
class TestSeriesSortIndex:
def test_sort_index_name(self, datetime_series):
result = datetime_series.sort_index(ascending=False)
@@ -104,18 +109,12 @@ def test_sort_index_multiindex(self, level):
res = s.sort_index(level=level, sort_remaining=False)
tm.assert_series_equal(s, res)
- def test_sort_index_kind(self):
+ def test_sort_index_kind(self, sort_kind):
# GH#14444 & GH#13589: Add support for sort algo choosing
series = Series(index=[3, 2, 1, 4, 3], dtype=object)
expected_series = Series(index=[1, 2, 3, 3, 4], dtype=object)
- index_sorted_series = series.sort_index(kind="mergesort")
- tm.assert_series_equal(expected_series, index_sorted_series)
-
- index_sorted_series = series.sort_index(kind="quicksort")
- tm.assert_series_equal(expected_series, index_sorted_series)
-
- index_sorted_series = series.sort_index(kind="heapsort")
+ index_sorted_series = series.sort_index(kind=sort_kind)
tm.assert_series_equal(expected_series, index_sorted_series)
def test_sort_index_na_position(self):
@@ -251,32 +250,20 @@ def test_sort_index_key_int(self):
result = series.sort_index(key=lambda x: 2 * x)
tm.assert_series_equal(result, series)
- def test_sort_index_kind_key(self, sort_by_key):
+ def test_sort_index_kind_key(self, sort_kind, sort_by_key):
# GH #14444 & #13589: Add support for sort algo choosing
series = Series(index=[3, 2, 1, 4, 3], dtype=object)
expected_series = Series(index=[1, 2, 3, 3, 4], dtype=object)
- index_sorted_series = series.sort_index(kind="mergesort", key=sort_by_key)
- tm.assert_series_equal(expected_series, index_sorted_series)
-
- index_sorted_series = series.sort_index(kind="quicksort", key=sort_by_key)
- tm.assert_series_equal(expected_series, index_sorted_series)
-
- index_sorted_series = series.sort_index(kind="heapsort", key=sort_by_key)
+ index_sorted_series = series.sort_index(kind=sort_kind, key=sort_by_key)
tm.assert_series_equal(expected_series, index_sorted_series)
- def test_sort_index_kind_neg_key(self):
+ def test_sort_index_kind_neg_key(self, sort_kind):
# GH #14444 & #13589: Add support for sort algo choosing
series = Series(index=[3, 2, 1, 4, 3], dtype=object)
expected_series = Series(index=[4, 3, 3, 2, 1], dtype=object)
- index_sorted_series = series.sort_index(kind="mergesort", key=lambda x: -x)
- tm.assert_series_equal(expected_series, index_sorted_series)
-
- index_sorted_series = series.sort_index(kind="quicksort", key=lambda x: -x)
- tm.assert_series_equal(expected_series, index_sorted_series)
-
- index_sorted_series = series.sort_index(kind="heapsort", key=lambda x: -x)
+ index_sorted_series = series.sort_index(kind=sort_kind, key=lambda x: -x)
tm.assert_series_equal(expected_series, index_sorted_series)
def test_sort_index_na_position_key(self, sort_by_key):
| Reference Issues/PRs
Fixes: #38287
Implemented changes:
Changed the docstring of all the methods using np.sort as it now includes one additional stable algorithm
| https://api.github.com/repos/pandas-dev/pandas/pulls/38503 | 2020-12-15T16:05:37Z | 2020-12-30T13:49:06Z | 2020-12-30T13:49:06Z | 2020-12-30T13:49:09Z |
Backport PR #38480 on branch 1.2.x (CI: Supress moto server logs in tests) | diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py
index bcc666a88e3be..5d4705dbe7d77 100644
--- a/pandas/tests/io/conftest.py
+++ b/pandas/tests/io/conftest.py
@@ -50,8 +50,7 @@ def s3_base(worker_id):
pytest.importorskip("s3fs")
pytest.importorskip("boto3")
requests = pytest.importorskip("requests")
- # GH 38090: Suppress http logs in tests by moto_server
- logging.getLogger("werkzeug").disabled = True
+ logging.getLogger("requests").disabled = True
with tm.ensure_safe_environment_variables():
# temporary workaround as moto fails for botocore >= 1.11 otherwise,
@@ -71,7 +70,9 @@ def s3_base(worker_id):
# pipe to null to avoid logging in terminal
proc = subprocess.Popen(
- shlex.split(f"moto_server s3 -p {endpoint_port}"), stdout=subprocess.DEVNULL
+ shlex.split(f"moto_server s3 -p {endpoint_port}"),
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
)
timeout = 5
| Backport PR #38480: CI: Supress moto server logs in tests | https://api.github.com/repos/pandas-dev/pandas/pulls/38501 | 2020-12-15T14:58:17Z | 2020-12-15T17:18:08Z | 2020-12-15T17:18:08Z | 2020-12-15T17:18:09Z |
Backport PR #38494 on branch 1.2.x (TST: don't use global fixture in the base extension tests) | diff --git a/pandas/_testing.py b/pandas/_testing.py
index 469f5e1bed6ba..73b1dcf31979f 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -108,6 +108,8 @@
+ BYTES_DTYPES
)
+NULL_OBJECTS = [None, np.nan, pd.NaT, float("nan"), pd.NA]
+
# set testing_mode
_testing_mode_warnings = (DeprecationWarning, ResourceWarning)
diff --git a/pandas/conftest.py b/pandas/conftest.py
index 2bac2ed198789..d84a72d4cc7a8 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -266,7 +266,7 @@ def nselect_method(request):
# ----------------------------------------------------------------
# Missing values & co.
# ----------------------------------------------------------------
-@pytest.fixture(params=[None, np.nan, pd.NaT, float("nan"), pd.NA], ids=str)
+@pytest.fixture(params=tm.NULL_OBJECTS, ids=str)
def nulls_fixture(request):
"""
Fixture for each null type in pandas.
diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py
index 922b3b94c16c1..b731859a761a4 100644
--- a/pandas/tests/extension/arrow/test_bool.py
+++ b/pandas/tests/extension/arrow/test_bool.py
@@ -51,8 +51,8 @@ def test_view(self, data):
data.view()
@pytest.mark.xfail(raises=AssertionError, reason="Not implemented yet")
- def test_contains(self, data, data_missing, nulls_fixture):
- super().test_contains(data, data_missing, nulls_fixture)
+ def test_contains(self, data, data_missing):
+ super().test_contains(data, data_missing)
class TestConstructors(BaseArrowTests, base.BaseConstructorsTests):
diff --git a/pandas/tests/extension/base/interface.py b/pandas/tests/extension/base/interface.py
index d7997310dde3d..6a4ff68b4580f 100644
--- a/pandas/tests/extension/base/interface.py
+++ b/pandas/tests/extension/base/interface.py
@@ -29,7 +29,7 @@ def test_can_hold_na_valid(self, data):
# GH-20761
assert data._can_hold_na is True
- def test_contains(self, data, data_missing, nulls_fixture):
+ def test_contains(self, data, data_missing):
# GH-37867
# Tests for membership checks. Membership checks for nan-likes is tricky and
# the settled on rule is: `nan_like in arr` is True if nan_like is
@@ -47,10 +47,12 @@ def test_contains(self, data, data_missing, nulls_fixture):
assert na_value in data_missing
assert na_value not in data
- if nulls_fixture is not na_value:
- # the data can never contain other nan-likes than na_value
- assert nulls_fixture not in data
- assert nulls_fixture not in data_missing
+ # the data can never contain other nan-likes than na_value
+ for na_value_obj in tm.NULL_OBJECTS:
+ if na_value_obj is na_value:
+ continue
+ assert na_value_obj not in data
+ assert na_value_obj not in data_missing
def test_memory_usage(self, data):
s = pd.Series(data)
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index d03a9ab6b2588..4a0fb8f81ed56 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -87,7 +87,7 @@ def test_memory_usage(self, data):
# Is this deliberate?
super().test_memory_usage(data)
- def test_contains(self, data, data_missing, nulls_fixture):
+ def test_contains(self, data, data_missing):
# GH-37867
# na value handling in Categorical.__contains__ is deprecated.
# See base.BaseInterFaceTests.test_contains for more details.
@@ -105,9 +105,11 @@ def test_contains(self, data, data_missing, nulls_fixture):
assert na_value not in data
# Categoricals can contain other nan-likes than na_value
- if nulls_fixture is not na_value:
- assert nulls_fixture not in data
- assert nulls_fixture in data_missing # this line differs from super method
+ for na_value_obj in tm.NULL_OBJECTS:
+ if na_value_obj is na_value:
+ continue
+ assert na_value_obj not in data
+ assert na_value_obj in data_missing # this line differs from super method
class TestConstructors(base.BaseConstructorsTests):
| Backport PR #38494: TST: don't use global fixture in the base extension tests | https://api.github.com/repos/pandas-dev/pandas/pulls/38500 | 2020-12-15T14:57:39Z | 2020-12-15T16:30:28Z | 2020-12-15T16:30:28Z | 2020-12-15T16:30:28Z |
DOC: Fix incorrect doc string for infer_dtype (#38375) | diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index c5fb20596d7b6..4e451fc33b055 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -1313,7 +1313,7 @@ def infer_dtype(value: object, skipna: bool = True) -> str:
'boolean'
>>> infer_dtype([True, False, np.nan])
- 'mixed'
+ 'boolean'
>>> infer_dtype([pd.Timestamp('20130101')])
'datetime'
| - [x] closes #38375
- ~~tests added / passed~~
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- ~~whatsnew entry~~
A minor fix to https://github.com/pandas-dev/pandas/issues/38375 correcting the output of an example in `infer_dtype` doc string
| https://api.github.com/repos/pandas-dev/pandas/pulls/38499 | 2020-12-15T14:30:52Z | 2020-12-16T02:14:19Z | 2020-12-16T02:14:18Z | 2020-12-16T02:14:22Z |
Backport PR #38478 on branch 1.2.x (CI: Use --strict-markers for pytest 6.0.2) | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2848437a76a16..48a3c464b8fe2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -64,7 +64,7 @@ jobs:
- name: Testing docstring validation script
run: |
source activate pandas-dev
- pytest --capture=no --strict scripts
+ pytest --capture=no --strict-markers scripts
if: always()
- name: Running benchmarks
diff --git a/ci/run_tests.sh b/ci/run_tests.sh
index 78d24c814840a..593939431d5eb 100755
--- a/ci/run_tests.sh
+++ b/ci/run_tests.sh
@@ -20,7 +20,7 @@ if [[ $(uname) == "Linux" && -z $DISPLAY ]]; then
XVFB="xvfb-run "
fi
-PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile -s --strict --durations=30 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas"
+PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile -s --strict-markers --durations=30 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas"
if [[ $(uname) != "Linux" && $(uname) != "Darwin" ]]; then
# GH#37455 windows py38 build appears to be running out of memory
diff --git a/test_fast.bat b/test_fast.bat
index f2c4e9fa71fcd..34c61fea08ab4 100644
--- a/test_fast.bat
+++ b/test_fast.bat
@@ -1,3 +1,3 @@
:: test on windows
set PYTHONHASHSEED=314159265
-pytest --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sXX --strict pandas
+pytest --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sXX --strict-markers pandas
diff --git a/test_fast.sh b/test_fast.sh
index 0a47f9de600ea..6444b81b3c6da 100755
--- a/test_fast.sh
+++ b/test_fast.sh
@@ -5,4 +5,4 @@
# https://github.com/pytest-dev/pytest/issues/1075
export PYTHONHASHSEED=$(python -c 'import random; print(random.randint(1, 4294967295))')
-pytest pandas --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sxX --strict "$@"
+pytest pandas --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sxX --strict-markers "$@"
| Backport PR #38478: CI: Use --strict-markers for pytest 6.0.2 | https://api.github.com/repos/pandas-dev/pandas/pulls/38497 | 2020-12-15T10:47:33Z | 2020-12-15T13:07:39Z | 2020-12-15T13:07:39Z | 2020-12-15T13:07:39Z |
Backport PR #38486 on branch 1.2.x (DOC: Fix missing ipython block in user_guide/indexing.rst) | diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst
index 817ea3445f995..0a11344d575f1 100644
--- a/doc/source/user_guide/indexing.rst
+++ b/doc/source/user_guide/indexing.rst
@@ -380,6 +380,8 @@ NA values in a boolean array propagate as ``False``:
.. versionchanged:: 1.0.2
+.. ipython:: python
+
mask = pd.array([True, False, True, False, pd.NA, False], dtype="boolean")
mask
df1[mask]
| Backport PR #38486: DOC: Fix missing ipython block in user_guide/indexing.rst | https://api.github.com/repos/pandas-dev/pandas/pulls/38496 | 2020-12-15T09:03:17Z | 2020-12-15T12:16:37Z | 2020-12-15T12:16:37Z | 2020-12-15T12:16:37Z |
TST: don't use global fixture in the base extension tests | diff --git a/pandas/_testing.py b/pandas/_testing.py
index 469f5e1bed6ba..73b1dcf31979f 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -108,6 +108,8 @@
+ BYTES_DTYPES
)
+NULL_OBJECTS = [None, np.nan, pd.NaT, float("nan"), pd.NA]
+
# set testing_mode
_testing_mode_warnings = (DeprecationWarning, ResourceWarning)
diff --git a/pandas/conftest.py b/pandas/conftest.py
index 2bac2ed198789..d84a72d4cc7a8 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -266,7 +266,7 @@ def nselect_method(request):
# ----------------------------------------------------------------
# Missing values & co.
# ----------------------------------------------------------------
-@pytest.fixture(params=[None, np.nan, pd.NaT, float("nan"), pd.NA], ids=str)
+@pytest.fixture(params=tm.NULL_OBJECTS, ids=str)
def nulls_fixture(request):
"""
Fixture for each null type in pandas.
diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py
index 922b3b94c16c1..b731859a761a4 100644
--- a/pandas/tests/extension/arrow/test_bool.py
+++ b/pandas/tests/extension/arrow/test_bool.py
@@ -51,8 +51,8 @@ def test_view(self, data):
data.view()
@pytest.mark.xfail(raises=AssertionError, reason="Not implemented yet")
- def test_contains(self, data, data_missing, nulls_fixture):
- super().test_contains(data, data_missing, nulls_fixture)
+ def test_contains(self, data, data_missing):
+ super().test_contains(data, data_missing)
class TestConstructors(BaseArrowTests, base.BaseConstructorsTests):
diff --git a/pandas/tests/extension/base/interface.py b/pandas/tests/extension/base/interface.py
index d7997310dde3d..6a4ff68b4580f 100644
--- a/pandas/tests/extension/base/interface.py
+++ b/pandas/tests/extension/base/interface.py
@@ -29,7 +29,7 @@ def test_can_hold_na_valid(self, data):
# GH-20761
assert data._can_hold_na is True
- def test_contains(self, data, data_missing, nulls_fixture):
+ def test_contains(self, data, data_missing):
# GH-37867
# Tests for membership checks. Membership checks for nan-likes is tricky and
# the settled on rule is: `nan_like in arr` is True if nan_like is
@@ -47,10 +47,12 @@ def test_contains(self, data, data_missing, nulls_fixture):
assert na_value in data_missing
assert na_value not in data
- if nulls_fixture is not na_value:
- # the data can never contain other nan-likes than na_value
- assert nulls_fixture not in data
- assert nulls_fixture not in data_missing
+ # the data can never contain other nan-likes than na_value
+ for na_value_obj in tm.NULL_OBJECTS:
+ if na_value_obj is na_value:
+ continue
+ assert na_value_obj not in data
+ assert na_value_obj not in data_missing
def test_memory_usage(self, data):
s = pd.Series(data)
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index d03a9ab6b2588..4a0fb8f81ed56 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -87,7 +87,7 @@ def test_memory_usage(self, data):
# Is this deliberate?
super().test_memory_usage(data)
- def test_contains(self, data, data_missing, nulls_fixture):
+ def test_contains(self, data, data_missing):
# GH-37867
# na value handling in Categorical.__contains__ is deprecated.
# See base.BaseInterFaceTests.test_contains for more details.
@@ -105,9 +105,11 @@ def test_contains(self, data, data_missing, nulls_fixture):
assert na_value not in data
# Categoricals can contain other nan-likes than na_value
- if nulls_fixture is not na_value:
- assert nulls_fixture not in data
- assert nulls_fixture in data_missing # this line differs from super method
+ for na_value_obj in tm.NULL_OBJECTS:
+ if na_value_obj is na_value:
+ continue
+ assert na_value_obj not in data
+ assert na_value_obj in data_missing # this line differs from super method
class TestConstructors(base.BaseConstructorsTests):
| Follow-up on https://github.com/pandas-dev/pandas/pull/37867. In the discussion about using this fixture, I forgot that we should not use global pandas fixtures in those tests, but only the ones that are defined in the local /pandas/tests/extension/conftest.py, otherwise this doesn't work for downstream projects (eg https://github.com/geopandas/geopandas/issues/1735). For this case it's easier to simply not use a fixture, I think (but still share the common definition of the list) | https://api.github.com/repos/pandas-dev/pandas/pulls/38494 | 2020-12-15T08:00:28Z | 2020-12-15T14:57:09Z | 2020-12-15T14:57:09Z | 2020-12-15T15:01:31Z |
TYP: func argument to DataFrame.apply, DataFrame.applymap, core.apply.frame_apply | diff --git a/pandas/_typing.py b/pandas/_typing.py
index 99c46d21844f3..c79942c48509e 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -133,6 +133,8 @@
"Resampler",
]
+PythonFuncType = Callable[[Any], Any]
+
# filenames and file-like-objects
Buffer = Union[IO[AnyStr], RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap]
FileOrBuffer = Union[str, Buffer[T]]
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 801d4665f9a1b..c0c6c9084b560 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -6,7 +6,7 @@
from pandas._config import option_context
-from pandas._typing import Axis, FrameOrSeriesUnion
+from pandas._typing import AggFuncType, Axis, FrameOrSeriesUnion
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.common import (
@@ -27,7 +27,7 @@
def frame_apply(
obj: "DataFrame",
- func,
+ func: AggFuncType,
axis: Axis = 0,
raw: bool = False,
result_type: Optional[str] = None,
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 86a40f0845fd9..f2e833dfe7790 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -62,6 +62,7 @@
IndexLabel,
Label,
Level,
+ PythonFuncType,
Renamer,
StorageOptions,
Suffixes,
@@ -7661,7 +7662,13 @@ def transform(
return result
def apply(
- self, func, axis: Axis = 0, raw: bool = False, result_type=None, args=(), **kwds
+ self,
+ func: AggFuncType,
+ axis: Axis = 0,
+ raw: bool = False,
+ result_type=None,
+ args=(),
+ **kwds,
):
"""
Apply a function along an axis of the DataFrame.
@@ -7807,7 +7814,9 @@ def apply(
)
return op.get_result()
- def applymap(self, func, na_action: Optional[str] = None) -> DataFrame:
+ def applymap(
+ self, func: PythonFuncType, na_action: Optional[str] = None
+ ) -> DataFrame:
"""
Apply a function to a Dataframe elementwise.
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Spinning off from #38416, xref https://github.com/pandas-dev/pandas/pull/38416#discussion_r542911035 | https://api.github.com/repos/pandas-dev/pandas/pulls/38493 | 2020-12-15T06:53:44Z | 2020-12-18T23:06:46Z | 2020-12-18T23:06:46Z | 2020-12-18T23:06:51Z |
BUG: CategoricalIndex.reindex fails when Index passed with labels all in category | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 57dd1d05a274e..719b5b5433f9c 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -170,7 +170,7 @@ Bug fixes
Categorical
^^^^^^^^^^^
--
+- Bug in ``CategoricalIndex.reindex`` failed when ``Index`` passed with elements all in category (:issue:`28690`)
-
Datetimelike
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index e2a7752cf3f0d..bd9224d340ec8 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -441,7 +441,7 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
if len(missing):
cats = self.categories.get_indexer(target)
- if (cats == -1).any():
+ if not isinstance(cats, CategoricalIndex) or (cats == -1).any():
# coerce to a regular index here!
result = Index(np.array(self), name=self.name)
new_target, indexer, _ = result._reindex_non_unique(np.array(target))
diff --git a/pandas/tests/indexes/categorical/test_reindex.py b/pandas/tests/indexes/categorical/test_reindex.py
index 668c559abd08e..8228c5139ccdd 100644
--- a/pandas/tests/indexes/categorical/test_reindex.py
+++ b/pandas/tests/indexes/categorical/test_reindex.py
@@ -1,7 +1,7 @@
import numpy as np
import pytest
-from pandas import Categorical, CategoricalIndex, Index, Series
+from pandas import Categorical, CategoricalIndex, DataFrame, Index, Series
import pandas._testing as tm
@@ -59,3 +59,35 @@ def test_reindex_missing_category(self):
msg = "'fill_value=-1' is not present in this Categorical's categories"
with pytest.raises(TypeError, match=msg):
ser.reindex([1, 2, 3, 4, 5], fill_value=-1)
+
+ @pytest.mark.parametrize(
+ "index_df,index_res,index_exp",
+ [
+ (
+ CategoricalIndex([], categories=["A"]),
+ Index(["A"]),
+ Index(["A"]),
+ ),
+ (
+ CategoricalIndex([], categories=["A"]),
+ Index(["B"]),
+ Index(["B"]),
+ ),
+ (
+ CategoricalIndex([], categories=["A"]),
+ CategoricalIndex(["A"]),
+ CategoricalIndex(["A"]),
+ ),
+ (
+ CategoricalIndex([], categories=["A"]),
+ CategoricalIndex(["B"]),
+ CategoricalIndex(["B"]),
+ ),
+ ],
+ )
+ def test_reindex_not_category(self, index_df, index_res, index_exp):
+ # GH: 28690
+ df = DataFrame(index=index_df)
+ result = df.reindex(index=index_res)
+ expected = DataFrame(index=index_exp)
+ tm.assert_frame_equal(result, expected)
| - [x] closes #28690
- [x] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38492 | 2020-12-15T05:59:55Z | 2020-12-17T23:40:05Z | 2020-12-17T23:40:05Z | 2020-12-18T11:23:46Z |
Updated README | diff --git a/README.md b/README.md
index 6d1d890c54093..f238e219bd3d8 100644
--- a/README.md
+++ b/README.md
@@ -87,7 +87,7 @@ The source code is currently hosted on GitHub at:
https://github.com/pandas-dev/pandas
Binary installers for the latest released version are available at the [Python
-package index](https://pypi.org/project/pandas) and on conda.
+Package Index (PyPI)](https://pypi.org/project/pandas) and on [Conda](https://docs.conda.io/en/latest/).
```sh
# conda
@@ -100,15 +100,15 @@ pip install pandas
```
## Dependencies
-- [NumPy](https://www.numpy.org)
-- [python-dateutil](https://labix.org/python-dateutil)
-- [pytz](https://pythonhosted.org/pytz)
+- [NumPy - Adds support for large, multi-dimensional arrays, matrices and high-level mathematical functions to operate on these arrays](https://www.numpy.org)
+- [python-dateutil - Provides powerful extensions to the standard datetime module](https://labix.org/python-dateutil)
+- [pytz - Brings the Olson tz database into Python which allows accurate and cross platform timezone calculations](https://pythonhosted.org/pytz)
See the [full installation instructions](https://pandas.pydata.org/pandas-docs/stable/install.html#dependencies) for minimum supported versions of required, recommended and optional dependencies.
## Installation from sources
-To install pandas from source you need Cython in addition to the normal
-dependencies above. Cython can be installed from pypi:
+To install pandas from source you need [Cython](https://cython.org/) in addition to the normal
+dependencies above. Cython can be installed from PyPI:
```sh
pip install cython
@@ -145,7 +145,7 @@ See the full instructions for [installing from source](https://pandas.pydata.org
The official documentation is hosted on PyData.org: https://pandas.pydata.org/pandas-docs/stable
## Background
-Work on ``pandas`` started at AQR (a quantitative hedge fund) in 2008 and
+Work on ``pandas`` started at [AQR](https://www.aqr.com/) (a quantitative hedge fund) in 2008 and
has been under active development since then.
## Getting Help
| I have updated the README with the following -
1. Added Links for Conda, Cython and AQR.
2. Added a brief description for what all the Dependencies do so people who are unfamiliar with them can atleast get a basic idea about them
3. Corrected PyPI spelling in one instance | https://api.github.com/repos/pandas-dev/pandas/pulls/38491 | 2020-12-15T04:52:09Z | 2020-12-16T16:18:40Z | 2020-12-16T16:18:40Z | 2020-12-16T17:31:23Z |
REF: share astype code in MaskedArray | diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py
index 44cc108ed9cfd..ea2ca1f70d414 100644
--- a/pandas/core/arrays/boolean.py
+++ b/pandas/core/arrays/boolean.py
@@ -10,7 +10,6 @@
from pandas.core.dtypes.common import (
is_bool_dtype,
- is_extension_array_dtype,
is_float,
is_float_dtype,
is_integer_dtype,
@@ -18,7 +17,7 @@
is_numeric_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.dtypes import register_extension_dtype
+from pandas.core.dtypes.dtypes import ExtensionDtype, register_extension_dtype
from pandas.core.dtypes.missing import isna
from pandas.core import ops
@@ -372,18 +371,10 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike:
if incompatible type with an BooleanDtype, equivalent of same_kind
casting
"""
- from pandas.core.arrays.string_ import StringDtype
-
dtype = pandas_dtype(dtype)
- if isinstance(dtype, BooleanDtype):
- values, mask = coerce_to_array(self, copy=copy)
- if not copy:
- return self
- else:
- return BooleanArray(values, mask, copy=False)
- elif isinstance(dtype, StringDtype):
- return dtype.construct_array_type()._from_sequence(self, copy=False)
+ if isinstance(dtype, ExtensionDtype):
+ return super().astype(dtype, copy)
if is_bool_dtype(dtype):
# astype_nansafe converts np.nan to True
@@ -391,15 +382,11 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike:
raise ValueError("cannot convert float NaN to bool")
else:
return self._data.astype(dtype, copy=copy)
- if is_extension_array_dtype(dtype) and is_integer_dtype(dtype):
- from pandas.core.arrays import IntegerArray
- return IntegerArray(
- self._data.astype(dtype.numpy_dtype), self._mask.copy(), copy=False
- )
# for integer, error if there are missing values
if is_integer_dtype(dtype) and self._hasna:
raise ValueError("cannot convert NA to integer")
+
# for float dtype, ensure we use np.nan before casting (numpy cannot
# deal with pd.NA)
na_value = self._na_value
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py
index aedf6adf09db4..1e9024e32c5b7 100644
--- a/pandas/core/arrays/floating.py
+++ b/pandas/core/arrays/floating.py
@@ -19,14 +19,13 @@
is_object_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.dtypes import register_extension_dtype
+from pandas.core.dtypes.dtypes import ExtensionDtype, register_extension_dtype
from pandas.core.dtypes.missing import isna
from pandas.core import ops
from pandas.core.ops import invalid_comparison
from pandas.core.tools.numeric import to_numeric
-from .masked import BaseMaskedDtype
from .numeric import NumericArray, NumericDtype
@@ -332,24 +331,10 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike:
if incompatible type with an FloatingDtype, equivalent of same_kind
casting
"""
- from pandas.core.arrays.string_ import StringArray, StringDtype
-
dtype = pandas_dtype(dtype)
- # if the dtype is exactly the same, we can fastpath
- if self.dtype == dtype:
- # return the same object for copy=False
- return self.copy() if copy else self
- # if we are astyping to another nullable masked dtype, we can fastpath
- if isinstance(dtype, BaseMaskedDtype):
- # TODO deal with NaNs
- data = self._data.astype(dtype.numpy_dtype, copy=copy)
- # mask is copied depending on whether the data was copied, and
- # not directly depending on the `copy` keyword
- mask = self._mask if data is self._data else self._mask.copy()
- return dtype.construct_array_type()(data, mask, copy=False)
- elif isinstance(dtype, StringDtype):
- return StringArray._from_sequence(self, copy=False)
+ if isinstance(dtype, ExtensionDtype):
+ return super().astype(dtype, copy=copy)
# coerce
if is_float_dtype(dtype):
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py
index 98e29f2062983..d01f84b224a89 100644
--- a/pandas/core/arrays/integer.py
+++ b/pandas/core/arrays/integer.py
@@ -9,7 +9,7 @@
from pandas.compat.numpy import function as nv
from pandas.util._decorators import cache_readonly
-from pandas.core.dtypes.base import register_extension_dtype
+from pandas.core.dtypes.base import ExtensionDtype, register_extension_dtype
from pandas.core.dtypes.common import (
is_bool_dtype,
is_datetime64_dtype,
@@ -390,24 +390,10 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike:
if incompatible type with an IntegerDtype, equivalent of same_kind
casting
"""
- from pandas.core.arrays.masked import BaseMaskedDtype
- from pandas.core.arrays.string_ import StringDtype
-
dtype = pandas_dtype(dtype)
- # if the dtype is exactly the same, we can fastpath
- if self.dtype == dtype:
- # return the same object for copy=False
- return self.copy() if copy else self
- # if we are astyping to another nullable masked dtype, we can fastpath
- if isinstance(dtype, BaseMaskedDtype):
- data = self._data.astype(dtype.numpy_dtype, copy=copy)
- # mask is copied depending on whether the data was copied, and
- # not directly depending on the `copy` keyword
- mask = self._mask if data is self._data else self._mask.copy()
- return dtype.construct_array_type()(data, mask, copy=False)
- elif isinstance(dtype, StringDtype):
- return dtype.construct_array_type()._from_sequence(self, copy=False)
+ if isinstance(dtype, ExtensionDtype):
+ return super().astype(dtype, copy=copy)
# coerce
if is_float_dtype(dtype):
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index caed932cd7857..7821f103909da 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -5,16 +5,18 @@
import numpy as np
from pandas._libs import lib, missing as libmissing
-from pandas._typing import Scalar
+from pandas._typing import ArrayLike, Dtype, Scalar
from pandas.errors import AbstractMethodError
from pandas.util._decorators import cache_readonly, doc
from pandas.core.dtypes.base import ExtensionDtype
from pandas.core.dtypes.common import (
+ is_dtype_equal,
is_integer,
is_object_dtype,
is_scalar,
is_string_dtype,
+ pandas_dtype,
)
from pandas.core.dtypes.missing import isna, notna
@@ -229,6 +231,30 @@ def to_numpy(
data = self._data.astype(dtype, copy=copy)
return data
+ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
+ dtype = pandas_dtype(dtype)
+
+ if is_dtype_equal(dtype, self.dtype):
+ if copy:
+ return self.copy()
+ return self
+
+ # if we are astyping to another nullable masked dtype, we can fastpath
+ if isinstance(dtype, BaseMaskedDtype):
+ # TODO deal with NaNs for FloatingArray case
+ data = self._data.astype(dtype.numpy_dtype, copy=copy)
+ # mask is copied depending on whether the data was copied, and
+ # not directly depending on the `copy` keyword
+ mask = self._mask if data is self._data else self._mask.copy()
+ cls = dtype.construct_array_type()
+ return cls(data, mask, copy=False)
+
+ if isinstance(dtype, ExtensionDtype):
+ eacls = dtype.construct_array_type()
+ return eacls._from_sequence(self, dtype=dtype, copy=copy)
+
+ raise NotImplementedError("subclass must implement astype to np.dtype")
+
__array_priority__ = 1000 # higher than ndarray so ops dispatch to us
def __array__(self, dtype=None) -> np.ndarray:
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index cc2013deb5252..74a41a0b64ff8 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -10,6 +10,7 @@
from pandas.core.dtypes.common import (
is_array_like,
is_bool_dtype,
+ is_dtype_equal,
is_integer_dtype,
is_object_dtype,
is_string_dtype,
@@ -285,10 +286,12 @@ def __setitem__(self, key, value):
def astype(self, dtype, copy=True):
dtype = pandas_dtype(dtype)
- if isinstance(dtype, StringDtype):
+
+ if is_dtype_equal(dtype, self.dtype):
if copy:
return self.copy()
return self
+
elif isinstance(dtype, _IntegerDtype):
arr = self._ndarray.copy()
mask = self.isna()
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
cc @jorisvandenbossche i dont know if this is the optimal way to do this, but it seems like there is a lot of share-ability here. | https://api.github.com/repos/pandas-dev/pandas/pulls/38490 | 2020-12-15T04:36:05Z | 2020-12-21T23:47:06Z | 2020-12-21T23:47:06Z | 2020-12-22T00:11:44Z |
REF: simplify maybe_upcast_putmask | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 63445d0e1598d..859783ace5006 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -419,9 +419,7 @@ def maybe_cast_to_extension_array(
return result
-def maybe_upcast_putmask(
- result: np.ndarray, mask: np.ndarray, other: Scalar
-) -> Tuple[np.ndarray, bool]:
+def maybe_upcast_putmask(result: np.ndarray, mask: np.ndarray) -> np.ndarray:
"""
A safe version of putmask that potentially upcasts the result.
@@ -435,69 +433,38 @@ def maybe_upcast_putmask(
The destination array. This will be mutated in-place if no upcasting is
necessary.
mask : boolean ndarray
- other : scalar
- The source value.
Returns
-------
result : ndarray
- changed : bool
- Set to true if the result array was upcasted.
Examples
--------
>>> arr = np.arange(1, 6)
>>> mask = np.array([False, True, False, True, True])
- >>> result, _ = maybe_upcast_putmask(arr, mask, False)
+ >>> result = maybe_upcast_putmask(arr, mask)
>>> result
- array([1, 0, 3, 0, 0])
+ array([ 1., nan, 3., nan, nan])
"""
if not isinstance(result, np.ndarray):
raise ValueError("The result input must be a ndarray.")
- if not is_scalar(other):
- # We _could_ support non-scalar other, but until we have a compelling
- # use case, we assume away the possibility.
- raise ValueError("other must be a scalar")
+
+ # NB: we never get here with result.dtype.kind in ["m", "M"]
if mask.any():
- # Two conversions for date-like dtypes that can't be done automatically
- # in np.place:
- # NaN -> NaT
- # integer or integer array -> date-like array
- if result.dtype.kind in ["m", "M"]:
- if isna(other):
- other = result.dtype.type("nat")
- elif is_integer(other):
- other = np.array(other, dtype=result.dtype)
-
- def changeit():
- # we are forced to change the dtype of the result as the input
- # isn't compatible
- r, _ = maybe_upcast(result, fill_value=other, copy=True)
- np.place(r, mask, other)
-
- return r, True
# we want to decide whether place will work
# if we have nans in the False portion of our mask then we need to
# upcast (possibly), otherwise we DON't want to upcast (e.g. if we
# have values, say integers, in the success portion then it's ok to not
# upcast)
- new_dtype, _ = maybe_promote(result.dtype, other)
+ new_dtype, _ = maybe_promote(result.dtype, np.nan)
if new_dtype != result.dtype:
+ result = result.astype(new_dtype, copy=True)
- # we have a scalar or len 0 ndarray
- # and its nan and we are changing some values
- if isna(other):
- return changeit()
-
- try:
- np.place(result, mask, other)
- except TypeError:
- # e.g. int-dtype result and float-dtype other
- return changeit()
+ np.place(result, mask, np.nan)
- return result, False
+ return result
def maybe_promote(dtype, fill_value=np.nan):
diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py
index 22f674cc6a894..857840cf9d8b9 100644
--- a/pandas/core/ops/array_ops.py
+++ b/pandas/core/ops/array_ops.py
@@ -110,7 +110,7 @@ def _masked_arith_op(x: np.ndarray, y, op):
with np.errstate(all="ignore"):
result[mask] = op(xrav[mask], y)
- result, _ = maybe_upcast_putmask(result, ~mask, np.nan)
+ result = maybe_upcast_putmask(result, ~mask)
result = result.reshape(x.shape) # 2D compat
return result
diff --git a/pandas/tests/dtypes/cast/test_upcast.py b/pandas/tests/dtypes/cast/test_upcast.py
index f9227a4e78a79..89b59ebe6628f 100644
--- a/pandas/tests/dtypes/cast/test_upcast.py
+++ b/pandas/tests/dtypes/cast/test_upcast.py
@@ -11,61 +11,27 @@
def test_upcast_error(result):
# GH23823 require result arg to be ndarray
mask = np.array([False, True, False])
- other = np.array([61, 62, 63])
with pytest.raises(ValueError, match="The result input must be a ndarray"):
- result, _ = maybe_upcast_putmask(result, mask, other)
-
-
-@pytest.mark.parametrize(
- "arr, other",
- [
- (np.arange(1, 6), np.array([61, 62, 63])),
- (np.arange(1, 6), np.array([61.1, 62.2, 63.3])),
- (np.arange(10, 15), np.array([61, 62])),
- (np.arange(10, 15), np.array([61, np.nan])),
- (
- np.arange("2019-01-01", "2019-01-06", dtype="datetime64[D]"),
- np.arange("2018-01-01", "2018-01-04", dtype="datetime64[D]"),
- ),
- (
- np.arange("2019-01-01", "2019-01-06", dtype="datetime64[D]"),
- np.arange("2018-01-01", "2018-01-03", dtype="datetime64[D]"),
- ),
- ],
-)
-def test_upcast_scalar_other(arr, other):
- # for now we do not support non-scalar `other`
- mask = np.array([False, True, False, True, True])
- with pytest.raises(ValueError, match="other must be a scalar"):
- maybe_upcast_putmask(arr, mask, other)
+ result = maybe_upcast_putmask(result, mask)
def test_upcast():
# GH23823
arr = np.arange(1, 6)
mask = np.array([False, True, False, True, True])
- result, changed = maybe_upcast_putmask(arr, mask, other=np.nan)
+ result = maybe_upcast_putmask(arr, mask)
expected = np.array([1, np.nan, 3, np.nan, np.nan])
- assert changed
tm.assert_numpy_array_equal(result, expected)
-def test_upcast_datetime():
- # GH23823
- arr = np.arange("2019-01-01", "2019-01-06", dtype="datetime64[D]")
+def test_maybe_upcast_putmask_bool():
+ # a case where maybe_upcast_putmask is *not* equivalent to
+ # try: np.putmask(result, mask, np.nan)
+ # except (ValueError, TypeError): result = np.where(mask, result, np.nan)
+ arr = np.array([True, False, True, False, True], dtype=bool)
mask = np.array([False, True, False, True, True])
- result, changed = maybe_upcast_putmask(arr, mask, other=np.nan)
+ result = maybe_upcast_putmask(arr, mask)
- expected = np.array(
- [
- "2019-01-01",
- np.datetime64("NaT"),
- "2019-01-03",
- np.datetime64("NaT"),
- np.datetime64("NaT"),
- ],
- dtype="datetime64[D]",
- )
- assert not changed
+ expected = np.array([True, np.nan, True, np.nan, np.nan], dtype=object)
tm.assert_numpy_array_equal(result, expected)
| https://api.github.com/repos/pandas-dev/pandas/pulls/38487 | 2020-12-15T01:49:49Z | 2020-12-16T02:13:25Z | 2020-12-16T02:13:25Z | 2020-12-16T02:19:42Z | |
DOC: Fix missing ipython block in user_guide/indexing.rst | diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst
index 2bc7e13e39ec4..6698a79f2741f 100644
--- a/doc/source/user_guide/indexing.rst
+++ b/doc/source/user_guide/indexing.rst
@@ -380,6 +380,8 @@ NA values in a boolean array propagate as ``False``:
.. versionchanged:: 1.0.2
+.. ipython:: python
+
mask = pd.array([True, False, True, False, pd.NA, False], dtype="boolean")
mask
df1[mask]
| - [x] closes #38485
| https://api.github.com/repos/pandas-dev/pandas/pulls/38486 | 2020-12-15T01:31:15Z | 2020-12-15T09:02:13Z | 2020-12-15T09:02:13Z | 2020-12-15T16:00:38Z |
REF: share .astype code for astype_nansafe + TDA.astype | diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index c51882afc4871..93c9567380f7f 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -24,6 +24,7 @@
)
from pandas.compat.numpy import function as nv
+from pandas.core.dtypes.cast import astype_td64_unit_conversion
from pandas.core.dtypes.common import (
DT64NS_DTYPE,
TD64NS_DTYPE,
@@ -35,7 +36,6 @@
is_scalar,
is_string_dtype,
is_timedelta64_dtype,
- is_timedelta64_ns_dtype,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import DatetimeTZDtype
@@ -324,22 +324,14 @@ def astype(self, dtype, copy: bool = True):
# DatetimeLikeArrayMixin super call handles other cases
dtype = pandas_dtype(dtype)
- if is_timedelta64_dtype(dtype) and not is_timedelta64_ns_dtype(dtype):
- # by pandas convention, converting to non-nano timedelta64
- # returns an int64-dtyped array with ints representing multiples
- # of the desired timedelta unit. This is essentially division
- if self._hasnans:
- # avoid double-copying
- result = self._data.astype(dtype, copy=False)
- return self._maybe_mask_results(
- result, fill_value=None, convert="float64"
- )
- result = self._data.astype(dtype, copy=copy)
- return result.astype("i8")
- elif is_timedelta64_ns_dtype(dtype):
+ if is_dtype_equal(dtype, self.dtype):
if copy:
return self.copy()
return self
+
+ elif dtype.kind == "m":
+ return astype_td64_unit_conversion(self._data, dtype, copy=copy)
+
return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy=copy)
def __iter__(self):
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 63445d0e1598d..059b354ee823f 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -38,7 +38,6 @@
from pandas.core.dtypes.common import (
DT64NS_DTYPE,
- INT64_DTYPE,
POSSIBLY_CAST_DTYPES,
TD64NS_DTYPE,
ensure_int8,
@@ -952,6 +951,39 @@ def coerce_indexer_dtype(indexer, categories):
return ensure_int64(indexer)
+def astype_td64_unit_conversion(
+ values: np.ndarray, dtype: np.dtype, copy: bool
+) -> np.ndarray:
+ """
+ By pandas convention, converting to non-nano timedelta64
+ returns an int64-dtyped array with ints representing multiples
+ of the desired timedelta unit. This is essentially division.
+
+ Parameters
+ ----------
+ values : np.ndarray[timedelta64[ns]]
+ dtype : np.dtype
+ timedelta64 with unit not-necessarily nano
+ copy : bool
+
+ Returns
+ -------
+ np.ndarray
+ """
+ if is_dtype_equal(values.dtype, dtype):
+ if copy:
+ return values.copy()
+ return values
+
+ # otherwise we are converting to non-nano
+ result = values.astype(dtype, copy=False) # avoid double-copying
+ result = result.astype(np.float64)
+
+ mask = isna(values)
+ np.putmask(result, mask, np.nan)
+ return result
+
+
def astype_nansafe(
arr, dtype: DtypeObj, copy: bool = True, skipna: bool = False
) -> ArrayLike:
@@ -1007,17 +1039,8 @@ def astype_nansafe(
raise ValueError("Cannot convert NaT values to integer")
return arr.view(dtype)
- if dtype not in [INT64_DTYPE, TD64NS_DTYPE]:
-
- # allow frequency conversions
- # we return a float here!
- if dtype.kind == "m":
- mask = isna(arr)
- result = arr.astype(dtype).astype(np.float64)
- result[mask] = np.nan
- return result
- elif dtype == TD64NS_DTYPE:
- return arr.astype(TD64NS_DTYPE, copy=copy)
+ elif dtype.kind == "m":
+ return astype_td64_unit_conversion(arr, dtype, copy=copy)
raise TypeError(f"cannot astype a timedelta from [{arr.dtype}] to [{dtype}]")
diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index 24cc2ae0c4d48..5cf1def014450 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -4,24 +4,14 @@
from pandas._libs.tslibs import Timedelta, to_offset
from pandas._typing import DtypeObj
from pandas.errors import InvalidIndexError
-from pandas.util._decorators import doc
-
-from pandas.core.dtypes.common import (
- TD64NS_DTYPE,
- is_scalar,
- is_timedelta64_dtype,
- is_timedelta64_ns_dtype,
- pandas_dtype,
-)
+
+from pandas.core.dtypes.common import TD64NS_DTYPE, is_scalar, is_timedelta64_dtype
from pandas.core.arrays import datetimelike as dtl
from pandas.core.arrays.timedeltas import TimedeltaArray
import pandas.core.common as com
from pandas.core.indexes.base import Index, maybe_extract_name
-from pandas.core.indexes.datetimelike import (
- DatetimeIndexOpsMixin,
- DatetimeTimedeltaMixin,
-)
+from pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin
from pandas.core.indexes.extension import inherit_names
@@ -159,19 +149,6 @@ def __new__(
# -------------------------------------------------------------------
- @doc(Index.astype)
- def astype(self, dtype, copy: bool = True):
- dtype = pandas_dtype(dtype)
- if is_timedelta64_dtype(dtype) and not is_timedelta64_ns_dtype(dtype):
- # Have to repeat the check for 'timedelta64' (not ns) dtype
- # so that we can return a numeric index, since pandas will return
- # a TimedeltaIndex when dtype='timedelta'
- result = self._data.astype(dtype, copy=copy)
- if self.hasnans:
- return Index(result, name=self.name)
- return Index(result.astype("i8"), name=self.name)
- return DatetimeIndexOpsMixin.astype(self, dtype, copy=copy)
-
def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
"""
Can we compare values of the given dtype to our own?
diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py
index f0e730eecf3d5..a1bc50604d34b 100644
--- a/pandas/tests/indexes/timedeltas/test_timedelta.py
+++ b/pandas/tests/indexes/timedeltas/test_timedelta.py
@@ -189,6 +189,21 @@ def test_fields(self):
rng.name = "name"
assert rng.days.name == "name"
+ def test_freq_conversion_always_floating(self):
+ # even if we have no NaTs, we get back float64; this matches TDA and Series
+ tdi = timedelta_range("1 Day", periods=30)
+
+ res = tdi.astype("m8[s]")
+ expected = Index((tdi.view("i8") / 10 ** 9).astype(np.float64))
+ tm.assert_index_equal(res, expected)
+
+ # check this matches Series and TimedeltaArray
+ res = tdi._data.astype("m8[s]")
+ tm.assert_numpy_array_equal(res, expected._values)
+
+ res = tdi.to_series().astype("m8[s]")
+ tm.assert_numpy_array_equal(res._values, expected._values)
+
def test_freq_conversion(self):
# doc example
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
This changes TDI.astype and TDA.astype in the cast with no-NAs to return float64 instead of int64, matching Series behavior. | https://api.github.com/repos/pandas-dev/pandas/pulls/38481 | 2020-12-15T00:00:31Z | 2020-12-16T01:00:01Z | 2020-12-16T01:00:01Z | 2020-12-16T21:06:43Z |
CI: Supress moto server logs in tests | diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py
index bcc666a88e3be..5d4705dbe7d77 100644
--- a/pandas/tests/io/conftest.py
+++ b/pandas/tests/io/conftest.py
@@ -50,8 +50,7 @@ def s3_base(worker_id):
pytest.importorskip("s3fs")
pytest.importorskip("boto3")
requests = pytest.importorskip("requests")
- # GH 38090: Suppress http logs in tests by moto_server
- logging.getLogger("werkzeug").disabled = True
+ logging.getLogger("requests").disabled = True
with tm.ensure_safe_environment_variables():
# temporary workaround as moto fails for botocore >= 1.11 otherwise,
@@ -71,7 +70,9 @@ def s3_base(worker_id):
# pipe to null to avoid logging in terminal
proc = subprocess.Popen(
- shlex.split(f"moto_server s3 -p {endpoint_port}"), stdout=subprocess.DEVNULL
+ shlex.split(f"moto_server s3 -p {endpoint_port}"),
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
)
timeout = 5
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
https://github.com/pandas-dev/pandas/pull/38096 originally did not do the trick. This change worked for me locally. | https://api.github.com/repos/pandas-dev/pandas/pulls/38480 | 2020-12-14T23:54:45Z | 2020-12-15T14:58:04Z | 2020-12-15T14:58:04Z | 2020-12-29T02:56:46Z |
REF: share unboxing code | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 63445d0e1598d..e91622b773724 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -3,7 +3,7 @@
"""
from contextlib import suppress
-from datetime import date, datetime, timedelta
+from datetime import datetime, timedelta
from typing import (
TYPE_CHECKING,
Any,
@@ -1717,18 +1717,9 @@ def convert_scalar_for_putitemlike(scalar: Scalar, dtype: np.dtype) -> Scalar:
-------
scalar
"""
- if dtype.kind == "m":
- if isinstance(scalar, (timedelta, np.timedelta64)):
- # We have to cast after asm8 in case we have NaT
- return Timedelta(scalar).asm8.view("timedelta64[ns]")
- elif scalar is None or scalar is NaT or (is_float(scalar) and np.isnan(scalar)):
- return np.timedelta64("NaT", "ns")
- if dtype.kind == "M":
- if isinstance(scalar, (date, np.datetime64)):
- # Note: we include date, not just datetime
- return Timestamp(scalar).to_datetime64()
- elif scalar is None or scalar is NaT or (is_float(scalar) and np.isnan(scalar)):
- return np.datetime64("NaT", "ns")
+ if dtype.kind in ["m", "M"]:
+ scalar = maybe_box_datetimelike(scalar, dtype)
+ return maybe_unbox_datetimelike(scalar, dtype)
else:
validate_numeric_casting(dtype, scalar)
return scalar
| https://api.github.com/repos/pandas-dev/pandas/pulls/38479 | 2020-12-14T23:24:24Z | 2020-12-16T02:12:19Z | 2020-12-16T02:12:19Z | 2020-12-16T02:17:58Z | |
CI: Use --strict-markers for pytest 6.0.2 | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2848437a76a16..48a3c464b8fe2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -64,7 +64,7 @@ jobs:
- name: Testing docstring validation script
run: |
source activate pandas-dev
- pytest --capture=no --strict scripts
+ pytest --capture=no --strict-markers scripts
if: always()
- name: Running benchmarks
diff --git a/ci/run_tests.sh b/ci/run_tests.sh
index 78d24c814840a..593939431d5eb 100755
--- a/ci/run_tests.sh
+++ b/ci/run_tests.sh
@@ -20,7 +20,7 @@ if [[ $(uname) == "Linux" && -z $DISPLAY ]]; then
XVFB="xvfb-run "
fi
-PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile -s --strict --durations=30 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas"
+PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile -s --strict-markers --durations=30 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas"
if [[ $(uname) != "Linux" && $(uname) != "Darwin" ]]; then
# GH#37455 windows py38 build appears to be running out of memory
diff --git a/test_fast.bat b/test_fast.bat
index f2c4e9fa71fcd..34c61fea08ab4 100644
--- a/test_fast.bat
+++ b/test_fast.bat
@@ -1,3 +1,3 @@
:: test on windows
set PYTHONHASHSEED=314159265
-pytest --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sXX --strict pandas
+pytest --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sXX --strict-markers pandas
diff --git a/test_fast.sh b/test_fast.sh
index 0a47f9de600ea..6444b81b3c6da 100755
--- a/test_fast.sh
+++ b/test_fast.sh
@@ -5,4 +5,4 @@
# https://github.com/pytest-dev/pytest/issues/1075
export PYTHONHASHSEED=$(python -c 'import random; print(random.randint(1, 4294967295))')
-pytest pandas --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sxX --strict "$@"
+pytest pandas --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sxX --strict-markers "$@"
| closes #38483
Found in the npdev build.
Noted in pytest changlog: https://docs.pytest.org/en/stable/changelog.html#deprecations
| https://api.github.com/repos/pandas-dev/pandas/pulls/38478 | 2020-12-14T23:15:52Z | 2020-12-15T00:14:35Z | 2020-12-15T00:14:35Z | 2020-12-15T10:47:21Z |
BENCH: Fix CategoricalIndexing benchmark | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 48a3c464b8fe2..e8834bd509bf0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -74,14 +74,10 @@ jobs:
asv check -E existing
git remote add upstream https://github.com/pandas-dev/pandas.git
git fetch upstream
- if git diff upstream/master --name-only | grep -q "^asv_bench/"; then
- asv machine --yes
- asv dev | sed "/failed$/ s/^/##[error]/" | tee benchmarks.log
- if grep "failed" benchmarks.log > /dev/null ; then
- exit 1
- fi
- else
- echo "Benchmarks did not run, no changes detected"
+ asv machine --yes
+ asv dev | sed "/failed$/ s/^/##[error]/" | tee benchmarks.log
+ if grep "failed" benchmarks.log > /dev/null ; then
+ exit 1
fi
if: always()
diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py
index 4fd91c8aafe4b..38d1f64bd5f4e 100644
--- a/asv_bench/benchmarks/indexing.py
+++ b/asv_bench/benchmarks/indexing.py
@@ -3,6 +3,7 @@
lower-level methods directly on Index and subclasses, see index_object.py,
indexing_engine.py, and index_cached.py
"""
+import string
import warnings
import numpy as np
@@ -255,6 +256,7 @@ def setup(self, index):
"non_monotonic": CategoricalIndex(list("abc" * N)),
}
self.data = indices[index]
+ self.data_unique = CategoricalIndex(list(string.printable))
self.int_scalar = 10000
self.int_list = list(range(10000))
@@ -281,7 +283,7 @@ def time_get_loc_scalar(self, index):
self.data.get_loc(self.cat_scalar)
def time_get_indexer_list(self, index):
- self.data.get_indexer(self.cat_list)
+ self.data_unique.get_indexer(self.cat_list)
class MethodLookup:
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
This benchmark behavior changed after https://github.com/pandas-dev/pandas/pull/38372
Additionally, exploring if its feasible to always run the benchmarks to catch these changes earlier. | https://api.github.com/repos/pandas-dev/pandas/pulls/38476 | 2020-12-14T22:13:59Z | 2020-12-16T01:01:43Z | 2020-12-16T01:01:43Z | 2020-12-16T21:03:48Z |
DOC: Add doc-string examples for pd.read_sql using custom parse_dates arg values | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 3eeee61f62a7e..d2f20a91cc654 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -178,6 +178,10 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
pytest -q --doctest-modules pandas/core/strings/
RET=$(($RET + $?)) ; echo $MSG "DONE"
+ MSG='Doctests sql.py' ; echo $MSG
+ pytest -q --doctest-modules pandas/io/sql.py
+ RET=$(($RET + $?)) ; echo $MSG "DONE"
+
# Directories
MSG='Doctests arrays'; echo $MSG
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index b7efb4a8d6947..23f992ceb009a 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -482,6 +482,64 @@ def read_sql(
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql_query : Read SQL query into a DataFrame.
+
+ Examples
+ --------
+ Read data from SQL via either a SQL query or a SQL tablename.
+ When using a SQLite database only SQL queries are accepted,
+ providing only the SQL tablename will result in an error.
+
+ >>> from sqlite3 import connect
+ >>> conn = connect(':memory:')
+ >>> df = pd.DataFrame(data=[[0, '10/11/12'], [1, '12/11/10']],
+ ... columns=['int_column', 'date_column'])
+ >>> df.to_sql('test_data', conn)
+
+ >>> pd.read_sql('SELECT int_column, date_column FROM test_data', conn)
+ int_column date_column
+ 0 0 10/11/12
+ 1 1 12/11/10
+
+ >>> pd.read_sql('test_data', 'postgres:///db_name') # doctest:+SKIP
+
+ Apply date parsing to columns through the ``parse_dates`` argument
+
+ >>> pd.read_sql('SELECT int_column, date_column FROM test_data',
+ ... conn,
+ ... parse_dates=["date_column"])
+ int_column date_column
+ 0 0 2012-10-11
+ 1 1 2010-12-11
+
+ The ``parse_dates`` argument calls ``pd.to_datetime`` on the provided columns.
+ Custom argument values for applying ``pd.to_datetime`` on a column are specified
+ via a dictionary format:
+ 1. Ignore errors while parsing the values of "date_column"
+
+ >>> pd.read_sql('SELECT int_column, date_column FROM test_data',
+ ... conn,
+ ... parse_dates={"date_column": {"errors": "ignore"}})
+ int_column date_column
+ 0 0 2012-10-11
+ 1 1 2010-12-11
+
+ 2. Apply a dayfirst date parsing order on the values of "date_column"
+
+ >>> pd.read_sql('SELECT int_column, date_column FROM test_data',
+ ... conn,
+ ... parse_dates={"date_column": {"dayfirst": True}})
+ int_column date_column
+ 0 0 2012-11-10
+ 1 1 2010-11-12
+
+ 3. Apply custom formatting when date parsing the values of "date_column"
+
+ >>> pd.read_sql('SELECT int_column, date_column FROM test_data',
+ ... conn,
+ ... parse_dates={"date_column": {"format": "%d/%m/%y"}})
+ int_column date_column
+ 0 0 2012-11-10
+ 1 1 2010-11-12
"""
pandas_sql = pandasSQL_builder(con)
| follow on PR for #37823
- [x] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38475 | 2020-12-14T22:08:33Z | 2020-12-17T02:18:51Z | 2020-12-17T02:18:51Z | 2020-12-17T02:18:57Z |
BUG: require arraylike in infer_dtype_from_array | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index abcc60a15c641..8c795c2aad224 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -674,7 +674,7 @@ def infer_dtype_from(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, Any]:
If False, scalar/array belongs to pandas extension types is inferred as
object
"""
- if is_scalar(val):
+ if not is_list_like(val):
return infer_dtype_from_scalar(val, pandas_dtype=pandas_dtype)
return infer_dtype_from_array(val, pandas_dtype=pandas_dtype)
@@ -815,7 +815,7 @@ def infer_dtype_from_array(
return arr.dtype, arr
if not is_list_like(arr):
- arr = [arr]
+ raise TypeError("'arr' must be list-like")
if pandas_dtype and is_extension_array_dtype(arr):
return arr.dtype, arr
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index 445c1efae22e4..1120416eebeb9 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -10,7 +10,7 @@
from pandas._typing import ArrayLike, Axis, DtypeObj
from pandas.compat._optional import import_optional_dependency
-from pandas.core.dtypes.cast import infer_dtype_from_array
+from pandas.core.dtypes.cast import infer_dtype_from
from pandas.core.dtypes.common import (
ensure_float64,
is_integer_dtype,
@@ -40,7 +40,7 @@ def mask_missing(arr: ArrayLike, values_to_mask) -> np.ndarray:
# When called from Block.replace/replace_list, values_to_mask is a scalar
# known to be holdable by arr.
# When called from Series._single_replace, values_to_mask is tuple or list
- dtype, values_to_mask = infer_dtype_from_array(values_to_mask)
+ dtype, values_to_mask = infer_dtype_from(values_to_mask)
values_to_mask = np.array(values_to_mask, dtype=dtype)
na_mask = isna(values_to_mask)
diff --git a/pandas/tests/dtypes/cast/test_infer_dtype.py b/pandas/tests/dtypes/cast/test_infer_dtype.py
index 16fb6f327a4d5..eaf00718f4c91 100644
--- a/pandas/tests/dtypes/cast/test_infer_dtype.py
+++ b/pandas/tests/dtypes/cast/test_infer_dtype.py
@@ -141,12 +141,29 @@ def test_infer_dtype_from_scalar_errors():
@pytest.mark.parametrize(
- "arr, expected, pandas_dtype",
+ "value, expected, pandas_dtype",
[
("foo", np.object_, False),
(b"foo", np.object_, False),
- (1, np.int_, False),
+ (1, np.int64, False),
(1.5, np.float_, False),
+ (np.datetime64("2016-01-01"), np.dtype("M8[ns]"), False),
+ (Timestamp("20160101"), np.dtype("M8[ns]"), False),
+ (Timestamp("20160101", tz="UTC"), np.object_, False),
+ (Timestamp("20160101", tz="UTC"), "datetime64[ns, UTC]", True),
+ ],
+)
+def test_infer_dtype_from_scalar(value, expected, pandas_dtype):
+ dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=pandas_dtype)
+ assert is_dtype_equal(dtype, expected)
+
+ with pytest.raises(TypeError, match="must be list-like"):
+ infer_dtype_from_array(value, pandas_dtype=pandas_dtype)
+
+
+@pytest.mark.parametrize(
+ "arr, expected, pandas_dtype",
+ [
([1], np.int_, False),
(np.array([1], dtype=np.int64), np.int64, False),
([np.nan, 1, ""], np.object_, False),
@@ -155,8 +172,6 @@ def test_infer_dtype_from_scalar_errors():
(Categorical([1, 2, 3]), np.int64, False),
(Categorical(list("aabc")), "category", True),
(Categorical([1, 2, 3]), "category", True),
- (Timestamp("20160101"), np.object_, False),
- (np.datetime64("2016-01-01"), np.dtype("=M8[D]"), False),
(date_range("20160101", periods=3), np.dtype("=M8[ns]"), False),
(
date_range("20160101", periods=3, tz="US/Eastern"),
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38473 | 2020-12-14T21:41:34Z | 2020-12-22T01:03:11Z | 2020-12-22T01:03:11Z | 2020-12-22T01:03:45Z |
BUG: disallow scalar in Categorical constructor | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 64b9a11b1980d..15f4a2677bf57 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -144,6 +144,7 @@ Other API changes
Deprecations
~~~~~~~~~~~~
+- Deprecating allowing scalars passed to the :class:`Categorical` constructor (:issue:`38433`)
- Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`,:issue:`21311`,:issue:`22315`,:issue:`26974`)
-
-
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 002f36f7949e5..940c56340f75e 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -320,6 +320,16 @@ def __init__(
self._dtype = self._dtype.update_dtype(dtype)
return
+ if not is_list_like(values):
+ # GH#38433
+ warn(
+ "Allowing scalars in the Categorical constructor is deprecated "
+ "and will raise in a future version. Use `[value]` instead",
+ FutureWarning,
+ stacklevel=2,
+ )
+ values = [values]
+
# null_mask indicates missing values we want to exclude from inference.
# This means: only missing values in list-likes (not arrays/ndframes).
null_mask = np.array(False)
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py
index 59d4700874810..924a20c7e6490 100644
--- a/pandas/tests/arrays/categorical/test_constructors.py
+++ b/pandas/tests/arrays/categorical/test_constructors.py
@@ -26,6 +26,11 @@
class TestCategoricalConstructors:
+ def test_categorical_scalar_deprecated(self):
+ # GH#38433
+ with tm.assert_produces_warning(FutureWarning):
+ Categorical("A", categories=["A", "B"])
+
def test_validate_ordered(self):
# see gh-14058
exp_msg = "'ordered' must either be 'True' or 'False'"
@@ -202,13 +207,13 @@ def test_constructor(self):
assert len(cat.codes) == 1
assert cat.codes[0] == 0
- # Scalars should be converted to lists
- cat = Categorical(1)
+ with tm.assert_produces_warning(FutureWarning):
+ # GH#38433
+ cat = Categorical(1)
assert len(cat.categories) == 1
assert cat.categories[0] == 1
assert len(cat.codes) == 1
assert cat.codes[0] == 0
-
# two arrays
# - when the first is an integer dtype and the second is not
# - when the resulting codes are all -1/NaN
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index 4a0fb8f81ed56..493cb979494c8 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -223,7 +223,7 @@ def test_cast_category_to_extension_dtype(self, expected):
)
def test_consistent_casting(self, dtype, expected):
# GH 28448
- result = Categorical("2015-01-01").astype(dtype)
+ result = Categorical(["2015-01-01"]).astype(dtype)
assert result == expected
diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py
index 6db226eb14a22..d2d564be88942 100644
--- a/pandas/tests/series/methods/test_replace.py
+++ b/pandas/tests/series/methods/test_replace.py
@@ -290,7 +290,7 @@ def test_replace_mixed_types_with_string(self):
@pytest.mark.parametrize(
"categorical, numeric",
[
- (pd.Categorical("A", categories=["A", "B"]), [1]),
+ (pd.Categorical(["A"], categories=["A", "B"]), [1]),
(pd.Categorical(("A",), categories=["A", "B"]), [1]),
(pd.Categorical(("A", "B"), categories=["A", "B"]), [1, 2]),
],
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 35411d7e9cfb7..4aca967d71111 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -908,8 +908,8 @@ def test_categorical_from_codes(self):
# GH 16639
vals = np.array([0, 1, 2, 0])
cats = ["a", "b", "c"]
- Sd = Series(Categorical(1).from_codes(vals, cats))
- St = Series(Categorical(1).from_codes(np.array([0, 1]), cats))
+ Sd = Series(Categorical([1]).from_codes(vals, cats))
+ St = Series(Categorical([1]).from_codes(np.array([0, 1]), cats))
expected = np.array([True, True, False, True])
result = algos.isin(Sd, St)
tm.assert_numpy_array_equal(expected, result)
@@ -917,8 +917,8 @@ def test_categorical_from_codes(self):
def test_categorical_isin(self):
vals = np.array([0, 1, 2, 0])
cats = ["a", "b", "c"]
- cat = Categorical(1).from_codes(vals, cats)
- other = Categorical(1).from_codes(np.array([0, 1]), cats)
+ cat = Categorical([1]).from_codes(vals, cats)
+ other = Categorical([1]).from_codes(np.array([0, 1]), cats)
expected = np.array([True, True, False, True])
result = algos.isin(cat, other)
| - [x] closes #38433
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38472 | 2020-12-14T21:35:02Z | 2020-12-23T18:44:29Z | 2020-12-23T18:44:29Z | 2020-12-23T19:18:59Z |
DOC: fixes for assert_frame_equal check_freq argument | diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst
index a1612117072a5..b1f8389420cd9 100644
--- a/doc/source/whatsnew/v1.2.1.rst
+++ b/doc/source/whatsnew/v1.2.1.rst
@@ -10,6 +10,20 @@ including other versions of pandas.
.. ---------------------------------------------------------------------------
+.. _whatsnew_121.api_breaking:
+
+Backwards incompatible API changes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. _whatsnew_121.api_breaking.testing.assert_frame_equal:
+
+Added ``check_freq`` argument to ``testing.assert_frame_equal``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``check_freq`` argument was added to :func:`testing.assert_frame_equal` in pandas 1.1.0 and defaults to ``True``. :func:`testing.assert_frame_equal` now raises ``AssertionError`` if the indexes do not have the same frequency. Before pandas 1.1.0, the index frequency was not checked by :func:`testing.assert_frame_equal`.
+
+.. ---------------------------------------------------------------------------
+
.. _whatsnew_121.regressions:
Fixed regressions
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index ba4410bd95940..13115d6b959d9 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -1128,6 +1128,8 @@ def assert_frame_equal(
(same as in columns) - same labels must be with the same data.
check_freq : bool, default True
Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex.
+
+ .. versionadded:: 1.1.0
check_flags : bool, default True
Whether to check the `flags` attribute.
rtol : float, default 1e-5
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
This is just a minor documentation change to fix the `versionadded` tag on the `check_freq` argument to `assert_frame_equal` and also to add a description of this backwards incompatible chage to the 1.1.0 Whats New (as recommended in https://github.com/pandas-dev/pandas/issues/35570#issuecomment-674064533). | https://api.github.com/repos/pandas-dev/pandas/pulls/38471 | 2020-12-14T21:12:10Z | 2021-01-01T23:10:06Z | 2021-01-01T23:10:05Z | 2021-01-03T01:38:30Z |
TYP : DataFrame.(merge, join) core.reshape.merge.(merge, ...) (easy) | diff --git a/pandas/_typing.py b/pandas/_typing.py
index 924fc323584b0..99c46d21844f3 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -95,6 +95,7 @@
IndexLabel = Union[Label, Sequence[Label]]
Level = Union[Label, int]
Shape = Tuple[int, ...]
+Suffixes = Tuple[str, str]
Ordered = Optional[bool]
JSONSerializable = Optional[Union[PythonScalar, List, Dict]]
Axes = Collection
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index f79e459362d7b..1bf40f782f666 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -59,10 +59,12 @@
FormattersType,
FrameOrSeriesUnion,
IndexKeyFunc,
+ IndexLabel,
Label,
Level,
Renamer,
StorageOptions,
+ Suffixes,
ValueKeyFunc,
)
from pandas.compat._optional import import_optional_dependency
@@ -8028,8 +8030,8 @@ def append(
def join(
self,
- other,
- on=None,
+ other: FrameOrSeriesUnion,
+ on: Optional[IndexLabel] = None,
how: str = "left",
lsuffix: str = "",
rsuffix: str = "",
@@ -8157,7 +8159,13 @@ def join(
)
def _join_compat(
- self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False
+ self,
+ other: FrameOrSeriesUnion,
+ on: Optional[IndexLabel] = None,
+ how: str = "left",
+ lsuffix: str = "",
+ rsuffix: str = "",
+ sort: bool = False,
):
from pandas.core.reshape.concat import concat
from pandas.core.reshape.merge import merge
@@ -8222,18 +8230,18 @@ def _join_compat(
@Appender(_merge_doc, indents=2)
def merge(
self,
- right,
- how="inner",
- on=None,
- left_on=None,
- right_on=None,
- left_index=False,
- right_index=False,
- sort=False,
- suffixes=("_x", "_y"),
- copy=True,
- indicator=False,
- validate=None,
+ right: FrameOrSeriesUnion,
+ how: str = "inner",
+ on: Optional[IndexLabel] = None,
+ left_on: Optional[IndexLabel] = None,
+ right_on: Optional[IndexLabel] = None,
+ left_index: bool = False,
+ right_index: bool = False,
+ sort: bool = False,
+ suffixes: Suffixes = ("_x", "_y"),
+ copy: bool = True,
+ indicator: bool = False,
+ validate: Optional[str] = None,
) -> DataFrame:
from pandas.core.reshape.merge import merge
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 2c6cdb846221f..ebdfff5227026 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -13,7 +13,13 @@
import numpy as np
from pandas._libs import Timedelta, hashtable as libhashtable, join as libjoin, lib
-from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion
+from pandas._typing import (
+ ArrayLike,
+ FrameOrSeries,
+ FrameOrSeriesUnion,
+ IndexLabel,
+ Suffixes,
+)
from pandas.errors import MergeError
from pandas.util._decorators import Appender, Substitution
@@ -57,19 +63,19 @@
@Substitution("\nleft : DataFrame")
@Appender(_merge_doc, indents=0)
def merge(
- left,
- right,
+ left: FrameOrSeriesUnion,
+ right: FrameOrSeriesUnion,
how: str = "inner",
- on=None,
- left_on=None,
- right_on=None,
+ on: Optional[IndexLabel] = None,
+ left_on: Optional[IndexLabel] = None,
+ right_on: Optional[IndexLabel] = None,
left_index: bool = False,
right_index: bool = False,
sort: bool = False,
- suffixes=("_x", "_y"),
+ suffixes: Suffixes = ("_x", "_y"),
copy: bool = True,
indicator: bool = False,
- validate=None,
+ validate: Optional[str] = None,
) -> "DataFrame":
op = _MergeOperation(
left,
@@ -151,15 +157,15 @@ def _groupby_and_merge(by, on, left: "DataFrame", right: "DataFrame", merge_piec
def merge_ordered(
- left,
- right,
- on=None,
- left_on=None,
- right_on=None,
+ left: "DataFrame",
+ right: "DataFrame",
+ on: Optional[IndexLabel] = None,
+ left_on: Optional[IndexLabel] = None,
+ right_on: Optional[IndexLabel] = None,
left_by=None,
right_by=None,
- fill_method=None,
- suffixes=("_x", "_y"),
+ fill_method: Optional[str] = None,
+ suffixes: Suffixes = ("_x", "_y"),
how: str = "outer",
) -> "DataFrame":
"""
@@ -294,17 +300,17 @@ def _merger(x, y):
def merge_asof(
- left,
- right,
- on=None,
- left_on=None,
- right_on=None,
+ left: "DataFrame",
+ right: "DataFrame",
+ on: Optional[IndexLabel] = None,
+ left_on: Optional[IndexLabel] = None,
+ right_on: Optional[IndexLabel] = None,
left_index: bool = False,
right_index: bool = False,
by=None,
left_by=None,
right_by=None,
- suffixes=("_x", "_y"),
+ suffixes: Suffixes = ("_x", "_y"),
tolerance=None,
allow_exact_matches: bool = True,
direction: str = "backward",
@@ -583,17 +589,17 @@ def __init__(
left: FrameOrSeriesUnion,
right: FrameOrSeriesUnion,
how: str = "inner",
- on=None,
- left_on=None,
- right_on=None,
- axis=1,
+ on: Optional[IndexLabel] = None,
+ left_on: Optional[IndexLabel] = None,
+ right_on: Optional[IndexLabel] = None,
+ axis: int = 1,
left_index: bool = False,
right_index: bool = False,
sort: bool = True,
- suffixes=("_x", "_y"),
+ suffixes: Suffixes = ("_x", "_y"),
copy: bool = True,
indicator: bool = False,
- validate=None,
+ validate: Optional[str] = None,
):
_left = _validate_operand(left)
_right = _validate_operand(right)
@@ -1224,7 +1230,7 @@ def _maybe_coerce_merge_keys(self):
self.right = self.right.assign(**{name: self.right[name].astype(typ)})
def _create_cross_configuration(
- self, left, right
+ self, left: "DataFrame", right: "DataFrame"
) -> Tuple["DataFrame", "DataFrame", str, str]:
"""
Creates the configuration to dispatch the cross operation to inner join,
@@ -1540,17 +1546,17 @@ class _OrderedMerge(_MergeOperation):
def __init__(
self,
- left,
- right,
- on=None,
- left_on=None,
- right_on=None,
+ left: "DataFrame",
+ right: "DataFrame",
+ on: Optional[IndexLabel] = None,
+ left_on: Optional[IndexLabel] = None,
+ right_on: Optional[IndexLabel] = None,
left_index: bool = False,
right_index: bool = False,
- axis=1,
- suffixes=("_x", "_y"),
+ axis: int = 1,
+ suffixes: Suffixes = ("_x", "_y"),
copy: bool = True,
- fill_method=None,
+ fill_method: Optional[str] = None,
how: str = "outer",
):
@@ -1634,20 +1640,20 @@ class _AsOfMerge(_OrderedMerge):
def __init__(
self,
- left,
- right,
- on=None,
- left_on=None,
- right_on=None,
+ left: "DataFrame",
+ right: "DataFrame",
+ on: Optional[IndexLabel] = None,
+ left_on: Optional[IndexLabel] = None,
+ right_on: Optional[IndexLabel] = None,
left_index: bool = False,
right_index: bool = False,
by=None,
left_by=None,
right_by=None,
- axis=1,
- suffixes=("_x", "_y"),
+ axis: int = 1,
+ suffixes: Suffixes = ("_x", "_y"),
copy: bool = True,
- fill_method=None,
+ fill_method: Optional[str] = None,
how: str = "asof",
tolerance=None,
allow_exact_matches: bool = True,
@@ -2150,7 +2156,7 @@ def _validate_operand(obj: FrameOrSeries) -> "DataFrame":
)
-def _items_overlap_with_suffix(left: Index, right: Index, suffixes: Tuple[str, str]):
+def _items_overlap_with_suffix(left: Index, right: Index, suffixes: Suffixes):
"""
Suffixes type validation.
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38468 | 2020-12-14T18:46:35Z | 2020-12-16T00:55:18Z | 2020-12-16T00:55:18Z | 2020-12-16T01:09:31Z |
CLN: unnecessary checks | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 0a2ef2fb29b96..27110fe1f8439 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -321,7 +321,7 @@ def __init__(
if is_categorical_dtype(values):
if dtype.categories is None:
dtype = CategoricalDtype(values.categories, dtype.ordered)
- elif not isinstance(values, (ABCIndex, ABCSeries)):
+ elif not isinstance(values, (ABCIndex, ABCSeries, ExtensionArray)):
# sanitize_array coerces np.nan to a string under certain versions
# of numpy
values = maybe_infer_to_datetimelike(values, convert_dates=True)
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 3274725016b40..9ffd8246d390b 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -80,11 +80,8 @@
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
- ABCDatetimeArray,
- ABCDatetimeIndex,
ABCExtensionArray,
- ABCPeriodArray,
- ABCPeriodIndex,
+ ABCIndex,
ABCSeries,
)
from pandas.core.dtypes.inference import is_list_like
@@ -1252,11 +1249,9 @@ def maybe_infer_to_datetimelike(
leave inferred dtype 'date' alone
"""
- # TODO: why not timedelta?
- if isinstance(
- value, (ABCDatetimeIndex, ABCPeriodIndex, ABCDatetimeArray, ABCPeriodArray)
- ):
- return value
+ if isinstance(value, (ABCIndex, ABCExtensionArray)):
+ if not is_object_dtype(value.dtype):
+ raise ValueError("array-like value must be object-dtype")
v = value
@@ -1431,7 +1426,7 @@ def maybe_cast_to_datetime(value, dtype: Optional[DtypeObj]):
value = to_timedelta(value, errors="raise")._values
except OutOfBoundsDatetime:
raise
- except (AttributeError, ValueError, TypeError):
+ except (ValueError, TypeError):
pass
# coerce datetimelike to object
diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py
index a971122bb5c45..9e0d20e3de4e4 100644
--- a/pandas/core/internals/construction.py
+++ b/pandas/core/internals/construction.py
@@ -212,7 +212,7 @@ def init_ndarray(values, index, columns, dtype: Optional[DtypeObj], copy: bool):
# if we don't have a dtype specified, then try to convert objects
# on the entire block; this is to convert if we have datetimelike's
# embedded in an object type
- if dtype is None and is_object_dtype(values):
+ if dtype is None and is_object_dtype(values.dtype):
if values.ndim == 2 and values.shape[0] != 1:
# transpose and separate blocks
| https://api.github.com/repos/pandas-dev/pandas/pulls/38467 | 2020-12-14T17:57:27Z | 2020-12-14T20:36:56Z | 2020-12-14T20:36:56Z | 2020-12-14T21:18:13Z | |
CLN: astype_nansafe require dtype object | diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 8268ebb48a017..575ae7531de2c 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -1061,7 +1061,7 @@ def astype(self, dtype=None, copy=True):
else:
return self.copy()
dtype = self.dtype.update_dtype(dtype)
- subtype = dtype._subtype_with_str
+ subtype = pandas_dtype(dtype._subtype_with_str)
# TODO copy=False is broken for astype_nansafe with int -> float, so cannot
# passthrough copy keyword: https://github.com/pandas-dev/pandas/issues/34456
sp_values = astype_nansafe(self.sp_values, subtype, copy=True)
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 3274725016b40..829ae3dddfa00 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -70,7 +70,6 @@
is_timedelta64_dtype,
is_timedelta64_ns_dtype,
is_unsigned_integer_dtype,
- pandas_dtype,
)
from pandas.core.dtypes.dtypes import (
DatetimeTZDtype,
@@ -965,7 +964,7 @@ def astype_nansafe(
Parameters
----------
arr : ndarray
- dtype : np.dtype
+ dtype : np.dtype or ExtensionDtype
copy : bool, default True
If False, a view will be attempted but may fail, if
e.g. the item sizes don't align.
@@ -978,11 +977,11 @@ def astype_nansafe(
The dtype was a datetime64/timedelta64 dtype, but it had no unit.
"""
# dispatch on extension dtype if needed
- if is_extension_array_dtype(dtype):
+ if isinstance(dtype, ExtensionDtype):
return dtype.construct_array_type()._from_sequence(arr, dtype=dtype, copy=copy)
- if not isinstance(dtype, np.dtype):
- dtype = pandas_dtype(dtype)
+ elif not isinstance(dtype, np.dtype):
+ raise ValueError("dtype must be np.dtype or ExtensionDtype")
if issubclass(dtype.type, str):
return lib.ensure_string_array(
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index d99a57143dae2..d670821c98520 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -1714,6 +1714,7 @@ def _convert_to_ndarrays(
except (AttributeError, TypeError):
# invalid input to is_bool_dtype
pass
+ cast_type = pandas_dtype(cast_type)
cvals = self._cast_types(cvals, cast_type, c)
result[c] = cvals
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py
index 19d80b714a674..0d0601aa542b4 100644
--- a/pandas/tests/dtypes/test_common.py
+++ b/pandas/tests/dtypes/test_common.py
@@ -716,6 +716,8 @@ def test__is_dtype_type(input_param, result):
def test_astype_nansafe(val, typ):
arr = np.array([val])
+ typ = np.dtype(typ)
+
msg = "Cannot convert NaT values to integer"
with pytest.raises(ValueError, match=msg):
astype_nansafe(arr, dtype=typ)
@@ -738,6 +740,8 @@ def test_astype_nansafe(val, typ):
def test_astype_datetime64_bad_dtype_raises(from_type, to_type):
arr = np.array([from_type("2018")])
+ to_type = np.dtype(to_type)
+
with pytest.raises(TypeError, match="cannot astype"):
astype_nansafe(arr, dtype=to_type)
@@ -745,7 +749,7 @@ def test_astype_datetime64_bad_dtype_raises(from_type, to_type):
@pytest.mark.parametrize("from_type", [np.datetime64, np.timedelta64])
def test_astype_object_preserves_datetime_na(from_type):
arr = np.array([from_type("NaT")])
- result = astype_nansafe(arr, dtype="object")
+ result = astype_nansafe(arr, dtype=np.dtype("object"))
assert isna(result)[0]
| https://api.github.com/repos/pandas-dev/pandas/pulls/38466 | 2020-12-14T17:51:30Z | 2020-12-14T20:37:09Z | 2020-12-14T20:37:09Z | 2020-12-14T21:17:53Z | |
Backport PR #38427 on branch 1.2.x (REGR: Assigning label with registered EA dtype raises) | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 4906288cc07d9..e2521cedb64cc 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -858,7 +858,7 @@ Other
- Bug in :meth:`Index.drop` raising ``InvalidIndexError`` when index has duplicates (:issue:`38051`)
- Bug in :meth:`RangeIndex.difference` returning :class:`Int64Index` in some cases where it should return :class:`RangeIndex` (:issue:`38028`)
- Fixed bug in :func:`assert_series_equal` when comparing a datetime-like array with an equivalent non extension dtype array (:issue:`37609`)
-
+- Bug in :func:`.is_bool_dtype` would raise when passed a valid string such as ``"boolean"`` (:issue:`38386`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index b4f6d587c6642..d8b0ad739b056 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -1397,7 +1397,7 @@ def is_bool_dtype(arr_or_dtype) -> bool:
# guess this
return arr_or_dtype.is_object and arr_or_dtype.inferred_type == "boolean"
elif is_extension_array_dtype(arr_or_dtype):
- return getattr(arr_or_dtype, "dtype", arr_or_dtype)._is_boolean
+ return getattr(dtype, "_is_boolean", False)
return issubclass(dtype.type, np.bool_)
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 44d3c8de0ae23..fcbf7ec3897fc 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -1689,9 +1689,8 @@ def _convert_to_ndarrays(
values, set(col_na_values) | col_na_fvalues, try_num_bool=False
)
else:
- is_str_or_ea_dtype = is_string_dtype(
- cast_type
- ) or is_extension_array_dtype(cast_type)
+ is_ea = is_extension_array_dtype(cast_type)
+ is_str_or_ea_dtype = is_ea or is_string_dtype(cast_type)
# skip inference if specified dtype is object
# or casting to an EA
try_num_bool = not (cast_type and is_str_or_ea_dtype)
@@ -1706,16 +1705,15 @@ def _convert_to_ndarrays(
not is_dtype_equal(cvals, cast_type)
or is_extension_array_dtype(cast_type)
):
- try:
- if (
- is_bool_dtype(cast_type)
- and not is_categorical_dtype(cast_type)
- and na_count > 0
- ):
- raise ValueError(f"Bool column has NA values in column {c}")
- except (AttributeError, TypeError):
- # invalid input to is_bool_dtype
- pass
+ if not is_ea and na_count > 0:
+ try:
+ if is_bool_dtype(cast_type):
+ raise ValueError(
+ f"Bool column has NA values in column {c}"
+ )
+ except (AttributeError, TypeError):
+ # invalid input to is_bool_dtype
+ pass
cvals = self._cast_types(cvals, cast_type, c)
result[c] = cvals
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py
index ce6737db44195..19d80b714a674 100644
--- a/pandas/tests/dtypes/test_common.py
+++ b/pandas/tests/dtypes/test_common.py
@@ -545,6 +545,7 @@ def test_is_bool_dtype():
assert not com.is_bool_dtype(pd.Series([1, 2]))
assert not com.is_bool_dtype(np.array(["a", "b"]))
assert not com.is_bool_dtype(pd.Index(["a", "b"]))
+ assert not com.is_bool_dtype("Int64")
assert com.is_bool_dtype(bool)
assert com.is_bool_dtype(np.bool_)
@@ -553,6 +554,7 @@ def test_is_bool_dtype():
assert com.is_bool_dtype(pd.BooleanDtype())
assert com.is_bool_dtype(pd.array([True, False, None], dtype="boolean"))
+ assert com.is_bool_dtype("boolean")
@pytest.mark.filterwarnings("ignore:'is_extension_type' is deprecated:FutureWarning")
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 884cb6c20b77e..19d2f8301037a 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -1,6 +1,7 @@
import numpy as np
import pytest
+from pandas.core.dtypes.base import registry as ea_registry
from pandas.core.dtypes.dtypes import DatetimeTZDtype, IntervalDtype, PeriodDtype
from pandas import (
@@ -197,6 +198,25 @@ def test_setitem_extension_types(self, obj, dtype):
tm.assert_frame_equal(df, expected)
+ @pytest.mark.parametrize(
+ "ea_name",
+ [
+ dtype.name
+ for dtype in ea_registry.dtypes
+ # property would require instantiation
+ if not isinstance(dtype.name, property)
+ ]
+ # mypy doesn't allow adding lists of different types
+ # https://github.com/python/mypy/issues/5492
+ + ["datetime64[ns, UTC]", "period[D]"], # type: ignore[list-item]
+ )
+ def test_setitem_with_ea_name(self, ea_name):
+ # GH 38386
+ result = DataFrame([0])
+ result[ea_name] = [1]
+ expected = DataFrame({0: [0], ea_name: [1]})
+ tm.assert_frame_equal(result, expected)
+
def test_setitem_dt64_ndarray_with_NaT_and_diff_time_units(self):
# GH#7492
data_ns = np.array([1, "nat"], dtype="datetime64[ns]")
| Backport PR #38427: REGR: Assigning label with registered EA dtype raises | https://api.github.com/repos/pandas-dev/pandas/pulls/38464 | 2020-12-14T14:11:32Z | 2020-12-14T16:11:17Z | 2020-12-14T16:11:17Z | 2020-12-14T16:11:17Z |
Update 10min.rst | diff --git a/doc/source/user_guide/10min.rst b/doc/source/user_guide/10min.rst
index cf548ba5d1133..e37d4cc05c8c7 100644
--- a/doc/source/user_guide/10min.rst
+++ b/doc/source/user_guide/10min.rst
@@ -722,6 +722,8 @@ We use the standard convention for referencing the matplotlib API:
plt.close("all")
+The :meth:`~plt.close` method is used to `close <https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.close.html>`__ a figure window.
+
.. ipython:: python
ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
| Added Links for Matplotlib Close along with a line explaining what it does.
I had faced difficulty when I read it for the first time and had to google search what close does
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38462 | 2020-12-14T12:59:39Z | 2020-12-14T20:38:03Z | 2020-12-14T20:38:03Z | 2020-12-15T04:31:51Z |
TYP: DataFrame.to_gbq, DataFrame.to_html (easy: copy-paste from format module) | diff --git a/pandas/_typing.py b/pandas/_typing.py
index 09c490e64957d..924fc323584b0 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -146,5 +146,12 @@
CompressionOptions = Optional[Union[str, CompressionDict]]
-# type of float formatter in DataFrameFormatter
+# types in DataFrameFormatter
+FormattersType = Union[
+ List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable]
+]
+ColspaceType = Mapping[Label, Union[str, int]]
FloatFormatType = Union[str, Callable, "EngFormatter"]
+ColspaceArgType = Union[
+ str, int, Sequence[Union[str, int]], Mapping[Label, Union[str, int]]
+]
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 0dff1305357b2..d698edbb0b8ad 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -51,9 +51,12 @@
ArrayLike,
Axes,
Axis,
+ ColspaceArgType,
CompressionOptions,
Dtype,
FilePathOrBuffer,
+ FloatFormatType,
+ FormattersType,
FrameOrSeriesUnion,
IndexKeyFunc,
Label,
@@ -1612,11 +1615,11 @@ def to_gbq(
self,
destination_table: str,
project_id: Optional[str] = None,
- chunksize=None,
+ chunksize: Optional[int] = None,
reauth: bool = False,
if_exists: str = "fail",
auth_local_webserver: bool = False,
- table_schema=None,
+ table_schema: Optional[List[Dict[str, str]]] = None,
location: Optional[str] = None,
progress_bar: bool = True,
credentials=None,
@@ -2474,29 +2477,29 @@ def to_parquet(
@Substitution(shared_params=fmt.common_docstring, returns=fmt.return_docstring)
def to_html(
self,
- buf=None,
- columns=None,
- col_space=None,
- header=True,
- index=True,
- na_rep="NaN",
- formatters=None,
- float_format=None,
- sparsify=None,
- index_names=True,
- justify=None,
- max_rows=None,
- max_cols=None,
- show_dimensions=False,
+ buf: Optional[FilePathOrBuffer[str]] = None,
+ columns: Optional[Sequence[str]] = None,
+ col_space: Optional[ColspaceArgType] = None,
+ header: Union[bool, Sequence[str]] = True,
+ index: bool = True,
+ na_rep: str = "NaN",
+ formatters: Optional[FormattersType] = None,
+ float_format: Optional[FloatFormatType] = None,
+ sparsify: Optional[bool] = None,
+ index_names: bool = True,
+ justify: Optional[str] = None,
+ max_rows: Optional[int] = None,
+ max_cols: Optional[int] = None,
+ show_dimensions: Union[bool, str] = False,
decimal: str = ".",
- bold_rows=True,
- classes=None,
- escape=True,
- notebook=False,
- border=None,
- table_id=None,
- render_links=False,
- encoding=None,
+ bold_rows: bool = True,
+ classes: Optional[Union[str, List, Tuple]] = None,
+ escape: bool = True,
+ notebook: bool = False,
+ border: Optional[int] = None,
+ table_id: Optional[str] = None,
+ render_links: bool = False,
+ encoding: Optional[str] = None,
):
"""
Render a DataFrame as an HTML table.
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index db34b882a3c35..527ee51873631 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -39,9 +39,12 @@
from pandas._libs.tslibs.nattype import NaTType
from pandas._typing import (
ArrayLike,
+ ColspaceArgType,
+ ColspaceType,
CompressionOptions,
FilePathOrBuffer,
FloatFormatType,
+ FormattersType,
IndexLabel,
Label,
StorageOptions,
@@ -81,14 +84,6 @@
from pandas import Categorical, DataFrame, Series
-FormattersType = Union[
- List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable]
-]
-ColspaceType = Mapping[Label, Union[str, int]]
-ColspaceArgType = Union[
- str, int, Sequence[Union[str, int]], Mapping[Label, Union[str, int]]
-]
-
common_docstring = """
Parameters
----------
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Spinning off from #38416 | https://api.github.com/repos/pandas-dev/pandas/pulls/38461 | 2020-12-14T04:28:12Z | 2020-12-14T14:24:42Z | 2020-12-14T14:24:42Z | 2020-12-14T15:43:46Z |
REF: roll DatetimeBlock.astype into Block._astype | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 031d28b19b138..b9558daf05ad2 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -654,6 +654,16 @@ def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike:
return Categorical(values, dtype=dtype)
+ elif is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype):
+ # if we are passed a datetime64[ns, tz]
+ if copy:
+ # this should be the only copy
+ values = values.copy()
+ # i.e. values.tz_localize("UTC").tz_convert(dtype.tz)
+ # FIXME: GH#33401 this doesn't match DatetimeArray.astype, which
+ # would be self.array_values().tz_localize(dtype.tz)
+ return DatetimeArray._simple_new(values.view("i8"), dtype=dtype)
+
if is_dtype_equal(values.dtype, dtype):
if copy:
return values.copy()
@@ -2237,25 +2247,6 @@ def _maybe_coerce_values(self, values):
assert isinstance(values, np.ndarray), type(values)
return values
- def astype(self, dtype, copy: bool = False, errors: str = "raise"):
- """
- these automatically copy, so copy=True has no effect
- raise on an except if raise == True
- """
- dtype = pandas_dtype(dtype)
-
- # if we are passed a datetime64[ns, tz]
- if is_datetime64tz_dtype(dtype):
- values = self.values
- if copy:
- # this should be the only copy
- values = values.copy()
- values = DatetimeArray._simple_new(values.view("i8"), dtype=dtype)
- return self.make_block(values)
-
- # delegate
- return super().astype(dtype=dtype, copy=copy, errors=errors)
-
def _can_hold_element(self, element: Any) -> bool:
tipo = maybe_infer_dtype_type(element)
if tipo is not None:
| Anything past this requires getting a handle on #36153. | https://api.github.com/repos/pandas-dev/pandas/pulls/38460 | 2020-12-14T04:13:09Z | 2020-12-14T14:18:16Z | 2020-12-14T14:18:16Z | 2021-11-20T23:21:31Z |
REF: simplify _sanitize_column | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index d698edbb0b8ad..4cc7a21ad2964 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3160,6 +3160,8 @@ def __setitem__(self, key, value):
self._setitem_frame(key, value)
elif isinstance(key, (Series, np.ndarray, list, Index)):
self._setitem_array(key, value)
+ elif isinstance(value, DataFrame):
+ self._set_item_frame_value(key, value)
else:
# set column
self._set_item(key, value)
@@ -3213,15 +3215,47 @@ def _setitem_frame(self, key, value):
self._check_setitem_copy()
self._where(-key, value, inplace=True)
+ def _set_item_frame_value(self, key, value: "DataFrame") -> None:
+ self._ensure_valid_index(value)
+
+ # align right-hand-side columns if self.columns
+ # is multi-index and self[key] is a sub-frame
+ if isinstance(self.columns, MultiIndex) and key in self.columns:
+ loc = self.columns.get_loc(key)
+ if isinstance(loc, (slice, Series, np.ndarray, Index)):
+ cols = maybe_droplevels(self.columns[loc], key)
+ if len(cols) and not cols.equals(value.columns):
+ value = value.reindex(cols, axis=1)
+
+ # now align rows
+ value = _reindex_for_setitem(value, self.index)
+ value = value.T
+ self._set_item_mgr(key, value)
+
def _iset_item_mgr(self, loc: int, value) -> None:
self._mgr.iset(loc, value)
self._clear_item_cache()
- def _iset_item(self, loc: int, value, broadcast: bool = False):
+ def _set_item_mgr(self, key, value):
+ value = _maybe_atleast_2d(value)
+
+ try:
+ loc = self._info_axis.get_loc(key)
+ except KeyError:
+ # This item wasn't present, just insert at end
+ self._mgr.insert(len(self._info_axis), key, value)
+ else:
+ self._iset_item_mgr(loc, value)
+
+ # check if we are modifying a copy
+ # try to set first as we want an invalid
+ # value exception to occur first
+ if len(self):
+ self._check_setitem_copy()
- # technically _sanitize_column expects a label, not a position,
- # but the behavior is the same as long as we pass broadcast=False
- value = self._sanitize_column(loc, value, broadcast=broadcast)
+ def _iset_item(self, loc: int, value):
+ value = self._sanitize_column(value)
+ value = _maybe_atleast_2d(value)
self._iset_item_mgr(loc, value)
# check if we are modifying a copy
@@ -3240,21 +3274,20 @@ def _set_item(self, key, value):
Series/TimeSeries will be conformed to the DataFrames index to
ensure homogeneity.
"""
- value = self._sanitize_column(key, value)
+ value = self._sanitize_column(value)
- try:
- loc = self._info_axis.get_loc(key)
- except KeyError:
- # This item wasn't present, just insert at end
- self._mgr.insert(len(self._info_axis), key, value)
- else:
- self._iset_item_mgr(loc, value)
+ if (
+ key in self.columns
+ and value.ndim == 1
+ and not is_extension_array_dtype(value)
+ ):
+ # broadcast across multiple columns if necessary
+ if not self.columns.is_unique or isinstance(self.columns, MultiIndex):
+ existing_piece = self[key]
+ if isinstance(existing_piece, DataFrame):
+ value = np.tile(value, (len(existing_piece.columns), 1))
- # check if we are modifying a copy
- # try to set first as we want an invalid
- # value exception to occur first
- if len(self):
- self._check_setitem_copy()
+ self._set_item_mgr(key, value)
def _set_value(self, index, col, value, takeable: bool = False):
"""
@@ -3788,7 +3821,8 @@ def insert(self, loc, column, value, allow_duplicates: bool = False) -> None:
"Cannot specify 'allow_duplicates=True' when "
"'self.flags.allows_duplicate_labels' is False."
)
- value = self._sanitize_column(column, value, broadcast=False)
+ value = self._sanitize_column(value)
+ value = _maybe_atleast_2d(value)
self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
def assign(self, **kwargs) -> DataFrame:
@@ -3859,20 +3893,14 @@ def assign(self, **kwargs) -> DataFrame:
data[k] = com.apply_if_callable(v, data)
return data
- def _sanitize_column(self, key, value, broadcast: bool = True):
+ def _sanitize_column(self, value):
"""
Ensures new columns (which go into the BlockManager as new blocks) are
always copied and converted into an array.
Parameters
----------
- key : object
value : scalar, Series, or array-like
- broadcast : bool, default True
- If ``key`` matches multiple duplicate column names in the
- DataFrame, this parameter indicates whether ``value`` should be
- tiled so that the returned array contains a (duplicated) column for
- each occurrence of the key. If False, ``value`` will not be tiled.
Returns
-------
@@ -3880,42 +3908,9 @@ def _sanitize_column(self, key, value, broadcast: bool = True):
"""
self._ensure_valid_index(value)
- def reindexer(value):
- # reindex if necessary
-
- if value.index.equals(self.index) or not len(self.index):
- value = value._values.copy()
- else:
-
- # GH 4107
- try:
- value = value.reindex(self.index)._values
- except ValueError as err:
- # raised in MultiIndex.from_tuples, see test_insert_error_msmgs
- if not value.index.is_unique:
- # duplicate axis
- raise err
-
- # other
- raise TypeError(
- "incompatible index of inserted column with frame index"
- ) from err
- return value
-
+ # We should never get here with DataFrame value
if isinstance(value, Series):
- value = reindexer(value)
-
- elif isinstance(value, DataFrame):
- # align right-hand-side columns if self.columns
- # is multi-index and self[key] is a sub-frame
- if isinstance(self.columns, MultiIndex) and key in self.columns:
- loc = self.columns.get_loc(key)
- if isinstance(loc, (slice, Series, np.ndarray, Index)):
- cols = maybe_droplevels(self.columns[loc], key)
- if len(cols) and not cols.equals(value.columns):
- value = value.reindex(cols, axis=1)
- # now align rows
- value = reindexer(value).T
+ value = _reindex_for_setitem(value, self.index)
elif isinstance(value, ExtensionArray):
# Explicitly copy here, instead of in sanitize_index,
@@ -3946,18 +3941,7 @@ def reindexer(value):
else:
value = construct_1d_arraylike_from_scalar(value, len(self), dtype=None)
- # return internal types directly
- if is_extension_array_dtype(value):
- return value
-
- # broadcast across multiple columns if necessary
- if broadcast and key in self.columns and value.ndim == 1:
- if not self.columns.is_unique or isinstance(self.columns, MultiIndex):
- existing_piece = self[key]
- if isinstance(existing_piece, DataFrame):
- value = np.tile(value, (len(existing_piece.columns), 1))
-
- return np.atleast_2d(np.asarray(value))
+ return value
@property
def _series(self):
@@ -9555,3 +9539,33 @@ def _from_nested_dict(data) -> collections.defaultdict:
for col, v in s.items():
new_data[col][index] = v
return new_data
+
+
+def _reindex_for_setitem(value, index: Index):
+ # reindex if necessary
+
+ if value.index.equals(index) or not len(index):
+ return value._values.copy()
+
+ # GH#4107
+ try:
+ value = value.reindex(index)._values
+ except ValueError as err:
+ # raised in MultiIndex.from_tuples, see test_insert_error_msmgs
+ if not value.index.is_unique:
+ # duplicate axis
+ raise err
+
+ raise TypeError(
+ "incompatible index of inserted column with frame index"
+ ) from err
+ return value
+
+
+def _maybe_atleast_2d(value):
+ # TODO(EA2D): not needed with 2D EAs
+
+ if is_extension_array_dtype(value):
+ return value
+
+ return np.atleast_2d(np.asarray(value))
| It gets called indirectly from `iloc._setitem_with_indexer`, which we're trying to simplify | https://api.github.com/repos/pandas-dev/pandas/pulls/38459 | 2020-12-14T04:08:07Z | 2020-12-14T17:59:46Z | 2020-12-14T17:59:46Z | 2020-12-14T18:01:21Z |
Backport PR #38141 on branch 1.2.x (BUG: do not stringify file-like objects) | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index bc7f5b8174573..4906288cc07d9 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -746,6 +746,7 @@ I/O
- :meth:`read_fwf` was inferring compression with ``compression=None`` which was not consistent with the other :meth:``read_*`` functions (:issue:`37909`)
- :meth:`DataFrame.to_html` was ignoring ``formatters`` argument for ``ExtensionDtype`` columns (:issue:`36525`)
- Bumped minimum xarray version to 0.12.3 to avoid reference to the removed ``Panel`` class (:issue:`27101`)
+- :meth:`DataFrame.to_csv` was re-opening file-like handles that also implement ``os.PathLike`` (:issue:`38125`)
Period
^^^^^^
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 9fede5180e727..64c5d3173fe0a 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -152,6 +152,7 @@ def validate_header_arg(header) -> None:
def stringify_path(
filepath_or_buffer: FilePathOrBuffer[AnyStr],
+ convert_file_like: bool = False,
) -> FileOrBuffer[AnyStr]:
"""
Attempt to convert a path-like object to a string.
@@ -169,12 +170,15 @@ def stringify_path(
Objects supporting the fspath protocol (python 3.6+) are coerced
according to its __fspath__ method.
- For backwards compatibility with older pythons, pathlib.Path and
- py.path objects are specially coerced.
-
Any other object is passed through unchanged, which includes bytes,
strings, buffers, or anything else that's not even path-like.
"""
+ if not convert_file_like and is_file_like(filepath_or_buffer):
+ # GH 38125: some fsspec objects implement os.PathLike but have already opened a
+ # file. This prevents opening the file a second time. infer_compression calls
+ # this function with convert_file_like=True to infer the compression.
+ return cast(FileOrBuffer[AnyStr], filepath_or_buffer)
+
if isinstance(filepath_or_buffer, os.PathLike):
filepath_or_buffer = filepath_or_buffer.__fspath__()
return _expand_user(filepath_or_buffer)
@@ -462,7 +466,7 @@ def infer_compression(
# Infer compression
if compression == "infer":
# Convert all path types (e.g. pathlib.Path) to strings
- filepath_or_buffer = stringify_path(filepath_or_buffer)
+ filepath_or_buffer = stringify_path(filepath_or_buffer, convert_file_like=True)
if not isinstance(filepath_or_buffer, str):
# Cannot infer compression of a buffer, assume no compression
return None
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 5b623c360c3ef..44d3c8de0ae23 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -74,7 +74,7 @@
from pandas.core.series import Series
from pandas.core.tools import datetimes as tools
-from pandas.io.common import IOHandles, get_handle, stringify_path, validate_header_arg
+from pandas.io.common import IOHandles, get_handle, validate_header_arg
from pandas.io.date_converters import generic_parser
# BOM character (byte order mark)
@@ -774,7 +774,7 @@ class TextFileReader(abc.Iterator):
def __init__(self, f, engine=None, **kwds):
- self.f = stringify_path(f)
+ self.f = f
if engine is not None:
engine_specified = True
@@ -859,14 +859,14 @@ def _get_options_with_defaults(self, engine):
def _check_file_or_buffer(self, f, engine):
# see gh-16530
- if is_file_like(f):
+ if is_file_like(f) and engine != "c" and not hasattr(f, "__next__"):
# The C engine doesn't need the file-like to have the "__next__"
# attribute. However, the Python engine explicitly calls
# "__next__(...)" when iterating through such an object, meaning it
# needs to have that attribute
- if engine != "c" and not hasattr(f, "__next__"):
- msg = "The 'python' engine cannot iterate through this file buffer."
- raise ValueError(msg)
+ raise ValueError(
+ "The 'python' engine cannot iterate through this file buffer."
+ )
def _clean_options(self, options, engine):
result = options.copy()
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
index c3b21daa0ac04..34cb00e89ea0c 100644
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -85,6 +85,13 @@ def test_stringify_path_fspath(self):
result = icom.stringify_path(p)
assert result == "foo/bar.csv"
+ def test_stringify_file_and_path_like(self):
+ # GH 38125: do not stringify file objects that are also path-like
+ fsspec = pytest.importorskip("fsspec")
+ with tm.ensure_clean() as path:
+ with fsspec.open(f"file://{path}", mode="wb") as fsspec_obj:
+ assert fsspec_obj == icom.stringify_path(fsspec_obj)
+
@pytest.mark.parametrize(
"extension,expected",
[
| Backport PR #38141: BUG: do not stringify file-like objects | https://api.github.com/repos/pandas-dev/pandas/pulls/38458 | 2020-12-14T01:10:30Z | 2020-12-14T10:24:49Z | 2020-12-14T10:24:49Z | 2020-12-14T10:24:50Z |
STYLE: use types_or in pre-commit | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 717334bfe1299..e4ea29aef2736 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,3 +1,4 @@
+minimum_pre_commit_version: '2.9.2'
repos:
- repo: https://github.com/python/black
rev: 20.8b1
@@ -21,10 +22,8 @@ repos:
rev: 5.6.4
hooks:
- id: isort
- name: isort (python)
- - id: isort
- name: isort (cython)
- types: [cython]
+ types: [text] # overwrite upstream `types: [python]`
+ types_or: [python, cython]
- repo: https://github.com/asottile/pyupgrade
rev: v2.7.4
hooks:
@@ -96,17 +95,17 @@ repos:
name: Check for incorrect code block or IPython directives
language: pygrep
entry: (\.\. code-block ::|\.\. ipython ::)
- files: \.(py|pyx|rst)$
+ types_or: [python, cython, rst]
- id: unwanted-patterns-strings-to-concatenate
name: Check for use of not concatenated strings
language: python
entry: python scripts/validate_unwanted_patterns.py --validation-type="strings_to_concatenate"
- files: \.(py|pyx|pxd|pxi)$
+ types_or: [python, cython]
- id: unwanted-patterns-strings-with-wrong-placed-whitespace
name: Check for strings with wrong placed spaces
language: python
entry: python scripts/validate_unwanted_patterns.py --validation-type="strings_with_wrong_placed_whitespace"
- files: \.(py|pyx|pxd|pxi)$
+ types_or: [python, cython]
- id: unwanted-patterns-private-import-across-module
name: Check for import of private attributes across modules
language: python
diff --git a/environment.yml b/environment.yml
index b99b856187fb6..600a20b153ed3 100644
--- a/environment.yml
+++ b/environment.yml
@@ -24,7 +24,7 @@ dependencies:
- flake8-comprehensions>=3.1.0 # used by flake8, linting of unnecessary comprehensions
- isort>=5.2.1 # check that imports are in the right order
- mypy=0.782
- - pre-commit
+ - pre-commit>=2.9.2
- pycodestyle # used by flake8
- pyupgrade
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 17ca6b8401501..d45e87b1785b0 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -12,7 +12,7 @@ flake8
flake8-comprehensions>=3.1.0
isort>=5.2.1
mypy==0.782
-pre-commit
+pre-commit>=2.9.2
pycodestyle
pyupgrade
gitpython
| - [x] closes #38022
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38457 | 2020-12-13T23:51:27Z | 2020-12-16T00:46:50Z | 2020-12-16T00:46:50Z | 2020-12-16T00:46:54Z |
DOC: update wording about when xlrd engine can be used | diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index 965833c013c03..eba097cd8c345 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -2820,15 +2820,40 @@ parse HTML tables in the top-level pandas io function ``read_html``.
Excel files
-----------
-The :func:`~pandas.read_excel` method can read Excel 2003 (``.xls``)
-files using the ``xlrd`` Python module. Excel 2007+ (``.xlsx``) files
-can be read using either ``xlrd`` or ``openpyxl``. Binary Excel (``.xlsb``)
+The :func:`~pandas.read_excel` method can read Excel 2007+ (``.xlsx``) files
+using the ``openpyxl`` Python module. Excel 2003 (``.xls``) files
+can be read using ``xlrd``. Binary Excel (``.xlsb``)
files can be read using ``pyxlsb``.
The :meth:`~DataFrame.to_excel` instance method is used for
saving a ``DataFrame`` to Excel. Generally the semantics are
similar to working with :ref:`csv<io.read_csv_table>` data.
See the :ref:`cookbook<cookbook.excel>` for some advanced strategies.
+.. warning::
+
+ The `xlwt <https://xlwt.readthedocs.io/en/latest/>`__ package for writing old-style ``.xls``
+ excel files is no longer maintained.
+ The `xlrd <https://xlrd.readthedocs.io/en/latest/>`__ package is now only for reading
+ old-style ``.xls`` files.
+
+ Previously, the default argument ``engine=None`` to :func:`~pandas.read_excel`
+ would result in using the ``xlrd`` engine in many cases, including new
+ Excel 2007+ (``.xlsx``) files.
+ If `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`__ is installed,
+ many of these cases will now default to using the ``openpyxl`` engine.
+ See the :func:`read_excel` documentation for more details.
+
+ Thus, it is strongly encouraged to install ``openpyxl`` to read Excel 2007+
+ (``.xlsx``) files.
+ **Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.**
+ This is no longer supported, switch to using ``openpyxl`` instead.
+
+ Attempting to use the the ``xlwt`` engine will raise a ``FutureWarning``
+ unless the option :attr:`io.excel.xls.writer` is set to ``"xlwt"``.
+ While this option is now deprecated and will also raise a ``FutureWarning``,
+ it can be globally set and the warning suppressed. Users are recommended to
+ write ``.xlsx`` files using the ``openpyxl`` engine instead.
+
.. _io.excel_reader:
Reading Excel files
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index bc7f5b8174573..a81443c1be93b 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -10,21 +10,22 @@ including other versions of pandas.
.. warning::
- The packages `xlrd <https://xlrd.readthedocs.io/en/latest/>`_ for reading excel
- files and `xlwt <https://xlwt.readthedocs.io/en/latest/>`_ for
- writing excel files are no longer maintained. These are the only engines in pandas
- that support the xls format.
-
- Previously, the default argument ``engine=None`` to ``pd.read_excel``
- would result in using the ``xlrd`` engine in many cases. If
- `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`_ is installed,
+ The `xlwt <https://xlwt.readthedocs.io/en/latest/>`_ package for writing old-style ``.xls``
+ excel files is no longer maintained.
+ The `xlrd <https://xlrd.readthedocs.io/en/latest/>`_ package is now only for reading
+ old-style ``.xls`` files.
+
+ Previously, the default argument ``engine=None`` to :func:`~pandas.read_excel`
+ would result in using the ``xlrd`` engine in many cases, including new
+ Excel 2007+ (``.xlsx``) files.
+ If `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`_ is installed,
many of these cases will now default to using the ``openpyxl`` engine.
- See the :func:`read_excel` documentation for more details. Attempting to read
- ``.xls`` files or specifying ``engine="xlrd"`` to ``pd.read_excel`` will not
- raise a warning. However users should be aware that ``xlrd`` is already
- broken with certain package configurations, for example with Python 3.9
- when `defusedxml <https://github.com/tiran/defusedxml/>`_ is installed, and
- is anticipated to be unusable in the future.
+ See the :func:`read_excel` documentation for more details.
+
+ Thus, it is strongly encouraged to install ``openpyxl`` to read Excel 2007+
+ (``.xlsx``) files.
+ **Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.**
+ This is no longer supported, switch to using ``openpyxl`` instead.
Attempting to use the the ``xlwt`` engine will raise a ``FutureWarning``
unless the option :attr:`io.excel.xls.writer` is set to ``"xlwt"``.
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index bf1011176693f..c72f294bf6ac8 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -105,16 +105,16 @@
Supported engines: "xlrd", "openpyxl", "odf", "pyxlsb".
Engine compatibility :
- - "xlrd" supports most old/new Excel file formats.
+ - "xlrd" supports old-style Excel files (.xls).
- "openpyxl" supports newer Excel file formats.
- "odf" supports OpenDocument file formats (.odf, .ods, .odt).
- "pyxlsb" supports Binary Excel files.
.. versionchanged:: 1.2.0
The engine `xlrd <https://xlrd.readthedocs.io/en/latest/>`_
- is no longer maintained, and is not supported with
- python >= 3.9. When ``engine=None``, the following logic will be
- used to determine the engine.
+ now only supports old-style ``.xls`` files.
+ When ``engine=None``, the following logic will be
+ used to determine the engine:
- If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
then `odf <https://pypi.org/project/odfpy/>`_ will be used.
@@ -920,7 +920,7 @@ class ExcelFile:
"""
Class for parsing tabular excel sheets into DataFrame objects.
- Uses xlrd engine by default. See read_excel for more documentation
+ See read_excel for more documentation
Parameters
----------
@@ -933,7 +933,7 @@ class ExcelFile:
Supported engines: ``xlrd``, ``openpyxl``, ``odf``, ``pyxlsb``
Engine compatibility :
- - ``xlrd`` supports most old/new Excel file formats.
+ - ``xlrd`` supports old-style Excel files (.xls).
- ``openpyxl`` supports newer Excel file formats.
- ``odf`` supports OpenDocument file formats (.odf, .ods, .odt).
- ``pyxlsb`` supports Binary Excel files.
@@ -941,9 +941,9 @@ class ExcelFile:
.. versionchanged:: 1.2.0
The engine `xlrd <https://xlrd.readthedocs.io/en/latest/>`_
- is no longer maintained, and is not supported with
- python >= 3.9. When ``engine=None``, the following logic will be
- used to determine the engine.
+ now only supports old-style ``.xls`` files.
+ When ``engine=None``, the following logic will be
+ used to determine the engine:
- If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
then `odf <https://pypi.org/project/odfpy/>`_ will be used.
@@ -954,8 +954,10 @@ class ExcelFile:
then ``openpyxl`` will be used.
- Otherwise ``xlrd`` will be used and a ``FutureWarning`` will be raised.
- Specifying ``engine="xlrd"`` will continue to be allowed for the
- indefinite future.
+ .. warning::
+
+ Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.
+ This is not supported, switch to using ``openpyxl`` instead.
"""
from pandas.io.excel._odfreader import ODFReader
| See https://github.com/pandas-dev/pandas/issues/38424#issuecomment-744043899.
| https://api.github.com/repos/pandas-dev/pandas/pulls/38456 | 2020-12-13T18:18:03Z | 2020-12-23T16:48:12Z | 2020-12-23T16:48:12Z | 2020-12-23T17:04:25Z |
REF: Separate values-casting from Block.astype | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index ac0564e1f4f79..031d28b19b138 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -10,7 +10,7 @@
from pandas._libs.internals import BlockPlacement
from pandas._libs.tslibs import conversion
from pandas._libs.tslibs.timezones import tz_compare
-from pandas._typing import ArrayLike, Scalar, Shape
+from pandas._typing import ArrayLike, DtypeObj, Scalar, Shape
from pandas.util._validators import validate_bool_kwarg
from pandas.core.dtypes.cast import (
@@ -68,7 +68,7 @@
)
from pandas.core.base import PandasObject
import pandas.core.common as com
-from pandas.core.construction import extract_array
+from pandas.core.construction import array as pd_array, extract_array
from pandas.core.indexers import (
check_setitem_lengths,
is_empty_indexer,
@@ -593,7 +593,7 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
dtype : str, dtype convertible
copy : bool, default False
copy if indicated
- errors : str, {'raise', 'ignore'}, default 'ignore'
+ errors : str, {'raise', 'ignore'}, default 'raise'
- ``raise`` : allow exceptions to be raised
- ``ignore`` : suppress exceptions. On error return original object
@@ -617,69 +617,23 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
)
raise TypeError(msg)
- if dtype is not None:
- dtype = pandas_dtype(dtype)
-
- # may need to convert to categorical
- if is_categorical_dtype(dtype):
-
- if is_categorical_dtype(self.values.dtype):
- # GH 10696/18593: update an existing categorical efficiently
- return self.make_block(self.values.astype(dtype, copy=copy))
-
- return self.make_block(Categorical(self.values, dtype=dtype))
-
dtype = pandas_dtype(dtype)
- # astype processing
- if is_dtype_equal(self.dtype, dtype):
- if copy:
- return self.copy()
- return self
-
- # force the copy here
- if self.is_extension:
- try:
- values = self.values.astype(dtype)
- except (ValueError, TypeError):
- if errors == "ignore":
- values = self.values
- else:
- raise
- else:
- if issubclass(dtype.type, str):
-
- # use native type formatting for datetime/tz/timedelta
- if self.is_datelike:
- values = self.to_native_types().values
-
- # astype formatting
- else:
- # Because we have neither is_extension nor is_datelike,
- # self.values already has the correct shape
- values = self.values
-
+ try:
+ new_values = self._astype(dtype, copy=copy)
+ except (ValueError, TypeError):
+ # e.g. astype_nansafe can fail on object-dtype of strings
+ # trying to convert to float
+ if errors == "ignore":
+ new_values = self.values
else:
- values = self.get_values(dtype=dtype)
-
- # _astype_nansafe works fine with 1-d only
- vals1d = values.ravel()
- try:
- values = astype_nansafe(vals1d, dtype, copy=True)
- except (ValueError, TypeError):
- # e.g. astype_nansafe can fail on object-dtype of strings
- # trying to convert to float
- if errors == "raise":
- raise
- newb = self.copy() if copy else self
- return newb
-
- # TODO(EA2D): special case not needed with 2D EAs
- if isinstance(values, np.ndarray):
- values = values.reshape(self.shape)
+ raise
- newb = self.make_block(values)
+ if isinstance(new_values, np.ndarray):
+ # TODO(EA2D): special case not needed with 2D EAs
+ new_values = new_values.reshape(self.shape)
+ newb = self.make_block(new_values)
if newb.is_numeric and self.is_numeric:
if newb.shape != self.shape:
raise TypeError(
@@ -689,6 +643,50 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
)
return newb
+ def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike:
+ values = self.values
+
+ if is_categorical_dtype(dtype):
+
+ if is_categorical_dtype(values.dtype):
+ # GH#10696/GH#18593: update an existing categorical efficiently
+ return values.astype(dtype, copy=copy)
+
+ return Categorical(values, dtype=dtype)
+
+ if is_dtype_equal(values.dtype, dtype):
+ if copy:
+ return values.copy()
+ return values
+
+ if isinstance(values, ExtensionArray):
+ values = values.astype(dtype, copy=copy)
+
+ else:
+ if issubclass(dtype.type, str):
+ if values.dtype.kind in ["m", "M"]:
+ # use native type formatting for datetime/tz/timedelta
+ arr = pd_array(values)
+ # Note: in the case where dtype is an np.dtype, i.e. not
+ # StringDtype, this matches arr.astype(dtype), xref GH#36153
+ values = arr._format_native_types(na_rep="NaT")
+
+ elif is_object_dtype(dtype):
+ if values.dtype.kind in ["m", "M"]:
+ # Wrap in Timedelta/Timestamp
+ arr = pd_array(values)
+ values = arr.astype(object)
+ else:
+ values = values.astype(object)
+ # We still need to go through astype_nansafe for
+ # e.g. dtype = Sparse[object, 0]
+
+ # astype_nansafe works with 1-d only
+ vals1d = values.ravel()
+ values = astype_nansafe(vals1d, dtype, copy=True)
+
+ return values
+
def convert(
self,
copy: bool = True,
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index c70d55b07661d..7cc032e61e989 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -5,6 +5,8 @@
import pandas.util._test_decorators as td
+from pandas.core.dtypes.common import is_dtype_equal
+
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays.string_arrow import ArrowStringArray, ArrowStringDtype
@@ -127,11 +129,14 @@ def test_astype_roundtrip(dtype, request):
mark = pytest.mark.xfail(reason=reason)
request.node.add_marker(mark)
- s = pd.Series(pd.date_range("2000", periods=12))
- s[0] = None
+ ser = pd.Series(pd.date_range("2000", periods=12))
+ ser[0] = None
+
+ casted = ser.astype(dtype)
+ assert is_dtype_equal(casted.dtype, dtype)
- result = s.astype(dtype).astype("datetime64[ns]")
- tm.assert_series_equal(result, s)
+ result = casted.astype("datetime64[ns]")
+ tm.assert_series_equal(result, ser)
def test_add(dtype, request):
| This separates Block._astype from Block.astype. Block._astype only requires Block.values, the idea being that we can roll it into astype_nansafe before long. | https://api.github.com/repos/pandas-dev/pandas/pulls/38455 | 2020-12-13T17:44:13Z | 2020-12-13T23:41:35Z | 2020-12-13T23:41:34Z | 2020-12-14T00:36:08Z |
ENH: Improve error message when names and usecols do not match for read_csv with engine=c | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index d86c1b7911528..1246d89db9960 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -20,7 +20,7 @@ Other enhancements
^^^^^^^^^^^^^^^^^^
- Added :meth:`MultiIndex.dtypes` (:issue:`37062`)
--
+- Improve error message when ``usecols`` and ``names`` do not match for :func:`read_csv` and ``engine="c"`` (:issue:`29042`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index eae72d700190d..4995252d7aafd 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -738,8 +738,8 @@ cdef class TextReader:
elif self.names is None and nuse < passed_count:
self.leading_cols = field_count - passed_count
elif passed_count != field_count:
- raise ValueError('Passed header names '
- 'mismatches usecols')
+ raise ValueError('Number of passed names did not match number of '
+ 'header fields in the file')
# oh boy, #2442, #2981
elif self.allow_leading_cols and passed_count < field_count:
self.leading_cols = field_count - passed_count
diff --git a/pandas/tests/io/parser/test_usecols.py b/pandas/tests/io/parser/test_usecols.py
index fbf3b0ea7c792..7bc8f749846c3 100644
--- a/pandas/tests/io/parser/test_usecols.py
+++ b/pandas/tests/io/parser/test_usecols.py
@@ -104,11 +104,7 @@ def test_usecols_name_length_conflict(all_parsers):
7,8,9
10,11,12"""
parser = all_parsers
- msg = (
- "Number of passed names did not match number of header fields in the file"
- if parser.engine == "python"
- else "Passed header names mismatches usecols"
- )
+ msg = "Number of passed names did not match number of header fields in the file"
with pytest.raises(ValueError, match=msg):
parser.read_csv(StringIO(data), names=["a", "b"], header=None, usecols=[1])
| - [x] closes #29042
- [x] tests added / passed This case was already covered with differing error messages. I adjusted the message accordingly
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38452 | 2020-12-13T16:21:43Z | 2020-12-13T17:37:04Z | 2020-12-13T17:37:04Z | 2020-12-13T18:29:29Z |
Revert "BUG: first("1M") returning two months when first day is last day of month" | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index ac7ef462cdea6..bc7f5b8174573 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -607,7 +607,6 @@ Datetimelike
- Bug in :meth:`Series.isin` with ``datetime64[ns]`` dtype and :meth:`.DatetimeIndex.isin` failing to consider timezone-aware and timezone-naive datetimes as always different (:issue:`35728`)
- Bug in :meth:`Series.isin` with ``PeriodDtype`` dtype and :meth:`PeriodIndex.isin` failing to consider arguments with different ``PeriodDtype`` as always different (:issue:`37528`)
- Bug in :class:`Period` constructor now correctly handles nanoseconds in the ``value`` argument (:issue:`34621` and :issue:`17053`)
-- Bug in :meth:`DataFrame.first` and :meth:`Series.first` returning two months for offset one month when first day is last calendar day (:issue:`29623`)
Timedelta
^^^^^^^^^
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index cb4f103ce1c8d..41cb76d88957e 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8420,11 +8420,7 @@ def first(self: FrameOrSeries, offset) -> FrameOrSeries:
return self
offset = to_offset(offset)
- if not isinstance(offset, Tick) and offset.is_on_offset(self.index[0]):
- # GH#29623 if first value is end of period
- end_date = end = self.index[0]
- else:
- end_date = end = self.index[0] + offset
+ end_date = end = self.index[0] + offset
# Tick-like, e.g. 3 weeks
if isinstance(offset, Tick):
diff --git a/pandas/tests/frame/methods/test_first_and_last.py b/pandas/tests/frame/methods/test_first_and_last.py
index 4ee7016004137..d21e1eee54e16 100644
--- a/pandas/tests/frame/methods/test_first_and_last.py
+++ b/pandas/tests/frame/methods/test_first_and_last.py
@@ -3,7 +3,7 @@
"""
import pytest
-from pandas import DataFrame, bdate_range
+from pandas import DataFrame
import pandas._testing as tm
@@ -69,13 +69,3 @@ def test_last_subset(self, frame_or_series):
result = ts[:0].last("3M")
tm.assert_equal(result, ts[:0])
-
- @pytest.mark.parametrize("start, periods", [("2010-03-31", 1), ("2010-03-30", 2)])
- def test_first_with_first_day_last_of_month(self, frame_or_series, start, periods):
- # GH#29623
- x = frame_or_series([1] * 100, index=bdate_range(start, periods=100))
- result = x.first("1M")
- expected = frame_or_series(
- [1] * periods, index=bdate_range(start, periods=periods)
- )
- tm.assert_equal(result, expected)
| Reverts pandas-dev/pandas#38331 | https://api.github.com/repos/pandas-dev/pandas/pulls/38448 | 2020-12-13T14:08:12Z | 2020-12-13T15:45:02Z | 2020-12-13T15:45:02Z | 2020-12-13T15:45:08Z |
BUG: first("2M") returning incorrect results | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index d86c1b7911528..4202c01dfe551 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -156,7 +156,7 @@ Categorical
Datetimelike
^^^^^^^^^^^^
- Bug in :class:`DataFrame` and :class:`Series` constructors sometimes dropping nanoseconds from :class:`Timestamp` (resp. :class:`Timedelta`) ``data``, with ``dtype=datetime64[ns]`` (resp. ``timedelta64[ns]``) (:issue:`38032`)
--
+- Bug in :meth:`DataFrame.first` and :meth:`Series.first` returning two months for offset one month when first day is last calendar day (:issue:`29623`)
-
Timedelta
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 41cb76d88957e..e0b5df7e2cf0c 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8420,7 +8420,12 @@ def first(self: FrameOrSeries, offset) -> FrameOrSeries:
return self
offset = to_offset(offset)
- end_date = end = self.index[0] + offset
+ if not isinstance(offset, Tick) and offset.is_on_offset(self.index[0]):
+ # GH#29623 if first value is end of period, remove offset with n = 1
+ # before adding the real offset
+ end_date = end = self.index[0] - offset.base + offset
+ else:
+ end_date = end = self.index[0] + offset
# Tick-like, e.g. 3 weeks
if isinstance(offset, Tick):
diff --git a/pandas/tests/frame/methods/test_first_and_last.py b/pandas/tests/frame/methods/test_first_and_last.py
index d21e1eee54e16..43469a093f827 100644
--- a/pandas/tests/frame/methods/test_first_and_last.py
+++ b/pandas/tests/frame/methods/test_first_and_last.py
@@ -3,7 +3,7 @@
"""
import pytest
-from pandas import DataFrame
+from pandas import DataFrame, bdate_range
import pandas._testing as tm
@@ -69,3 +69,22 @@ def test_last_subset(self, frame_or_series):
result = ts[:0].last("3M")
tm.assert_equal(result, ts[:0])
+
+ @pytest.mark.parametrize("start, periods", [("2010-03-31", 1), ("2010-03-30", 2)])
+ def test_first_with_first_day_last_of_month(self, frame_or_series, start, periods):
+ # GH#29623
+ x = frame_or_series([1] * 100, index=bdate_range(start, periods=100))
+ result = x.first("1M")
+ expected = frame_or_series(
+ [1] * periods, index=bdate_range(start, periods=periods)
+ )
+ tm.assert_equal(result, expected)
+
+ def test_first_with_first_day_end_of_frq_n_greater_one(self, frame_or_series):
+ # GH#29623
+ x = frame_or_series([1] * 100, index=bdate_range("2010-03-31", periods=100))
+ result = x.first("2M")
+ expected = frame_or_series(
+ [1] * 23, index=bdate_range("2010-03-31", "2010-04-30")
+ )
+ tm.assert_equal(result, expected)
| - [x] closes #29623
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
This would fix #29623 for offsets with n > 1
cc @simonjayhawkins | https://api.github.com/repos/pandas-dev/pandas/pulls/38446 | 2020-12-13T13:37:15Z | 2020-12-19T02:14:08Z | 2020-12-19T02:14:08Z | 2020-12-19T17:21:21Z |
BUG: read_csv usecols and names parameters inconsistent between c and python | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index d86c1b7911528..26e548f519ecd 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -217,6 +217,7 @@ MultiIndex
I/O
^^^
+- Bug in :func:`read_csv` not accepting ``usecols`` with different length than ``names`` for ``engine="python"`` (:issue:`16469`)
- Bug in :func:`read_csv` raising ``TypeError`` when ``names`` and ``parse_dates`` is specified for ``engine="c"`` (:issue:`33699`)
-
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 7a56b03326762..8177741b5252d 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -2487,9 +2487,8 @@ def read(self, rows=None):
content = content[1:]
alldata = self._rows_to_cols(content)
- data = self._exclude_implicit_index(alldata)
+ data, columns = self._exclude_implicit_index(alldata)
- columns = self._maybe_dedup_names(self.columns)
columns, data = self._do_date_conversions(columns, data)
data = self._convert_data(data)
@@ -2500,19 +2499,14 @@ def read(self, rows=None):
def _exclude_implicit_index(self, alldata):
names = self._maybe_dedup_names(self.orig_names)
+ offset = 0
if self._implicit_index:
- excl_indices = self.index_col
+ offset = len(self.index_col)
- data = {}
- offset = 0
- for i, col in enumerate(names):
- while i + offset in excl_indices:
- offset += 1
- data[col] = alldata[i + offset]
- else:
- data = {k: v for k, v in zip(names, alldata)}
+ if self._col_indices is not None and len(names) != len(self._col_indices):
+ names = [names[i] for i in sorted(self._col_indices)]
- return data
+ return {name: alldata[i + offset] for i, name in enumerate(names)}, names
# legacy
def get_chunk(self, size=None):
@@ -2694,9 +2688,7 @@ def _infer_columns(self):
self._clear_buffer()
if names is not None:
- if (self.usecols is not None and len(names) != len(self.usecols)) or (
- self.usecols is None and len(names) != len(columns[0])
- ):
+ if len(names) > len(columns[0]):
raise ValueError(
"Number of passed names did not match "
"number of header fields in the file"
diff --git a/pandas/tests/io/parser/test_usecols.py b/pandas/tests/io/parser/test_usecols.py
index fbf3b0ea7c792..98e5801b3458e 100644
--- a/pandas/tests/io/parser/test_usecols.py
+++ b/pandas/tests/io/parser/test_usecols.py
@@ -559,12 +559,7 @@ def test_raises_on_usecols_names_mismatch(all_parsers, usecols, kwargs, expected
@pytest.mark.parametrize("usecols", [["A", "C"], [0, 2]])
-def test_usecols_subset_names_mismatch_orig_columns(all_parsers, usecols, request):
- if all_parsers.engine != "c":
- reason = "see gh-16469: works on the C engine but not the Python engine"
- # Number of passed names did not match number of header fields in the file
- request.node.add_marker(pytest.mark.xfail(reason=reason, raises=ValueError))
-
+def test_usecols_subset_names_mismatch_orig_columns(all_parsers, usecols):
data = "a,b,c,d\n1,2,3,4\n5,6,7,8"
names = ["A", "B", "C", "D"]
parser = all_parsers
| - [x] closes #16469
- [x] tests added / passed The tests added by @gfyoung which were marked as xfail are passing now.
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38445 | 2020-12-13T11:17:41Z | 2020-12-13T17:08:29Z | 2020-12-13T17:08:28Z | 2020-12-13T17:15:09Z |
CI: add slash dispatch workflow to trigger pre-commit checks with comment | diff --git a/.github/workflows/autoupdate-pre-commit-config.yml b/.github/workflows/autoupdate-pre-commit-config.yml
index 42d6ae6606442..801e063f72726 100644
--- a/.github/workflows/autoupdate-pre-commit-config.yml
+++ b/.github/workflows/autoupdate-pre-commit-config.yml
@@ -23,7 +23,7 @@ jobs:
- name: Update pre-commit config packages
uses: technote-space/create-pr-action@v2
with:
- GITHUB_TOKEN: ${{ secrets.ACTION_TRIGGER_TOKEN }}
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
EXECUTE_COMMANDS: |
pip install pre-commit
pre-commit autoupdate || (exit 0);
diff --git a/.github/workflows/comment_bot.yml b/.github/workflows/comment_bot.yml
new file mode 100644
index 0000000000000..98b8e10f66f6c
--- /dev/null
+++ b/.github/workflows/comment_bot.yml
@@ -0,0 +1,40 @@
+name: Comment-bot
+
+on:
+ issue_comment:
+ types:
+ - created
+ - edited
+
+jobs:
+ autotune:
+ name: "Fixup pre-commit formatting"
+ if: startsWith(github.event.comment.body, '@github-actions pre-commit')
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - uses: r-lib/actions/pr-fetch@master
+ with:
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
+ - name: Cache multiple paths
+ uses: actions/cache@v2
+ with:
+ path: |
+ ~/.cache/pre-commit
+ ~/.cache/pip
+ key: pre-commit-dispatched-${{ runner.os }}-build
+ - uses: actions/setup-python@v2
+ with:
+ python-version: 3.8
+ - name: Install-pre-commit
+ run: python -m pip install --upgrade pre-commit
+ - name: Run pre-commit
+ run: pre-commit run --all-files || (exit 0)
+ - name: Commit results
+ run: |
+ git config user.name "$(git log -1 --pretty=format:%an)"
+ git config user.email "$(git log -1 --pretty=format:%ae)"
+ git commit -a -m 'Fixes from pre-commit [automated commit]' || echo "No changes to commit"
+ - uses: r-lib/actions/pr-push@master
+ with:
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
| This would be an on-demand bot to run pre-commit checks on a PR, which can be triggered by commenting
```
@github-actions pre-commit
```
on a pull request (see [here](https://github.com/nbQA-dev/nbQA/pull/518) for a demo).
Use case: if a PR is submitted and is good-to-go except for some linting error, we can just comment `/pre-commit-run` and have the bot fixup the errors. | https://api.github.com/repos/pandas-dev/pandas/pulls/38444 | 2020-12-13T11:16:20Z | 2020-12-22T18:39:27Z | 2020-12-22T18:39:27Z | 2020-12-23T08:06:55Z |
BUG: Fix Index.__repr__ when `display.max_seq_items` = 1 | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index d62356e45b723..a4260965db442 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -217,6 +217,7 @@ MultiIndex
I/O
^^^
+- Bug in :meth:`Index.__repr__` when ``display.max_seq_items=1`` (:issue:`38415`)
- Bug in :func:`read_csv` interpreting ``NA`` value as comment, when ``NA`` does contain the comment string fixed for ``engine="python"`` (:issue:`34002`)
- Bug in :func:`read_csv` raising ``IndexError`` with multiple header columns and ``index_col`` specified when file has no data rows (:issue:`38292`)
- Bug in :func:`read_csv` not accepting ``usecols`` with different length than ``names`` for ``engine="python"`` (:issue:`16469`)
diff --git a/pandas/io/formats/printing.py b/pandas/io/formats/printing.py
index 128e50d84657c..acb17aee50b76 100644
--- a/pandas/io/formats/printing.py
+++ b/pandas/io/formats/printing.py
@@ -382,7 +382,11 @@ def best_len(values: List[str]) -> int:
summary = f"[{first}, {last}]{close}"
else:
- if n > max_seq_items:
+ if max_seq_items == 1:
+ # If max_seq_items=1 show only last element
+ head = []
+ tail = [formatter(x) for x in obj[-1:]]
+ elif n > max_seq_items:
n = min(max_seq_items // 2, 10)
head = [formatter(x) for x in obj[:n]]
tail = [formatter(x) for x in obj[-n:]]
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 7c179a79513fa..f8a9412d3036d 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -2058,6 +2058,7 @@ def test_groupby_list_level():
[
(5, "{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}"),
(4, "{0: [0], 1: [1], 2: [2], 3: [3], ...}"),
+ (1, "{0: [0], ...}"),
],
)
def test_groups_repr_truncates(max_seq_items, expected):
diff --git a/pandas/tests/indexes/multi/test_formats.py b/pandas/tests/indexes/multi/test_formats.py
index c1de7f79c2d2e..4e56b7c73c64f 100644
--- a/pandas/tests/indexes/multi/test_formats.py
+++ b/pandas/tests/indexes/multi/test_formats.py
@@ -89,6 +89,20 @@ def test_unicode_repr_issues(self):
# NumPy bug
# repr(index.get_level_values(1))
+ def test_repr_max_seq_items_equal_to_n(self, idx):
+ # display.max_seq_items == n
+ with pd.option_context("display.max_seq_items", 6):
+ result = idx.__repr__()
+ expected = """\
+MultiIndex([('foo', 'one'),
+ ('foo', 'two'),
+ ('bar', 'one'),
+ ('baz', 'two'),
+ ('qux', 'one'),
+ ('qux', 'two')],
+ names=['first', 'second'])"""
+ assert result == expected
+
def test_repr(self, idx):
result = idx[:1].__repr__()
expected = """\
@@ -118,6 +132,15 @@ def test_repr(self, idx):
names=['first', 'second'], length=6)"""
assert result == expected
+ # display.max_seq_items == 1
+ with pd.option_context("display.max_seq_items", 1):
+ result = idx.__repr__()
+ expected = """\
+MultiIndex([...
+ ('qux', 'two')],
+ names=['first', ...], length=6)"""
+ assert result == expected
+
def test_rjust(self, narrow_multi_index):
mi = narrow_multi_index
result = mi[:1].__repr__()
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index fe85849c6dcca..02a0c78bb2d17 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -297,6 +297,9 @@ def test_repr_obeys_max_seq_limit(self):
with option_context("display.max_seq_items", 5):
assert len(printing.pprint_thing(list(range(1000)))) < 100
+ with option_context("display.max_seq_items", 1):
+ assert len(printing.pprint_thing(list(range(1000)))) < 9
+
def test_repr_set(self):
assert printing.pprint_thing({1}) == "{1}"
| - [x] closes #38415
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38443 | 2020-12-13T09:10:20Z | 2020-12-28T18:38:47Z | 2020-12-28T18:38:47Z | 2020-12-28T18:38:55Z |
BENCH/REF: parametrize CSV benchmarks on engine | diff --git a/asv_bench/benchmarks/io/csv.py b/asv_bench/benchmarks/io/csv.py
index 9bcd125f56bbb..24d21ad6a633d 100644
--- a/asv_bench/benchmarks/io/csv.py
+++ b/asv_bench/benchmarks/io/csv.py
@@ -1,4 +1,4 @@
-from io import StringIO
+from io import BytesIO, StringIO
import random
import string
@@ -146,10 +146,10 @@ def time_read_csv(self, bad_date_value):
class ReadCSVSkipRows(BaseIO):
fname = "__test__.csv"
- params = [None, 10000]
- param_names = ["skiprows"]
+ params = ([None, 10000], ["c", "python"])
+ param_names = ["skiprows", "engine"]
- def setup(self, skiprows):
+ def setup(self, skiprows, engine):
N = 20000
index = tm.makeStringIndex(N)
df = DataFrame(
@@ -164,8 +164,8 @@ def setup(self, skiprows):
)
df.to_csv(self.fname)
- def time_skipprows(self, skiprows):
- read_csv(self.fname, skiprows=skiprows)
+ def time_skipprows(self, skiprows, engine):
+ read_csv(self.fname, skiprows=skiprows, engine=engine)
class ReadUint64Integers(StringIORewind):
@@ -192,10 +192,10 @@ def time_read_uint64_na_values(self):
class ReadCSVThousands(BaseIO):
fname = "__test__.csv"
- params = ([",", "|"], [None, ","])
- param_names = ["sep", "thousands"]
+ params = ([",", "|"], [None, ","], ["c", "python"])
+ param_names = ["sep", "thousands", "engine"]
- def setup(self, sep, thousands):
+ def setup(self, sep, thousands, engine):
N = 10000
K = 8
data = np.random.randn(N, K) * np.random.randint(100, 10000, (N, K))
@@ -206,16 +206,19 @@ def setup(self, sep, thousands):
df = df.applymap(lambda x: fmt.format(x))
df.to_csv(self.fname, sep=sep)
- def time_thousands(self, sep, thousands):
- read_csv(self.fname, sep=sep, thousands=thousands)
+ def time_thousands(self, sep, thousands, engine):
+ read_csv(self.fname, sep=sep, thousands=thousands, engine=engine)
class ReadCSVComment(StringIORewind):
- def setup(self):
+ params = ["c", "python"]
+ param_names = ["engine"]
+
+ def setup(self, engine):
data = ["A,B,C"] + (["1,2,3 # comment"] * 100000)
self.StringIO_input = StringIO("\n".join(data))
- def time_comment(self):
+ def time_comment(self, engine):
read_csv(
self.data(self.StringIO_input), comment="#", header=None, names=list("abc")
)
@@ -255,25 +258,47 @@ def time_read_csv_python_engine(self, sep, decimal, float_precision):
)
+class ReadCSVEngine(StringIORewind):
+ params = ["c", "python"]
+ param_names = ["engine"]
+
+ def setup(self, engine):
+ data = ["A,B,C,D,E"] + (["1,2,3,4,5"] * 100000)
+ self.StringIO_input = StringIO("\n".join(data))
+ # simulate reading from file
+ self.BytesIO_input = BytesIO(self.StringIO_input.read().encode("utf-8"))
+
+ def time_read_stringcsv(self, engine):
+ read_csv(self.data(self.StringIO_input), engine=engine)
+
+ def time_read_bytescsv(self, engine):
+ read_csv(self.data(self.BytesIO_input), engine=engine)
+
+
class ReadCSVCategorical(BaseIO):
fname = "__test__.csv"
+ params = ["c", "python"]
+ param_names = ["engine"]
- def setup(self):
+ def setup(self, engine):
N = 100000
group1 = ["aaaaaaaa", "bbbbbbb", "cccccccc", "dddddddd", "eeeeeeee"]
df = DataFrame(np.random.choice(group1, (N, 3)), columns=list("abc"))
df.to_csv(self.fname, index=False)
- def time_convert_post(self):
- read_csv(self.fname).apply(Categorical)
+ def time_convert_post(self, engine):
+ read_csv(self.fname, engine=engine).apply(Categorical)
- def time_convert_direct(self):
- read_csv(self.fname, dtype="category")
+ def time_convert_direct(self, engine):
+ read_csv(self.fname, engine=engine, dtype="category")
class ReadCSVParseDates(StringIORewind):
- def setup(self):
+ params = ["c", "python"]
+ param_names = ["engine"]
+
+ def setup(self, engine):
data = """{},19:00:00,18:56:00,0.8100,2.8100,7.2000,0.0000,280.0000\n
{},20:00:00,19:56:00,0.0100,2.2100,7.2000,0.0000,260.0000\n
{},21:00:00,20:56:00,-0.5900,2.2100,5.7000,0.0000,280.0000\n
@@ -284,18 +309,20 @@ def setup(self):
data = data.format(*two_cols)
self.StringIO_input = StringIO(data)
- def time_multiple_date(self):
+ def time_multiple_date(self, engine):
read_csv(
self.data(self.StringIO_input),
+ engine=engine,
sep=",",
header=None,
names=list(string.digits[:9]),
parse_dates=[[1, 2], [1, 3]],
)
- def time_baseline(self):
+ def time_baseline(self, engine):
read_csv(
self.data(self.StringIO_input),
+ engine=engine,
sep=",",
header=None,
parse_dates=[1],
@@ -304,17 +331,18 @@ def time_baseline(self):
class ReadCSVCachedParseDates(StringIORewind):
- params = ([True, False],)
- param_names = ["do_cache"]
+ params = ([True, False], ["c", "python"])
+ param_names = ["do_cache", "engine"]
- def setup(self, do_cache):
+ def setup(self, do_cache, engine):
data = ("\n".join(f"10/{year}" for year in range(2000, 2100)) + "\n") * 10
self.StringIO_input = StringIO(data)
- def time_read_csv_cached(self, do_cache):
+ def time_read_csv_cached(self, do_cache, engine):
try:
read_csv(
self.data(self.StringIO_input),
+ engine=engine,
header=None,
parse_dates=[0],
cache_dates=do_cache,
@@ -329,37 +357,40 @@ class ReadCSVMemoryGrowth(BaseIO):
chunksize = 20
num_rows = 1000
fname = "__test__.csv"
+ params = ["c", "python"]
+ param_names = ["engine"]
- def setup(self):
+ def setup(self, engine):
with open(self.fname, "w") as f:
for i in range(self.num_rows):
f.write(f"{i}\n")
- def mem_parser_chunks(self):
+ def mem_parser_chunks(self, engine):
# see gh-24805.
- result = read_csv(self.fname, chunksize=self.chunksize)
+ result = read_csv(self.fname, chunksize=self.chunksize, engine=engine)
for _ in result:
pass
class ReadCSVParseSpecialDate(StringIORewind):
- params = (["mY", "mdY", "hm"],)
- param_names = ["value"]
+ params = (["mY", "mdY", "hm"], ["c", "python"])
+ param_names = ["value", "engine"]
objects = {
"mY": "01-2019\n10-2019\n02/2000\n",
"mdY": "12/02/2010\n",
"hm": "21:34\n",
}
- def setup(self, value):
+ def setup(self, value, engine):
count_elem = 10000
data = self.objects[value] * count_elem
self.StringIO_input = StringIO(data)
- def time_read_special_date(self, value):
+ def time_read_special_date(self, value, engine):
read_csv(
self.data(self.StringIO_input),
+ engine=engine,
sep=",",
header=None,
names=["Date"],
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
The diff in basic PR implementing the `pyarrow`-based CSV engine (#38370) is quite big. A part of that PR is a small refactor of the CSV I/O benchmarks such that they take `engine` as a parameter. Most of that refactor is not dependent on having the pyarrow engine so I'm spinning it off here to de-bloat #38370. | https://api.github.com/repos/pandas-dev/pandas/pulls/38442 | 2020-12-13T06:57:01Z | 2020-12-17T01:23:05Z | 2020-12-17T01:23:05Z | 2020-12-17T01:43:28Z |
TYP: pandas/core/frame.py (easy: Axis/Level) | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index b4ef6e8eaf64f..0dff1305357b2 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4050,7 +4050,7 @@ def _reindex_index(
new_index,
method,
copy: bool,
- level,
+ level: Level,
fill_value=np.nan,
limit=None,
tolerance=None,
@@ -4070,7 +4070,7 @@ def _reindex_columns(
new_columns,
method,
copy: bool,
- level,
+ level: Level,
fill_value=None,
limit=None,
tolerance=None,
@@ -4110,14 +4110,14 @@ def align(
self,
other,
join: str = "outer",
- axis=None,
- level=None,
+ axis: Optional[Axis] = None,
+ level: Optional[Level] = None,
copy: bool = True,
fill_value=None,
method: Optional[str] = None,
limit=None,
- fill_axis=0,
- broadcast_axis=None,
+ fill_axis: Axis = 0,
+ broadcast_axis: Optional[Axis] = None,
) -> DataFrame:
return super().align(
other,
@@ -4198,10 +4198,10 @@ def reindex(self, *args, **kwargs) -> DataFrame:
def drop(
self,
labels=None,
- axis=0,
+ axis: Axis = 0,
index=None,
columns=None,
- level=None,
+ level: Optional[Level] = None,
inplace: bool = False,
errors: str = "raise",
):
@@ -4474,7 +4474,7 @@ def fillna(
self,
value=None,
method: Optional[str] = None,
- axis=None,
+ axis: Optional[Axis] = None,
inplace: bool = False,
limit=None,
downcast=None,
@@ -4587,7 +4587,7 @@ def _replace_columnwise(
@doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"])
def shift(
- self, periods=1, freq=None, axis=0, fill_value=lib.no_default
+ self, periods=1, freq=None, axis: Axis = 0, fill_value=lib.no_default
) -> DataFrame:
axis = self._get_axis_number(axis)
@@ -5074,7 +5074,12 @@ def notnull(self) -> DataFrame:
return ~self.isna()
def dropna(
- self, axis=0, how: str = "any", thresh=None, subset=None, inplace: bool = False
+ self,
+ axis: Axis = 0,
+ how: str = "any",
+ thresh=None,
+ subset=None,
+ inplace: bool = False,
):
"""
Remove missing values.
@@ -5454,7 +5459,7 @@ def f(vals):
def sort_values( # type: ignore[override]
self,
by,
- axis=0,
+ axis: Axis = 0,
ascending=True,
inplace: bool = False,
kind: str = "quicksort",
@@ -5514,8 +5519,8 @@ def sort_values( # type: ignore[override]
def sort_index(
self,
- axis=0,
- level=None,
+ axis: Axis = 0,
+ level: Optional[Level] = None,
ascending: bool = True,
inplace: bool = False,
kind: str = "quicksort",
@@ -5932,7 +5937,7 @@ def nsmallest(self, n, columns, keep: str = "first") -> DataFrame:
self, n=n, keep=keep, columns=columns
).nsmallest()
- def swaplevel(self, i=-2, j=-1, axis=0) -> DataFrame:
+ def swaplevel(self, i: Axis = -2, j: Axis = -1, axis: Axis = 0) -> DataFrame:
"""
Swap levels i and j in a MultiIndex on a particular axis.
@@ -5963,7 +5968,7 @@ def swaplevel(self, i=-2, j=-1, axis=0) -> DataFrame:
result.columns = result.columns.swaplevel(i, j)
return result
- def reorder_levels(self, order, axis=0) -> DataFrame:
+ def reorder_levels(self, order: Sequence[Axis], axis: Axis = 0) -> DataFrame:
"""
Rearrange index levels using input order. May not drop or duplicate levels.
@@ -6726,8 +6731,8 @@ def update(
def groupby(
self,
by=None,
- axis=0,
- level=None,
+ axis: Axis = 0,
+ level: Optional[Level] = None,
as_index: bool = True,
sort: bool = True,
group_keys: bool = True,
@@ -7080,7 +7085,7 @@ def pivot_table(
observed=observed,
)
- def stack(self, level=-1, dropna: bool = True):
+ def stack(self, level: Level = -1, dropna: bool = True):
"""
Stack the prescribed level(s) from columns to index.
@@ -7399,7 +7404,7 @@ def melt(
value_vars=None,
var_name=None,
value_name="value",
- col_level=None,
+ col_level: Optional[Level] = None,
ignore_index=True,
) -> DataFrame:
@@ -7607,7 +7612,7 @@ def _gotitem(
see_also=_agg_summary_and_see_also_doc,
examples=_agg_examples_doc,
)
- def aggregate(self, func=None, axis=0, *args, **kwargs):
+ def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs):
axis = self._get_axis_number(axis)
relabeling, func, columns, order = reconstruct_func(func, **kwargs)
@@ -7638,7 +7643,7 @@ def aggregate(self, func=None, axis=0, *args, **kwargs):
return result
- def _aggregate(self, arg, axis=0, *args, **kwargs):
+ def _aggregate(self, arg, axis: Axis = 0, *args, **kwargs):
if axis == 1:
# NDFrame.aggregate returns a tuple, and we need to transpose
# only result
@@ -7661,7 +7666,9 @@ def transform(
assert isinstance(result, DataFrame)
return result
- def apply(self, func, axis=0, raw: bool = False, result_type=None, args=(), **kwds):
+ def apply(
+ self, func, axis: Axis = 0, raw: bool = False, result_type=None, args=(), **kwds
+ ):
"""
Apply a function along an axis of the DataFrame.
@@ -8578,7 +8585,7 @@ def cov(
return self._constructor(base_cov, index=idx, columns=cols)
- def corrwith(self, other, axis=0, drop=False, method="pearson") -> Series:
+ def corrwith(self, other, axis: Axis = 0, drop=False, method="pearson") -> Series:
"""
Compute pairwise correlation.
@@ -8674,7 +8681,9 @@ def c(x):
# ----------------------------------------------------------------------
# ndarray-like stats methods
- def count(self, axis=0, level=None, numeric_only: bool = False):
+ def count(
+ self, axis: Axis = 0, level: Optional[Level] = None, numeric_only: bool = False
+ ):
"""
Count non-NA cells for each column or row.
@@ -8778,7 +8787,7 @@ def count(self, axis=0, level=None, numeric_only: bool = False):
return result.astype("int64")
- def _count_level(self, level, axis=0, numeric_only=False):
+ def _count_level(self, level: Level, axis: Axis = 0, numeric_only=False):
if numeric_only:
frame = self._get_numeric_data()
else:
@@ -8828,7 +8837,7 @@ def _reduce(
op,
name: str,
*,
- axis=0,
+ axis: Axis = 0,
skipna: bool = True,
numeric_only: Optional[bool] = None,
filter_type=None,
@@ -8936,7 +8945,7 @@ def _get_data() -> DataFrame:
result = self._constructor_sliced(result, index=labels)
return result
- def nunique(self, axis=0, dropna: bool = True) -> Series:
+ def nunique(self, axis: Axis = 0, dropna: bool = True) -> Series:
"""
Count distinct observations over requested axis.
@@ -8976,7 +8985,7 @@ def nunique(self, axis=0, dropna: bool = True) -> Series:
"""
return self.apply(Series.nunique, axis=axis, dropna=dropna)
- def idxmin(self, axis=0, skipna: bool = True) -> Series:
+ def idxmin(self, axis: Axis = 0, skipna: bool = True) -> Series:
"""
Return index of first occurrence of minimum over requested axis.
@@ -9053,7 +9062,7 @@ def idxmin(self, axis=0, skipna: bool = True) -> Series:
result = [index[i] if i >= 0 else np.nan for i in indices]
return self._constructor_sliced(result, index=self._get_agg_axis(axis))
- def idxmax(self, axis=0, skipna: bool = True) -> Series:
+ def idxmax(self, axis: Axis = 0, skipna: bool = True) -> Series:
"""
Return index of first occurrence of maximum over requested axis.
@@ -9142,7 +9151,7 @@ def _get_agg_axis(self, axis_num: int) -> Index:
raise ValueError(f"Axis must be 0 or 1 (got {repr(axis_num)})")
def mode(
- self, axis=0, numeric_only: bool = False, dropna: bool = True
+ self, axis: Axis = 0, numeric_only: bool = False, dropna: bool = True
) -> DataFrame:
"""
Get the mode(s) of each element along the selected axis.
@@ -9231,7 +9240,11 @@ def f(s):
return data.apply(f, axis=axis)
def quantile(
- self, q=0.5, axis=0, numeric_only: bool = True, interpolation: str = "linear"
+ self,
+ q=0.5,
+ axis: Axis = 0,
+ numeric_only: bool = True,
+ interpolation: str = "linear",
):
"""
Return values at the given quantile over requested axis.
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Splitting this away from #38416 | https://api.github.com/repos/pandas-dev/pandas/pulls/38441 | 2020-12-13T05:37:03Z | 2020-12-13T22:04:41Z | 2020-12-13T22:04:41Z | 2020-12-13T22:04:47Z |
TYP: pandas/core/frame.py (easy: bool/str) | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index fd7820196f9a9..650809ebcf771 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1440,7 +1440,7 @@ def to_numpy(
return result
- def to_dict(self, orient="dict", into=dict):
+ def to_dict(self, orient: str = "dict", into=dict):
"""
Convert the DataFrame to a dictionary.
@@ -1615,15 +1615,15 @@ def to_dict(self, orient="dict", into=dict):
def to_gbq(
self,
- destination_table,
- project_id=None,
+ destination_table: str,
+ project_id: Optional[str] = None,
chunksize=None,
- reauth=False,
- if_exists="fail",
- auth_local_webserver=False,
+ reauth: bool = False,
+ if_exists: str = "fail",
+ auth_local_webserver: bool = False,
table_schema=None,
- location=None,
- progress_bar=True,
+ location: Optional[str] = None,
+ progress_bar: bool = True,
credentials=None,
) -> None:
"""
@@ -1728,7 +1728,7 @@ def from_records(
index=None,
exclude=None,
columns=None,
- coerce_float=False,
+ coerce_float: bool = False,
nrows=None,
) -> DataFrame:
"""
@@ -2489,7 +2489,7 @@ def to_html(
max_rows=None,
max_cols=None,
show_dimensions=False,
- decimal=".",
+ decimal: str = ".",
bold_rows=True,
classes=None,
escape=True,
@@ -3311,7 +3311,7 @@ def _box_col_values(self, values, loc: int) -> Series:
# ----------------------------------------------------------------------
# Unsorted
- def query(self, expr, inplace=False, **kwargs):
+ def query(self, expr: str, inplace: bool = False, **kwargs):
"""
Query the columns of a DataFrame with a boolean expression.
@@ -3475,7 +3475,7 @@ def query(self, expr, inplace=False, **kwargs):
else:
return result
- def eval(self, expr, inplace=False, **kwargs):
+ def eval(self, expr: str, inplace: bool = False, **kwargs):
"""
Evaluate a string describing operations on DataFrame columns.
@@ -3732,7 +3732,7 @@ def extract_unique_dtypes_from_dtypes_set(
return self.iloc[:, keep_these.values]
- def insert(self, loc, column, value, allow_duplicates=False) -> None:
+ def insert(self, loc, column, value, allow_duplicates: bool = False) -> None:
"""
Insert column into DataFrame at specified location.
@@ -3846,7 +3846,7 @@ def assign(self, **kwargs) -> DataFrame:
data[k] = com.apply_if_callable(v, data)
return data
- def _sanitize_column(self, key, value, broadcast=True):
+ def _sanitize_column(self, key, value, broadcast: bool = True):
"""
Ensures new columns (which go into the BlockManager as new blocks) are
always copied and converted into an array.
@@ -4046,7 +4046,7 @@ def _reindex_index(
self,
new_index,
method,
- copy,
+ copy: bool,
level,
fill_value=np.nan,
limit=None,
@@ -4066,7 +4066,7 @@ def _reindex_columns(
self,
new_columns,
method,
- copy,
+ copy: bool,
level,
fill_value=None,
limit=None,
@@ -4082,7 +4082,7 @@ def _reindex_columns(
allow_dups=False,
)
- def _reindex_multi(self, axes, copy, fill_value) -> DataFrame:
+ def _reindex_multi(self, axes, copy: bool, fill_value) -> DataFrame:
"""
We are guaranteed non-Nones in the axes.
"""
@@ -4106,12 +4106,12 @@ def _reindex_multi(self, axes, copy, fill_value) -> DataFrame:
def align(
self,
other,
- join="outer",
+ join: str = "outer",
axis=None,
level=None,
- copy=True,
+ copy: bool = True,
fill_value=None,
- method=None,
+ method: Optional[str] = None,
limit=None,
fill_axis=0,
broadcast_axis=None,
@@ -4199,8 +4199,8 @@ def drop(
index=None,
columns=None,
level=None,
- inplace=False,
- errors="raise",
+ inplace: bool = False,
+ errors: str = "raise",
):
"""
Drop specified labels from rows or columns.
@@ -4470,9 +4470,9 @@ def rename(
def fillna(
self,
value=None,
- method=None,
+ method: Optional[str] = None,
axis=None,
- inplace=False,
+ inplace: bool = False,
limit=None,
downcast=None,
) -> Optional[DataFrame]:
@@ -4533,10 +4533,10 @@ def replace(
self,
to_replace=None,
value=None,
- inplace=False,
+ inplace: bool = False,
limit=None,
- regex=False,
- method="pad",
+ regex: bool = False,
+ method: str = "pad",
):
return super().replace(
to_replace=to_replace,
@@ -4616,7 +4616,12 @@ def shift(
)
def set_index(
- self, keys, drop=True, append=False, inplace=False, verify_integrity=False
+ self,
+ keys,
+ drop: bool = True,
+ append: bool = False,
+ inplace: bool = False,
+ verify_integrity: bool = False,
):
"""
Set the DataFrame index using existing columns.
@@ -5055,7 +5060,9 @@ def notna(self) -> DataFrame:
def notnull(self) -> DataFrame:
return ~self.isna()
- def dropna(self, axis=0, how="any", thresh=None, subset=None, inplace=False):
+ def dropna(
+ self, axis=0, how: str = "any", thresh=None, subset=None, inplace: bool = False
+ ):
"""
Remove missing values.
@@ -5436,10 +5443,10 @@ def sort_values( # type: ignore[override]
by,
axis=0,
ascending=True,
- inplace=False,
- kind="quicksort",
- na_position="last",
- ignore_index=False,
+ inplace: bool = False,
+ kind: str = "quicksort",
+ na_position: str = "last",
+ ignore_index: bool = False,
key: ValueKeyFunc = None,
):
inplace = validate_bool_kwarg(inplace, "inplace")
@@ -5701,7 +5708,7 @@ def value_counts(
return counts
- def nlargest(self, n, columns, keep="first") -> DataFrame:
+ def nlargest(self, n, columns, keep: str = "first") -> DataFrame:
"""
Return the first `n` rows ordered by `columns` in descending order.
@@ -5810,7 +5817,7 @@ def nlargest(self, n, columns, keep="first") -> DataFrame:
"""
return algorithms.SelectNFrame(self, n=n, keep=keep, columns=columns).nlargest()
- def nsmallest(self, n, columns, keep="first") -> DataFrame:
+ def nsmallest(self, n, columns, keep: str = "first") -> DataFrame:
"""
Return the first `n` rows ordered by `columns` in ascending order.
@@ -6234,7 +6241,7 @@ def compare(
)
def combine(
- self, other: DataFrame, func, fill_value=None, overwrite=True
+ self, other: DataFrame, func, fill_value=None, overwrite: bool = True
) -> DataFrame:
"""
Perform column-wise combine with another DataFrame.
@@ -6462,7 +6469,12 @@ def combiner(x, y):
return self.combine(other, combiner, overwrite=False)
def update(
- self, other, join="left", overwrite=True, filter_func=None, errors="ignore"
+ self,
+ other,
+ join: str = "left",
+ overwrite: bool = True,
+ filter_func=None,
+ errors: str = "ignore",
) -> None:
"""
Modify in place using non-NA values from another DataFrame.
@@ -7055,7 +7067,7 @@ def pivot_table(
observed=observed,
)
- def stack(self, level=-1, dropna=True):
+ def stack(self, level=-1, dropna: bool = True):
"""
Stack the prescribed level(s) from columns to index.
@@ -7636,7 +7648,7 @@ def transform(
assert isinstance(result, DataFrame)
return result
- def apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwds):
+ def apply(self, func, axis=0, raw: bool = False, result_type=None, args=(), **kwds):
"""
Apply a function along an axis of the DataFrame.
@@ -7861,7 +7873,11 @@ def infer(x):
# Merging / joining methods
def append(
- self, other, ignore_index=False, verify_integrity=False, sort=False
+ self,
+ other,
+ ignore_index: bool = False,
+ verify_integrity: bool = False,
+ sort: bool = False,
) -> DataFrame:
"""
Append rows of `other` to the end of caller, returning a new object.
@@ -8002,7 +8018,13 @@ def append(
).__finalize__(self, method="append")
def join(
- self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False
+ self,
+ other,
+ on=None,
+ how: str = "left",
+ lsuffix: str = "",
+ rsuffix: str = "",
+ sort: bool = False,
) -> DataFrame:
"""
Join columns of another DataFrame.
@@ -8639,7 +8661,7 @@ def c(x):
# ----------------------------------------------------------------------
# ndarray-like stats methods
- def count(self, axis=0, level=None, numeric_only=False):
+ def count(self, axis=0, level=None, numeric_only: bool = False):
"""
Count non-NA cells for each column or row.
@@ -8794,8 +8816,8 @@ def _reduce(
name: str,
*,
axis=0,
- skipna=True,
- numeric_only=None,
+ skipna: bool = True,
+ numeric_only: Optional[bool] = None,
filter_type=None,
**kwds,
):
@@ -8901,7 +8923,7 @@ def _get_data() -> DataFrame:
result = self._constructor_sliced(result, index=labels)
return result
- def nunique(self, axis=0, dropna=True) -> Series:
+ def nunique(self, axis=0, dropna: bool = True) -> Series:
"""
Count distinct observations over requested axis.
@@ -8941,7 +8963,7 @@ def nunique(self, axis=0, dropna=True) -> Series:
"""
return self.apply(Series.nunique, axis=axis, dropna=dropna)
- def idxmin(self, axis=0, skipna=True) -> Series:
+ def idxmin(self, axis=0, skipna: bool = True) -> Series:
"""
Return index of first occurrence of minimum over requested axis.
@@ -9018,7 +9040,7 @@ def idxmin(self, axis=0, skipna=True) -> Series:
result = [index[i] if i >= 0 else np.nan for i in indices]
return self._constructor_sliced(result, index=self._get_agg_axis(axis))
- def idxmax(self, axis=0, skipna=True) -> Series:
+ def idxmax(self, axis=0, skipna: bool = True) -> Series:
"""
Return index of first occurrence of maximum over requested axis.
@@ -9106,7 +9128,9 @@ def _get_agg_axis(self, axis_num: int) -> Index:
else:
raise ValueError(f"Axis must be 0 or 1 (got {repr(axis_num)})")
- def mode(self, axis=0, numeric_only=False, dropna=True) -> DataFrame:
+ def mode(
+ self, axis=0, numeric_only: bool = False, dropna: bool = True
+ ) -> DataFrame:
"""
Get the mode(s) of each element along the selected axis.
@@ -9193,7 +9217,9 @@ def f(s):
return data.apply(f, axis=axis)
- def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation="linear"):
+ def quantile(
+ self, q=0.5, axis=0, numeric_only: bool = True, interpolation: str = "linear"
+ ):
"""
Return values at the given quantile over requested axis.
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Splitting this away from #38416 | https://api.github.com/repos/pandas-dev/pandas/pulls/38440 | 2020-12-13T04:39:41Z | 2020-12-13T17:22:09Z | 2020-12-13T17:22:09Z | 2020-12-13T17:22:09Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.