title stringlengths 1 185 | diff stringlengths 0 32.2M | body stringlengths 0 123k ⌀ | url stringlengths 57 58 | created_at stringlengths 20 20 | closed_at stringlengths 20 20 | merged_at stringlengths 20 20 ⌀ | updated_at stringlengths 20 20 |
|---|---|---|---|---|---|---|---|
BUG: Respect check_dtype in assert_series_equal | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index a667d0663aa31..0d3a9a8f969a4 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -401,6 +401,7 @@ Other
- Bug in :meth:`DataFrame.to_records` incorrectly losing timezone information in timezone-aware ``datetime64`` columns (:issue:`32535`)
- Fixed :func:`pandas.testing.assert_series_equal` to correctly raise if left object is a different subclass with ``check_series_type=True`` (:issue:`32670`).
- :meth:`IntegerArray.astype` now supports ``datetime64`` dtype (:issue:32538`)
+- Fixed bug in :func:`pandas.testing.assert_series_equal` where dtypes were checked for ``Interval`` and ``ExtensionArray`` operands when ``check_dtype`` was ``False`` (:issue:`32747`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/_testing.py b/pandas/_testing.py
index d473b453d77d2..f96e3872eb8bd 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -1160,7 +1160,7 @@ def assert_series_equal(
f"is not equal to {right._values}."
)
raise AssertionError(msg)
- elif is_interval_dtype(left.dtype) or is_interval_dtype(right.dtype):
+ elif is_interval_dtype(left.dtype) and is_interval_dtype(right.dtype):
assert_interval_array_equal(left.array, right.array)
elif is_categorical_dtype(left.dtype) or is_categorical_dtype(right.dtype):
_testing.assert_almost_equal(
@@ -1170,7 +1170,7 @@ def assert_series_equal(
check_dtype=check_dtype,
obj=str(obj),
)
- elif is_extension_array_dtype(left.dtype) or is_extension_array_dtype(right.dtype):
+ elif is_extension_array_dtype(left.dtype) and is_extension_array_dtype(right.dtype):
assert_extension_array_equal(left._values, right._values)
elif needs_i8_conversion(left.dtype) or needs_i8_conversion(right.dtype):
# DatetimeArray or TimedeltaArray
diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py
index 3090343ba2fd9..4bcf7087c239d 100644
--- a/pandas/tests/util/test_assert_frame_equal.py
+++ b/pandas/tests/util/test_assert_frame_equal.py
@@ -1,5 +1,6 @@
import pytest
+import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
@@ -218,3 +219,41 @@ def test_frame_equal_unicode(df1, df2, msg, by_blocks_fixture, obj_fixture):
msg = msg.format(obj=obj_fixture)
with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture)
+
+
+def test_assert_frame_equal_extension_dtype_mismatch():
+ # https://github.com/pandas-dev/pandas/issues/32747
+ left = DataFrame({"a": [1, 2, 3]}, dtype="Int64")
+ right = left.astype(int)
+
+ msg = (
+ "Attributes of DataFrame\\.iloc\\[:, 0\\] "
+ '\\(column name="a"\\) are different\n\n'
+ 'Attribute "dtype" are different\n'
+ "\\[left\\]: Int64\n"
+ "\\[right\\]: int[32|64]"
+ )
+
+ tm.assert_frame_equal(left, right, check_dtype=False)
+
+ with pytest.raises(AssertionError, match=msg):
+ tm.assert_frame_equal(left, right, check_dtype=True)
+
+
+def test_assert_frame_equal_interval_dtype_mismatch():
+ # https://github.com/pandas-dev/pandas/issues/32747
+ left = DataFrame({"a": [pd.Interval(0, 1)]}, dtype="interval")
+ right = left.astype(object)
+
+ msg = (
+ "Attributes of DataFrame\\.iloc\\[:, 0\\] "
+ '\\(column name="a"\\) are different\n\n'
+ 'Attribute "dtype" are different\n'
+ "\\[left\\]: interval\\[int64\\]\n"
+ "\\[right\\]: object"
+ )
+
+ tm.assert_frame_equal(left, right, check_dtype=False)
+
+ with pytest.raises(AssertionError, match=msg):
+ tm.assert_frame_equal(left, right, check_dtype=True)
diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py
index 2550b32446055..49f5489a2e2f1 100644
--- a/pandas/tests/util/test_assert_series_equal.py
+++ b/pandas/tests/util/test_assert_series_equal.py
@@ -1,5 +1,6 @@
import pytest
+import pandas as pd
from pandas import Categorical, DataFrame, Series
import pandas._testing as tm
@@ -196,6 +197,40 @@ def test_series_equal_categorical_mismatch(check_categorical):
_assert_series_equal_both(s1, s2, check_categorical=check_categorical)
+def test_assert_series_equal_extension_dtype_mismatch():
+ # https://github.com/pandas-dev/pandas/issues/32747
+ left = Series(pd.array([1, 2, 3], dtype="Int64"))
+ right = left.astype(int)
+
+ msg = """Attributes of Series are different
+
+Attribute "dtype" are different
+\\[left\\]: Int64
+\\[right\\]: int[32|64]"""
+
+ tm.assert_series_equal(left, right, check_dtype=False)
+
+ with pytest.raises(AssertionError, match=msg):
+ tm.assert_series_equal(left, right, check_dtype=True)
+
+
+def test_assert_series_equal_interval_dtype_mismatch():
+ # https://github.com/pandas-dev/pandas/issues/32747
+ left = Series([pd.Interval(0, 1)], dtype="interval")
+ right = left.astype(object)
+
+ msg = """Attributes of Series are different
+
+Attribute "dtype" are different
+\\[left\\]: interval\\[int64\\]
+\\[right\\]: object"""
+
+ tm.assert_series_equal(left, right, check_dtype=False)
+
+ with pytest.raises(AssertionError, match=msg):
+ tm.assert_series_equal(left, right, check_dtype=True)
+
+
def test_series_equal_series_type():
class MySeries(Series):
pass
| - [x] closes #32747
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
I'm not sure if https://github.com/pandas-dev/pandas/blob/master/pandas/_testing.py#L1174 needs to change too?
cc @jorisvandenbossche | https://api.github.com/repos/pandas-dev/pandas/pulls/32757 | 2020-03-16T18:40:33Z | 2020-03-17T19:33:41Z | 2020-03-17T19:33:40Z | 2020-03-17T20:56:21Z |
copy license text from: tidyverse/haven | diff --git a/LICENSES/HAVEN_LICENSE b/LICENSES/HAVEN_LICENSE
index 2f444cb44d505..ce1b07b783e74 100644
--- a/LICENSES/HAVEN_LICENSE
+++ b/LICENSES/HAVEN_LICENSE
@@ -1,2 +1,21 @@
-YEAR: 2013-2016
-COPYRIGHT HOLDER: Hadley Wickham; RStudio; and Evan Miller
+# MIT License
+
+Copyright (c) 2019 Hadley Wickham; RStudio; and Evan Miller
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
| The existing HAVEN_LICENSE file was lacking any form of actual license.
After checking the pandas source, it appears that the reference to HAVEN
is in relation to tidyverse/haven, copying the license from
tidyverse/haven for clarity.
Signed-off-by: Jamin Collins <jamin@amazon.com>
| https://api.github.com/repos/pandas-dev/pandas/pulls/32756 | 2020-03-16T17:13:07Z | 2020-03-18T00:00:58Z | 2020-03-18T00:00:58Z | 2020-03-18T00:01:06Z |
REF: avoid _internal_get_values in json get_values | diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c
index e2deffb46c4e6..db1feccb4d0c6 100644
--- a/pandas/_libs/src/ujson/python/objToJSON.c
+++ b/pandas/_libs/src/ujson/python/objToJSON.c
@@ -222,13 +222,19 @@ static PyObject *get_values(PyObject *obj) {
PRINTMARK();
- if (PyObject_HasAttrString(obj, "_internal_get_values")) {
+ if (PyObject_TypeCheck(obj, cls_index) || PyObject_TypeCheck(obj, cls_series)) {
+ // The special cases to worry about are dt64tz and category[dt64tz].
+ // In both cases we want the UTC-localized datetime64 ndarray,
+ // without going through and object array of Timestamps.
PRINTMARK();
- values = PyObject_CallMethod(obj, "_internal_get_values", NULL);
+ values = PyObject_GetAttrString(obj, "values");
if (values == NULL) {
// Clear so we can subsequently try another method
PyErr_Clear();
+ } else if (PyObject_HasAttrString(values, "__array__")) {
+ // We may have gotten a Categorical or Sparse array so call np.array
+ values = PyObject_CallMethod(values, "__array__", NULL);
} else if (!PyArray_CheckExact(values)) {
// Didn't get a numpy array, so keep trying
PRINTMARK();
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 9720819adeb16..5504856e002c6 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5382,26 +5382,6 @@ def _values(self) -> np.ndarray:
"""internal implementation"""
return self.values
- def _internal_get_values(self) -> np.ndarray:
- """
- Return an ndarray after converting sparse values to dense.
-
- This is the same as ``.values`` for non-sparse data. For sparse
- data contained in a `SparseArray`, the data are first
- converted to a dense representation.
-
- Returns
- -------
- numpy.ndarray
- Numpy representation of DataFrame.
-
- See Also
- --------
- values : Numpy representation of DataFrame.
- SparseArray : Container for sparse data.
- """
- return self.values
-
@property
def dtypes(self):
"""
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 31966489403f4..943a82900379c 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -3870,50 +3870,6 @@ def _values(self) -> Union[ExtensionArray, np.ndarray]:
"""
return self._data
- def _internal_get_values(self) -> np.ndarray:
- """
- Return `Index` data as an `numpy.ndarray`.
-
- Returns
- -------
- numpy.ndarray
- A one-dimensional numpy array of the `Index` values.
-
- See Also
- --------
- Index.values : The attribute that _internal_get_values wraps.
-
- Examples
- --------
- Getting the `Index` values of a `DataFrame`:
-
- >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],
- ... index=['a', 'b', 'c'], columns=['A', 'B', 'C'])
- >>> df
- A B C
- a 1 2 3
- b 4 5 6
- c 7 8 9
- >>> df.index._internal_get_values()
- array(['a', 'b', 'c'], dtype=object)
-
- Standalone `Index` values:
-
- >>> idx = pd.Index(['1', '2', '3'])
- >>> idx._internal_get_values()
- array(['1', '2', '3'], dtype=object)
-
- `MultiIndex` arrays also have only one dimension:
-
- >>> midx = pd.MultiIndex.from_arrays([[1, 2, 3], ['a', 'b', 'c']],
- ... names=('number', 'letter'))
- >>> midx._internal_get_values()
- array([(1, 'a'), (2, 'b'), (3, 'c')], dtype=object)
- >>> midx._internal_get_values().ndim
- 1
- """
- return self.values
-
def _get_engine_target(self) -> np.ndarray:
"""
Get the ndarray that we can pass to the IndexEngine constructor.
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 07707e1b0093c..cab2bd5146745 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -237,9 +237,6 @@ def get_block_values_for_json(self) -> np.ndarray:
# TODO(2DEA): reshape will be unnecessary with 2D EAs
return np.asarray(self.values).reshape(self.shape)
- def to_dense(self):
- return self.values.view()
-
@property
def fill_value(self):
return np.nan
@@ -1820,9 +1817,6 @@ def get_values(self, dtype=None):
def array_values(self) -> ExtensionArray:
return self.values
- def to_dense(self):
- return np.asarray(self.values)
-
def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs):
"""override to use ExtensionArray astype for the conversion"""
values = self.values
@@ -2378,12 +2372,6 @@ def get_values(self, dtype=None):
values = values.reshape(1, -1)
return values
- def to_dense(self):
- # we request M8[ns] dtype here, even though it discards tzinfo,
- # as lots of code (e.g. anything using values_from_object)
- # expects that behavior.
- return np.asarray(self.values, dtype=_NS_DTYPE)
-
def _slice(self, slicer):
""" return a slice of my values """
if isinstance(slicer, tuple):
@@ -2911,12 +2899,6 @@ def __init__(self, values, placement, ndim=None):
def _holder(self):
return Categorical
- def to_dense(self):
- # Categorical.get_values returns a DatetimeIndex for datetime
- # categories, so we can't simply use `np.asarray(self.values)` like
- # other types.
- return self.values._internal_get_values()
-
def to_native_types(self, slicer=None, na_rep="", quoting=None, **kwargs):
""" convert to our native types format, slicing if desired """
values = self.values
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 501555aee21b7..1ba112a6d184d 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -528,18 +528,6 @@ def _values(self):
def array(self) -> ExtensionArray:
return self._data._block.array_values()
- def _internal_get_values(self):
- """
- Same as values (but handles sparseness conversions); is a view.
-
- Returns
- -------
- numpy.ndarray
- Data of the Series.
- """
- blk = self._data._block
- return np.array(blk.to_dense(), copy=False)
-
# ops
def ravel(self, order="C"):
"""
| cc @WillAyd
As mentioned in #32731, this changes the behavior for CategoricalIndex[dt64tz] and Series with that for its index. Suggestions for where tests for that should go?
Note: the Categorical[dt64tz] cases still do a trip through object-dtype; I don't want to futz with that in C-space. | https://api.github.com/repos/pandas-dev/pandas/pulls/32754 | 2020-03-16T16:16:39Z | 2020-03-17T02:06:28Z | 2020-03-17T02:06:28Z | 2020-03-17T02:21:49Z |
DOC: Partial fix SA04 errors in docstrings #28792 | diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 85386923e9912..acd4a68e3fd09 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -217,8 +217,8 @@ def merge_ordered(
See Also
--------
- merge
- merge_asof
+ merge : Merge with a database-style join.
+ merge_asof : Merge on nearest keys.
Examples
--------
@@ -364,8 +364,8 @@ def merge_asof(
See Also
--------
- merge
- merge_ordered
+ merge : Merge with a database-style join.
+ merge_ordered : Merge with optional filling/interpolation.
Examples
--------
| - [x] xref #28792
My first PR. Tell me if I'm doing this incorrectly.
| https://api.github.com/repos/pandas-dev/pandas/pulls/32753 | 2020-03-16T15:29:53Z | 2020-03-16T22:42:15Z | 2020-03-16T22:42:15Z | 2020-03-17T08:12:40Z |
TST: re-enable downstream geopandas test | diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index b2a85b539fd86..122ef1f47968e 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -107,7 +107,6 @@ def test_pandas_datareader():
# importing from pandas, Cython import warning
@pytest.mark.filterwarnings("ignore:can't resolve:ImportWarning")
-@pytest.mark.skip(reason="Anaconda installation issue - GH32144")
def test_geopandas():
geopandas = import_module("geopandas") # noqa
| Closes https://github.com/pandas-dev/pandas/issues/32144 | https://api.github.com/repos/pandas-dev/pandas/pulls/32752 | 2020-03-16T13:56:56Z | 2020-03-16T16:55:37Z | 2020-03-16T16:55:37Z | 2020-03-16T16:55:59Z |
Backport PR #32746: DOC: start 1.0.3 | diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst
index 76d13478612ee..6764fbd736d46 100644
--- a/doc/source/whatsnew/index.rst
+++ b/doc/source/whatsnew/index.rst
@@ -16,9 +16,10 @@ Version 1.0
.. toctree::
:maxdepth: 2
- v1.0.0
- v1.0.1
+ v1.0.3
v1.0.2
+ v1.0.1
+ v1.0.0
Version 0.25
------------
diff --git a/doc/source/whatsnew/v1.0.2.rst b/doc/source/whatsnew/v1.0.2.rst
index d3921271264c2..cfa3ee6acc29d 100644
--- a/doc/source/whatsnew/v1.0.2.rst
+++ b/doc/source/whatsnew/v1.0.2.rst
@@ -123,4 +123,4 @@ Bug fixes
Contributors
~~~~~~~~~~~~
-.. contributors:: v1.0.1..v1.0.2|HEAD
+.. contributors:: v1.0.1..v1.0.2
diff --git a/doc/source/whatsnew/v1.0.3.rst b/doc/source/whatsnew/v1.0.3.rst
new file mode 100644
index 0000000000000..17f1bdc365518
--- /dev/null
+++ b/doc/source/whatsnew/v1.0.3.rst
@@ -0,0 +1,27 @@
+
+.. _whatsnew_103:
+
+What's new in 1.0.3 (March ??, 2020)
+------------------------------------
+
+These are the changes in pandas 1.0.3. See :ref:`release` for a full changelog
+including other versions of pandas.
+
+{{ header }}
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_103.regressions:
+
+Fixed regressions
+~~~~~~~~~~~~~~~~~
+
+.. _whatsnew_103.bug_fixes:
+
+Bug fixes
+~~~~~~~~~
+
+Contributors
+~~~~~~~~~~~~
+
+.. contributors:: v1.0.2..v1.0.3|HEAD
| https://github.com/pandas-dev/pandas/pull/32746 | https://api.github.com/repos/pandas-dev/pandas/pulls/32750 | 2020-03-16T13:23:59Z | 2020-03-16T14:34:52Z | 2020-03-16T14:34:52Z | 2020-03-16T14:34:53Z |
DOC: start 1.0.3 | diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst
index cbfeb0352c283..50333b54ca903 100644
--- a/doc/source/whatsnew/index.rst
+++ b/doc/source/whatsnew/index.rst
@@ -24,6 +24,7 @@ Version 1.0
.. toctree::
:maxdepth: 2
+ v1.0.3
v1.0.2
v1.0.1
v1.0.0
diff --git a/doc/source/whatsnew/v1.0.2.rst b/doc/source/whatsnew/v1.0.2.rst
index 0bfcb95b25ffd..93f6532d1e37d 100644
--- a/doc/source/whatsnew/v1.0.2.rst
+++ b/doc/source/whatsnew/v1.0.2.rst
@@ -111,4 +111,4 @@ Bug fixes
Contributors
~~~~~~~~~~~~
-.. contributors:: v1.0.1..v1.0.2|HEAD
+.. contributors:: v1.0.1..v1.0.2
diff --git a/doc/source/whatsnew/v1.0.3.rst b/doc/source/whatsnew/v1.0.3.rst
new file mode 100644
index 0000000000000..17f1bdc365518
--- /dev/null
+++ b/doc/source/whatsnew/v1.0.3.rst
@@ -0,0 +1,27 @@
+
+.. _whatsnew_103:
+
+What's new in 1.0.3 (March ??, 2020)
+------------------------------------
+
+These are the changes in pandas 1.0.3. See :ref:`release` for a full changelog
+including other versions of pandas.
+
+{{ header }}
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_103.regressions:
+
+Fixed regressions
+~~~~~~~~~~~~~~~~~
+
+.. _whatsnew_103.bug_fixes:
+
+Bug fixes
+~~~~~~~~~
+
+Contributors
+~~~~~~~~~~~~
+
+.. contributors:: v1.0.2..v1.0.3|HEAD
| https://api.github.com/repos/pandas-dev/pandas/pulls/32746 | 2020-03-16T11:38:25Z | 2020-03-16T13:14:59Z | 2020-03-16T13:14:58Z | 2020-03-16T14:37:42Z | |
CLN: Split pandas/tests/base/test_ops.py | diff --git a/pandas/tests/base/common.py b/pandas/tests/base/common.py
new file mode 100644
index 0000000000000..b09710a974c2a
--- /dev/null
+++ b/pandas/tests/base/common.py
@@ -0,0 +1,9 @@
+from typing import Any
+
+from pandas import Index
+
+
+def allow_na_ops(obj: Any) -> bool:
+ """Whether to skip test cases including NaN"""
+ is_bool_index = isinstance(obj, Index) and obj.is_boolean()
+ return not is_bool_index and obj._can_hold_na
diff --git a/pandas/tests/base/test_drop_duplicates.py b/pandas/tests/base/test_drop_duplicates.py
new file mode 100644
index 0000000000000..4032890b4db18
--- /dev/null
+++ b/pandas/tests/base/test_drop_duplicates.py
@@ -0,0 +1,30 @@
+from datetime import datetime
+
+import numpy as np
+
+import pandas as pd
+import pandas._testing as tm
+
+
+def test_drop_duplicates_series_vs_dataframe():
+ # GH 14192
+ df = pd.DataFrame(
+ {
+ "a": [1, 1, 1, "one", "one"],
+ "b": [2, 2, np.nan, np.nan, np.nan],
+ "c": [3, 3, np.nan, np.nan, "three"],
+ "d": [1, 2, 3, 4, 4],
+ "e": [
+ datetime(2015, 1, 1),
+ datetime(2015, 1, 1),
+ datetime(2015, 2, 1),
+ pd.NaT,
+ pd.NaT,
+ ],
+ }
+ )
+ for column in df.columns:
+ for keep in ["first", "last", False]:
+ dropped_frame = df[[column]].drop_duplicates(keep=keep)
+ dropped_series = df[column].drop_duplicates(keep=keep)
+ tm.assert_frame_equal(dropped_frame, dropped_series.to_frame())
diff --git a/pandas/tests/base/test_factorize.py b/pandas/tests/base/test_factorize.py
new file mode 100644
index 0000000000000..415a8b7e4362f
--- /dev/null
+++ b/pandas/tests/base/test_factorize.py
@@ -0,0 +1,28 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize("sort", [True, False])
+def test_factorize(index_or_series_obj, sort):
+ obj = index_or_series_obj
+ result_codes, result_uniques = obj.factorize(sort=sort)
+
+ constructor = pd.Index
+ if isinstance(obj, pd.MultiIndex):
+ constructor = pd.MultiIndex.from_tuples
+ expected_uniques = constructor(obj.unique())
+
+ if sort:
+ expected_uniques = expected_uniques.sort_values()
+
+ # construct an integer ndarray so that
+ # `expected_uniques.take(expected_codes)` is equal to `obj`
+ expected_uniques_list = list(expected_uniques)
+ expected_codes = [expected_uniques_list.index(val) for val in obj]
+ expected_codes = np.asarray(expected_codes, dtype=np.intp)
+
+ tm.assert_numpy_array_equal(result_codes, expected_codes)
+ tm.assert_index_equal(result_uniques, expected_uniques)
diff --git a/pandas/tests/base/test_fillna.py b/pandas/tests/base/test_fillna.py
new file mode 100644
index 0000000000000..5e50a9e2d1c7f
--- /dev/null
+++ b/pandas/tests/base/test_fillna.py
@@ -0,0 +1,70 @@
+"""
+Though Index.fillna and Series.fillna has separate impl,
+test here to confirm these works as the same
+"""
+
+import numpy as np
+import pytest
+
+from pandas._libs.tslib import iNaT
+
+from pandas.core.dtypes.common import needs_i8_conversion
+from pandas.core.dtypes.generic import ABCMultiIndex
+
+from pandas import Index
+import pandas._testing as tm
+from pandas.tests.base.common import allow_na_ops
+
+
+def test_fillna(index_or_series_obj):
+ # GH 11343
+ obj = index_or_series_obj
+ if isinstance(obj, ABCMultiIndex):
+ pytest.skip("MultiIndex doesn't support isna")
+
+ # values will not be changed
+ fill_value = obj.values[0] if len(obj) > 0 else 0
+ result = obj.fillna(fill_value)
+ if isinstance(obj, Index):
+ tm.assert_index_equal(obj, result)
+ else:
+ tm.assert_series_equal(obj, result)
+
+ # check shallow_copied
+ assert obj is not result
+
+
+@pytest.mark.parametrize("null_obj", [np.nan, None])
+def test_fillna_null(null_obj, index_or_series_obj):
+ # GH 11343
+ obj = index_or_series_obj
+ klass = type(obj)
+
+ if not allow_na_ops(obj):
+ pytest.skip(f"{klass} doesn't allow for NA operations")
+ elif len(obj) < 1:
+ pytest.skip("Test doesn't make sense on empty data")
+ elif isinstance(obj, ABCMultiIndex):
+ pytest.skip(f"MultiIndex can't hold '{null_obj}'")
+
+ values = obj.values
+ fill_value = values[0]
+ expected = values.copy()
+ if needs_i8_conversion(obj):
+ values[0:2] = iNaT
+ expected[0:2] = fill_value
+ else:
+ values[0:2] = null_obj
+ expected[0:2] = fill_value
+
+ expected = klass(expected)
+ obj = klass(values)
+
+ result = obj.fillna(fill_value)
+ if isinstance(obj, Index):
+ tm.assert_index_equal(result, expected)
+ else:
+ tm.assert_series_equal(result, expected)
+
+ # check shallow_copied
+ assert obj is not result
diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py
new file mode 100644
index 0000000000000..6bab60f05ce89
--- /dev/null
+++ b/pandas/tests/base/test_misc.py
@@ -0,0 +1,204 @@
+import sys
+
+import numpy as np
+import pytest
+
+from pandas.compat import PYPY
+
+from pandas.core.dtypes.common import (
+ is_categorical_dtype,
+ is_datetime64_dtype,
+ is_datetime64tz_dtype,
+ is_object_dtype,
+)
+
+import pandas as pd
+from pandas import DataFrame, Index, IntervalIndex, Series
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize(
+ "op_name, op",
+ [
+ ("add", "+"),
+ ("sub", "-"),
+ ("mul", "*"),
+ ("mod", "%"),
+ ("pow", "**"),
+ ("truediv", "/"),
+ ("floordiv", "//"),
+ ],
+)
+@pytest.mark.parametrize("klass", [Series, DataFrame])
+def test_binary_ops_docstring(klass, op_name, op):
+ # not using the all_arithmetic_functions fixture with _get_opstr
+ # as _get_opstr is used internally in the dynamic implementation of the docstring
+ operand1 = klass.__name__.lower()
+ operand2 = "other"
+ expected_str = " ".join([operand1, op, operand2])
+ assert expected_str in getattr(klass, op_name).__doc__
+
+ # reverse version of the binary ops
+ expected_str = " ".join([operand2, op, operand1])
+ assert expected_str in getattr(klass, "r" + op_name).__doc__
+
+
+def test_none_comparison(series_with_simple_index):
+ series = series_with_simple_index
+ if isinstance(series.index, IntervalIndex):
+ # IntervalIndex breaks on "series[0] = np.nan" below
+ pytest.skip("IntervalIndex doesn't support assignment")
+ if len(series) < 1:
+ pytest.skip("Test doesn't make sense on empty data")
+
+ # bug brought up by #1079
+ # changed from TypeError in 0.17.0
+ series[0] = np.nan
+
+ # noinspection PyComparisonWithNone
+ result = series == None # noqa
+ assert not result.iat[0]
+ assert not result.iat[1]
+
+ # noinspection PyComparisonWithNone
+ result = series != None # noqa
+ assert result.iat[0]
+ assert result.iat[1]
+
+ result = None == series # noqa
+ assert not result.iat[0]
+ assert not result.iat[1]
+
+ result = None != series # noqa
+ assert result.iat[0]
+ assert result.iat[1]
+
+ if is_datetime64_dtype(series) or is_datetime64tz_dtype(series):
+ # Following DatetimeIndex (and Timestamp) convention,
+ # inequality comparisons with Series[datetime64] raise
+ msg = "Invalid comparison"
+ with pytest.raises(TypeError, match=msg):
+ None > series
+ with pytest.raises(TypeError, match=msg):
+ series > None
+ else:
+ result = None > series
+ assert not result.iat[0]
+ assert not result.iat[1]
+
+ result = series < None
+ assert not result.iat[0]
+ assert not result.iat[1]
+
+
+def test_ndarray_compat_properties(index_or_series_obj):
+ obj = index_or_series_obj
+
+ # Check that we work.
+ for p in ["shape", "dtype", "T", "nbytes"]:
+ assert getattr(obj, p, None) is not None
+
+ # deprecated properties
+ for p in ["flags", "strides", "itemsize", "base", "data"]:
+ assert not hasattr(obj, p)
+
+ msg = "can only convert an array of size 1 to a Python scalar"
+ with pytest.raises(ValueError, match=msg):
+ obj.item() # len > 1
+
+ assert obj.ndim == 1
+ assert obj.size == len(obj)
+
+ assert Index([1]).item() == 1
+ assert Series([1]).item() == 1
+
+
+@pytest.mark.skipif(PYPY, reason="not relevant for PyPy")
+def test_memory_usage(index_or_series_obj):
+ obj = index_or_series_obj
+ res = obj.memory_usage()
+ res_deep = obj.memory_usage(deep=True)
+
+ is_object = is_object_dtype(obj) or (
+ isinstance(obj, Series) and is_object_dtype(obj.index)
+ )
+ is_categorical = is_categorical_dtype(obj) or (
+ isinstance(obj, Series) and is_categorical_dtype(obj.index)
+ )
+
+ if len(obj) == 0:
+ assert res_deep == res == 0
+ elif is_object or is_categorical:
+ # only deep will pick them up
+ assert res_deep > res
+ else:
+ assert res == res_deep
+
+ # sys.getsizeof will call the .memory_usage with
+ # deep=True, and add on some GC overhead
+ diff = res_deep - sys.getsizeof(obj)
+ assert abs(diff) < 100
+
+
+def test_memory_usage_components_series(series_with_simple_index):
+ series = series_with_simple_index
+ total_usage = series.memory_usage(index=True)
+ non_index_usage = series.memory_usage(index=False)
+ index_usage = series.index.memory_usage()
+ assert total_usage == non_index_usage + index_usage
+
+
+def test_memory_usage_components_narrow_series(narrow_series):
+ series = narrow_series
+ total_usage = series.memory_usage(index=True)
+ non_index_usage = series.memory_usage(index=False)
+ index_usage = series.index.memory_usage()
+ assert total_usage == non_index_usage + index_usage
+
+
+def test_searchsorted(index_or_series_obj):
+ # numpy.searchsorted calls obj.searchsorted under the hood.
+ # See gh-12238
+ obj = index_or_series_obj
+
+ if isinstance(obj, pd.MultiIndex):
+ # See gh-14833
+ pytest.skip("np.searchsorted doesn't work on pd.MultiIndex")
+
+ max_obj = max(obj, default=0)
+ index = np.searchsorted(obj, max_obj)
+ assert 0 <= index <= len(obj)
+
+ index = np.searchsorted(obj, max_obj, sorter=range(len(obj)))
+ assert 0 <= index <= len(obj)
+
+
+def test_access_by_position(indices):
+ index = indices
+
+ if len(index) == 0:
+ pytest.skip("Test doesn't make sense on empty data")
+ elif isinstance(index, pd.MultiIndex):
+ pytest.skip("Can't instantiate Series from MultiIndex")
+
+ series = pd.Series(index)
+ assert index[0] == series.iloc[0]
+ assert index[5] == series.iloc[5]
+ assert index[-1] == series.iloc[-1]
+
+ size = len(index)
+ assert index[-1] == index[size - 1]
+
+ msg = f"index {size} is out of bounds for axis 0 with size {size}"
+ with pytest.raises(IndexError, match=msg):
+ index[size]
+ msg = "single positional indexer is out-of-bounds"
+ with pytest.raises(IndexError, match=msg):
+ series.iloc[size]
+
+
+def test_get_indexer_non_unique_dtype_mismatch():
+ # GH 25459
+ indexes, missing = pd.Index(["A", "B"]).get_indexer_non_unique(pd.Index([0]))
+ tm.assert_numpy_array_equal(np.array([-1], dtype=np.intp), indexes)
+ tm.assert_numpy_array_equal(np.array([0], dtype=np.int64), missing)
diff --git a/pandas/tests/base/test_ops.py b/pandas/tests/base/test_ops.py
deleted file mode 100644
index 87c7cf3b141bd..0000000000000
--- a/pandas/tests/base/test_ops.py
+++ /dev/null
@@ -1,687 +0,0 @@
-import collections
-from datetime import datetime, timedelta
-from io import StringIO
-import sys
-from typing import Any
-
-import numpy as np
-import pytest
-
-from pandas._libs.tslib import iNaT
-from pandas.compat import PYPY
-from pandas.compat.numpy import np_array_datetime64_compat
-
-from pandas.core.dtypes.common import (
- is_categorical_dtype,
- is_datetime64_dtype,
- is_datetime64tz_dtype,
- is_object_dtype,
- needs_i8_conversion,
-)
-from pandas.core.dtypes.generic import ABCMultiIndex
-
-import pandas as pd
-from pandas import (
- DataFrame,
- DatetimeIndex,
- Index,
- Interval,
- IntervalIndex,
- Series,
- Timedelta,
- TimedeltaIndex,
-)
-import pandas._testing as tm
-
-
-def allow_na_ops(obj: Any) -> bool:
- """Whether to skip test cases including NaN"""
- is_bool_index = isinstance(obj, Index) and obj.is_boolean()
- return not is_bool_index and obj._can_hold_na
-
-
-@pytest.mark.parametrize(
- "op_name, op",
- [
- ("add", "+"),
- ("sub", "-"),
- ("mul", "*"),
- ("mod", "%"),
- ("pow", "**"),
- ("truediv", "/"),
- ("floordiv", "//"),
- ],
-)
-@pytest.mark.parametrize("klass", [Series, DataFrame])
-def test_binary_ops(klass, op_name, op):
- # not using the all_arithmetic_functions fixture with _get_opstr
- # as _get_opstr is used internally in the dynamic implementation of the docstring
- operand1 = klass.__name__.lower()
- operand2 = "other"
- expected_str = " ".join([operand1, op, operand2])
- assert expected_str in getattr(klass, op_name).__doc__
-
- # reverse version of the binary ops
- expected_str = " ".join([operand2, op, operand1])
- assert expected_str in getattr(klass, "r" + op_name).__doc__
-
-
-class TestTranspose:
- errmsg = "the 'axes' parameter is not supported"
-
- def test_transpose(self, index_or_series_obj):
- obj = index_or_series_obj
- tm.assert_equal(obj.transpose(), obj)
-
- def test_transpose_non_default_axes(self, index_or_series_obj):
- obj = index_or_series_obj
- with pytest.raises(ValueError, match=self.errmsg):
- obj.transpose(1)
- with pytest.raises(ValueError, match=self.errmsg):
- obj.transpose(axes=1)
-
- def test_numpy_transpose(self, index_or_series_obj):
- obj = index_or_series_obj
- tm.assert_equal(np.transpose(obj), obj)
-
- with pytest.raises(ValueError, match=self.errmsg):
- np.transpose(obj, axes=1)
-
-
-class TestIndexOps:
- def test_none_comparison(self, series_with_simple_index):
- series = series_with_simple_index
- if isinstance(series.index, IntervalIndex):
- # IntervalIndex breaks on "series[0] = np.nan" below
- pytest.skip("IntervalIndex doesn't support assignment")
- if len(series) < 1:
- pytest.skip("Test doesn't make sense on empty data")
-
- # bug brought up by #1079
- # changed from TypeError in 0.17.0
- series[0] = np.nan
-
- # noinspection PyComparisonWithNone
- result = series == None # noqa
- assert not result.iat[0]
- assert not result.iat[1]
-
- # noinspection PyComparisonWithNone
- result = series != None # noqa
- assert result.iat[0]
- assert result.iat[1]
-
- result = None == series # noqa
- assert not result.iat[0]
- assert not result.iat[1]
-
- result = None != series # noqa
- assert result.iat[0]
- assert result.iat[1]
-
- if is_datetime64_dtype(series) or is_datetime64tz_dtype(series):
- # Following DatetimeIndex (and Timestamp) convention,
- # inequality comparisons with Series[datetime64] raise
- msg = "Invalid comparison"
- with pytest.raises(TypeError, match=msg):
- None > series
- with pytest.raises(TypeError, match=msg):
- series > None
- else:
- result = None > series
- assert not result.iat[0]
- assert not result.iat[1]
-
- result = series < None
- assert not result.iat[0]
- assert not result.iat[1]
-
- def test_ndarray_compat_properties(self, index_or_series_obj):
- obj = index_or_series_obj
-
- # Check that we work.
- for p in ["shape", "dtype", "T", "nbytes"]:
- assert getattr(obj, p, None) is not None
-
- # deprecated properties
- for p in ["flags", "strides", "itemsize", "base", "data"]:
- assert not hasattr(obj, p)
-
- msg = "can only convert an array of size 1 to a Python scalar"
- with pytest.raises(ValueError, match=msg):
- obj.item() # len > 1
-
- assert obj.ndim == 1
- assert obj.size == len(obj)
-
- assert Index([1]).item() == 1
- assert Series([1]).item() == 1
-
- def test_unique(self, index_or_series_obj):
- obj = index_or_series_obj
- obj = np.repeat(obj, range(1, len(obj) + 1))
- result = obj.unique()
-
- # dict.fromkeys preserves the order
- unique_values = list(dict.fromkeys(obj.values))
- if isinstance(obj, pd.MultiIndex):
- expected = pd.MultiIndex.from_tuples(unique_values)
- expected.names = obj.names
- tm.assert_index_equal(result, expected)
- elif isinstance(obj, pd.Index):
- expected = pd.Index(unique_values, dtype=obj.dtype)
- if is_datetime64tz_dtype(obj):
- expected = expected.normalize()
- tm.assert_index_equal(result, expected)
- else:
- expected = np.array(unique_values)
- tm.assert_numpy_array_equal(result, expected)
-
- @pytest.mark.parametrize("null_obj", [np.nan, None])
- def test_unique_null(self, null_obj, index_or_series_obj):
- obj = index_or_series_obj
-
- if not allow_na_ops(obj):
- pytest.skip("type doesn't allow for NA operations")
- elif len(obj) < 1:
- pytest.skip("Test doesn't make sense on empty data")
- elif isinstance(obj, pd.MultiIndex):
- pytest.skip(f"MultiIndex can't hold '{null_obj}'")
-
- values = obj.values
- if needs_i8_conversion(obj):
- values[0:2] = iNaT
- else:
- values[0:2] = null_obj
-
- klass = type(obj)
- repeated_values = np.repeat(values, range(1, len(values) + 1))
- obj = klass(repeated_values, dtype=obj.dtype)
- result = obj.unique()
-
- unique_values_raw = dict.fromkeys(obj.values)
- # because np.nan == np.nan is False, but None == None is True
- # np.nan would be duplicated, whereas None wouldn't
- unique_values_not_null = [
- val for val in unique_values_raw if not pd.isnull(val)
- ]
- unique_values = [null_obj] + unique_values_not_null
-
- if isinstance(obj, pd.Index):
- expected = pd.Index(unique_values, dtype=obj.dtype)
- if is_datetime64tz_dtype(obj):
- result = result.normalize()
- expected = expected.normalize()
- elif isinstance(obj, pd.CategoricalIndex):
- expected = expected.set_categories(unique_values_not_null)
- tm.assert_index_equal(result, expected)
- else:
- expected = np.array(unique_values, dtype=obj.dtype)
- tm.assert_numpy_array_equal(result, expected)
-
- def test_nunique(self, index_or_series_obj):
- obj = index_or_series_obj
- obj = np.repeat(obj, range(1, len(obj) + 1))
- expected = len(obj.unique())
- assert obj.nunique(dropna=False) == expected
-
- @pytest.mark.parametrize("null_obj", [np.nan, None])
- def test_nunique_null(self, null_obj, index_or_series_obj):
- obj = index_or_series_obj
-
- if not allow_na_ops(obj):
- pytest.skip("type doesn't allow for NA operations")
- elif isinstance(obj, pd.MultiIndex):
- pytest.skip(f"MultiIndex can't hold '{null_obj}'")
-
- values = obj.values
- if needs_i8_conversion(obj):
- values[0:2] = iNaT
- else:
- values[0:2] = null_obj
-
- klass = type(obj)
- repeated_values = np.repeat(values, range(1, len(values) + 1))
- obj = klass(repeated_values, dtype=obj.dtype)
-
- if isinstance(obj, pd.CategoricalIndex):
- assert obj.nunique() == len(obj.categories)
- assert obj.nunique(dropna=False) == len(obj.categories) + 1
- else:
- num_unique_values = len(obj.unique())
- assert obj.nunique() == max(0, num_unique_values - 1)
- assert obj.nunique(dropna=False) == max(0, num_unique_values)
-
- def test_value_counts(self, index_or_series_obj):
- obj = index_or_series_obj
- obj = np.repeat(obj, range(1, len(obj) + 1))
- result = obj.value_counts()
-
- counter = collections.Counter(obj)
- expected = pd.Series(dict(counter.most_common()), dtype=np.int64, name=obj.name)
- expected.index = expected.index.astype(obj.dtype)
- if isinstance(obj, pd.MultiIndex):
- expected.index = pd.Index(expected.index)
-
- # TODO: Order of entries with the same count is inconsistent on CI (gh-32449)
- if obj.duplicated().any():
- result = result.sort_index()
- expected = expected.sort_index()
- tm.assert_series_equal(result, expected)
-
- @pytest.mark.parametrize("null_obj", [np.nan, None])
- def test_value_counts_null(self, null_obj, index_or_series_obj):
- orig = index_or_series_obj
- obj = orig.copy()
-
- if not allow_na_ops(obj):
- pytest.skip("type doesn't allow for NA operations")
- elif len(obj) < 1:
- pytest.skip("Test doesn't make sense on empty data")
- elif isinstance(orig, pd.MultiIndex):
- pytest.skip(f"MultiIndex can't hold '{null_obj}'")
-
- values = obj.values
- if needs_i8_conversion(obj):
- values[0:2] = iNaT
- else:
- values[0:2] = null_obj
-
- klass = type(obj)
- repeated_values = np.repeat(values, range(1, len(values) + 1))
- obj = klass(repeated_values, dtype=obj.dtype)
-
- # because np.nan == np.nan is False, but None == None is True
- # np.nan would be duplicated, whereas None wouldn't
- counter = collections.Counter(obj.dropna())
- expected = pd.Series(dict(counter.most_common()), dtype=np.int64)
- expected.index = expected.index.astype(obj.dtype)
-
- result = obj.value_counts()
- if obj.duplicated().any():
- # TODO:
- # Order of entries with the same count is inconsistent on CI (gh-32449)
- expected = expected.sort_index()
- result = result.sort_index()
- tm.assert_series_equal(result, expected)
-
- # can't use expected[null_obj] = 3 as
- # IntervalIndex doesn't allow assignment
- new_entry = pd.Series({np.nan: 3}, dtype=np.int64)
- expected = expected.append(new_entry)
-
- result = obj.value_counts(dropna=False)
- if obj.duplicated().any():
- # TODO:
- # Order of entries with the same count is inconsistent on CI (gh-32449)
- expected = expected.sort_index()
- result = result.sort_index()
- tm.assert_series_equal(result, expected)
-
- def test_value_counts_inferred(self, index_or_series):
- klass = index_or_series
- s_values = ["a", "b", "b", "b", "b", "c", "d", "d", "a", "a"]
- s = klass(s_values)
- expected = Series([4, 3, 2, 1], index=["b", "a", "d", "c"])
- tm.assert_series_equal(s.value_counts(), expected)
-
- if isinstance(s, Index):
- exp = Index(np.unique(np.array(s_values, dtype=np.object_)))
- tm.assert_index_equal(s.unique(), exp)
- else:
- exp = np.unique(np.array(s_values, dtype=np.object_))
- tm.assert_numpy_array_equal(s.unique(), exp)
-
- assert s.nunique() == 4
- # don't sort, have to sort after the fact as not sorting is
- # platform-dep
- hist = s.value_counts(sort=False).sort_values()
- expected = Series([3, 1, 4, 2], index=list("acbd")).sort_values()
- tm.assert_series_equal(hist, expected)
-
- # sort ascending
- hist = s.value_counts(ascending=True)
- expected = Series([1, 2, 3, 4], index=list("cdab"))
- tm.assert_series_equal(hist, expected)
-
- # relative histogram.
- hist = s.value_counts(normalize=True)
- expected = Series([0.4, 0.3, 0.2, 0.1], index=["b", "a", "d", "c"])
- tm.assert_series_equal(hist, expected)
-
- def test_value_counts_bins(self, index_or_series):
- klass = index_or_series
- s_values = ["a", "b", "b", "b", "b", "c", "d", "d", "a", "a"]
- s = klass(s_values)
-
- # bins
- msg = "bins argument only works with numeric data"
- with pytest.raises(TypeError, match=msg):
- s.value_counts(bins=1)
-
- s1 = Series([1, 1, 2, 3])
- res1 = s1.value_counts(bins=1)
- exp1 = Series({Interval(0.997, 3.0): 4})
- tm.assert_series_equal(res1, exp1)
- res1n = s1.value_counts(bins=1, normalize=True)
- exp1n = Series({Interval(0.997, 3.0): 1.0})
- tm.assert_series_equal(res1n, exp1n)
-
- if isinstance(s1, Index):
- tm.assert_index_equal(s1.unique(), Index([1, 2, 3]))
- else:
- exp = np.array([1, 2, 3], dtype=np.int64)
- tm.assert_numpy_array_equal(s1.unique(), exp)
-
- assert s1.nunique() == 3
-
- # these return the same
- res4 = s1.value_counts(bins=4, dropna=True)
- intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0])
- exp4 = Series([2, 1, 1, 0], index=intervals.take([0, 3, 1, 2]))
- tm.assert_series_equal(res4, exp4)
-
- res4 = s1.value_counts(bins=4, dropna=False)
- intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0])
- exp4 = Series([2, 1, 1, 0], index=intervals.take([0, 3, 1, 2]))
- tm.assert_series_equal(res4, exp4)
-
- res4n = s1.value_counts(bins=4, normalize=True)
- exp4n = Series([0.5, 0.25, 0.25, 0], index=intervals.take([0, 3, 1, 2]))
- tm.assert_series_equal(res4n, exp4n)
-
- # handle NA's properly
- s_values = ["a", "b", "b", "b", np.nan, np.nan, "d", "d", "a", "a", "b"]
- s = klass(s_values)
- expected = Series([4, 3, 2], index=["b", "a", "d"])
- tm.assert_series_equal(s.value_counts(), expected)
-
- if isinstance(s, Index):
- exp = Index(["a", "b", np.nan, "d"])
- tm.assert_index_equal(s.unique(), exp)
- else:
- exp = np.array(["a", "b", np.nan, "d"], dtype=object)
- tm.assert_numpy_array_equal(s.unique(), exp)
- assert s.nunique() == 3
-
- s = klass({}) if klass is dict else klass({}, dtype=object)
- expected = Series([], dtype=np.int64)
- tm.assert_series_equal(s.value_counts(), expected, check_index_type=False)
- # returned dtype differs depending on original
- if isinstance(s, Index):
- tm.assert_index_equal(s.unique(), Index([]), exact=False)
- else:
- tm.assert_numpy_array_equal(s.unique(), np.array([]), check_dtype=False)
-
- assert s.nunique() == 0
-
- def test_value_counts_datetime64(self, index_or_series):
- klass = index_or_series
-
- # GH 3002, datetime64[ns]
- # don't test names though
- txt = "\n".join(
- [
- "xxyyzz20100101PIE",
- "xxyyzz20100101GUM",
- "xxyyzz20100101EGG",
- "xxyyww20090101EGG",
- "foofoo20080909PIE",
- "foofoo20080909GUM",
- ]
- )
- f = StringIO(txt)
- df = pd.read_fwf(
- f, widths=[6, 8, 3], names=["person_id", "dt", "food"], parse_dates=["dt"]
- )
-
- s = klass(df["dt"].copy())
- s.name = None
- idx = pd.to_datetime(
- ["2010-01-01 00:00:00", "2008-09-09 00:00:00", "2009-01-01 00:00:00"]
- )
- expected_s = Series([3, 2, 1], index=idx)
- tm.assert_series_equal(s.value_counts(), expected_s)
-
- expected = np_array_datetime64_compat(
- ["2010-01-01 00:00:00", "2009-01-01 00:00:00", "2008-09-09 00:00:00"],
- dtype="datetime64[ns]",
- )
- if isinstance(s, Index):
- tm.assert_index_equal(s.unique(), DatetimeIndex(expected))
- else:
- tm.assert_numpy_array_equal(s.unique(), expected)
-
- assert s.nunique() == 3
-
- # with NaT
- s = df["dt"].copy()
- s = klass(list(s.values) + [pd.NaT])
-
- result = s.value_counts()
- assert result.index.dtype == "datetime64[ns]"
- tm.assert_series_equal(result, expected_s)
-
- result = s.value_counts(dropna=False)
- expected_s[pd.NaT] = 1
- tm.assert_series_equal(result, expected_s)
-
- unique = s.unique()
- assert unique.dtype == "datetime64[ns]"
-
- # numpy_array_equal cannot compare pd.NaT
- if isinstance(s, Index):
- exp_idx = DatetimeIndex(expected.tolist() + [pd.NaT])
- tm.assert_index_equal(unique, exp_idx)
- else:
- tm.assert_numpy_array_equal(unique[:3], expected)
- assert pd.isna(unique[3])
-
- assert s.nunique() == 3
- assert s.nunique(dropna=False) == 4
-
- # timedelta64[ns]
- td = df.dt - df.dt + timedelta(1)
- td = klass(td, name="dt")
-
- result = td.value_counts()
- expected_s = Series([6], index=[Timedelta("1day")], name="dt")
- tm.assert_series_equal(result, expected_s)
-
- expected = TimedeltaIndex(["1 days"], name="dt")
- if isinstance(td, Index):
- tm.assert_index_equal(td.unique(), expected)
- else:
- tm.assert_numpy_array_equal(td.unique(), expected.values)
-
- td2 = timedelta(1) + (df.dt - df.dt)
- td2 = klass(td2, name="dt")
- result2 = td2.value_counts()
- tm.assert_series_equal(result2, expected_s)
-
- @pytest.mark.parametrize("sort", [True, False])
- def test_factorize(self, index_or_series_obj, sort):
- obj = index_or_series_obj
- result_codes, result_uniques = obj.factorize(sort=sort)
-
- constructor = pd.Index
- if isinstance(obj, pd.MultiIndex):
- constructor = pd.MultiIndex.from_tuples
- expected_uniques = constructor(obj.unique())
-
- if sort:
- expected_uniques = expected_uniques.sort_values()
-
- # construct an integer ndarray so that
- # `expected_uniques.take(expected_codes)` is equal to `obj`
- expected_uniques_list = list(expected_uniques)
- expected_codes = [expected_uniques_list.index(val) for val in obj]
- expected_codes = np.asarray(expected_codes, dtype=np.intp)
-
- tm.assert_numpy_array_equal(result_codes, expected_codes)
- tm.assert_index_equal(result_uniques, expected_uniques)
-
- def test_drop_duplicates_series_vs_dataframe(self):
- # GH 14192
- df = pd.DataFrame(
- {
- "a": [1, 1, 1, "one", "one"],
- "b": [2, 2, np.nan, np.nan, np.nan],
- "c": [3, 3, np.nan, np.nan, "three"],
- "d": [1, 2, 3, 4, 4],
- "e": [
- datetime(2015, 1, 1),
- datetime(2015, 1, 1),
- datetime(2015, 2, 1),
- pd.NaT,
- pd.NaT,
- ],
- }
- )
- for column in df.columns:
- for keep in ["first", "last", False]:
- dropped_frame = df[[column]].drop_duplicates(keep=keep)
- dropped_series = df[column].drop_duplicates(keep=keep)
- tm.assert_frame_equal(dropped_frame, dropped_series.to_frame())
-
- def test_fillna(self, index_or_series_obj):
- # # GH 11343
- # though Index.fillna and Series.fillna has separate impl,
- # test here to confirm these works as the same
-
- obj = index_or_series_obj
- if isinstance(obj, ABCMultiIndex):
- pytest.skip("MultiIndex doesn't support isna")
-
- # values will not be changed
- fill_value = obj.values[0] if len(obj) > 0 else 0
- result = obj.fillna(fill_value)
- if isinstance(obj, Index):
- tm.assert_index_equal(obj, result)
- else:
- tm.assert_series_equal(obj, result)
-
- # check shallow_copied
- assert obj is not result
-
- @pytest.mark.parametrize("null_obj", [np.nan, None])
- def test_fillna_null(self, null_obj, index_or_series_obj):
- # # GH 11343
- # though Index.fillna and Series.fillna has separate impl,
- # test here to confirm these works as the same
- obj = index_or_series_obj
- klass = type(obj)
-
- if not allow_na_ops(obj):
- pytest.skip(f"{klass} doesn't allow for NA operations")
- elif len(obj) < 1:
- pytest.skip("Test doesn't make sense on empty data")
- elif isinstance(obj, ABCMultiIndex):
- pytest.skip(f"MultiIndex can't hold '{null_obj}'")
-
- values = obj.values
- fill_value = values[0]
- expected = values.copy()
- if needs_i8_conversion(obj):
- values[0:2] = iNaT
- expected[0:2] = fill_value
- else:
- values[0:2] = null_obj
- expected[0:2] = fill_value
-
- expected = klass(expected)
- obj = klass(values)
-
- result = obj.fillna(fill_value)
- if isinstance(obj, Index):
- tm.assert_index_equal(result, expected)
- else:
- tm.assert_series_equal(result, expected)
-
- # check shallow_copied
- assert obj is not result
-
- @pytest.mark.skipif(PYPY, reason="not relevant for PyPy")
- def test_memory_usage(self, index_or_series_obj):
- obj = index_or_series_obj
- res = obj.memory_usage()
- res_deep = obj.memory_usage(deep=True)
-
- is_object = is_object_dtype(obj) or (
- isinstance(obj, Series) and is_object_dtype(obj.index)
- )
- is_categorical = is_categorical_dtype(obj) or (
- isinstance(obj, Series) and is_categorical_dtype(obj.index)
- )
-
- if len(obj) == 0:
- assert res_deep == res == 0
- elif is_object or is_categorical:
- # only deep will pick them up
- assert res_deep > res
- else:
- assert res == res_deep
-
- # sys.getsizeof will call the .memory_usage with
- # deep=True, and add on some GC overhead
- diff = res_deep - sys.getsizeof(obj)
- assert abs(diff) < 100
-
- def test_memory_usage_components_series(self, series_with_simple_index):
- series = series_with_simple_index
- total_usage = series.memory_usage(index=True)
- non_index_usage = series.memory_usage(index=False)
- index_usage = series.index.memory_usage()
- assert total_usage == non_index_usage + index_usage
-
- def test_memory_usage_components_narrow_series(self, narrow_series):
- series = narrow_series
- total_usage = series.memory_usage(index=True)
- non_index_usage = series.memory_usage(index=False)
- index_usage = series.index.memory_usage()
- assert total_usage == non_index_usage + index_usage
-
- def test_searchsorted(self, index_or_series_obj):
- # numpy.searchsorted calls obj.searchsorted under the hood.
- # See gh-12238
- obj = index_or_series_obj
-
- if isinstance(obj, pd.MultiIndex):
- # See gh-14833
- pytest.skip("np.searchsorted doesn't work on pd.MultiIndex")
-
- max_obj = max(obj, default=0)
- index = np.searchsorted(obj, max_obj)
- assert 0 <= index <= len(obj)
-
- index = np.searchsorted(obj, max_obj, sorter=range(len(obj)))
- assert 0 <= index <= len(obj)
-
- def test_access_by_position(self, indices):
- index = indices
-
- if len(index) == 0:
- pytest.skip("Test doesn't make sense on empty data")
- elif isinstance(index, pd.MultiIndex):
- pytest.skip("Can't instantiate Series from MultiIndex")
-
- series = pd.Series(index)
- assert index[0] == series.iloc[0]
- assert index[5] == series.iloc[5]
- assert index[-1] == series.iloc[-1]
-
- size = len(index)
- assert index[-1] == index[size - 1]
-
- msg = f"index {size} is out of bounds for axis 0 with size {size}"
- with pytest.raises(IndexError, match=msg):
- index[size]
- msg = "single positional indexer is out-of-bounds"
- with pytest.raises(IndexError, match=msg):
- series.iloc[size]
-
- def test_get_indexer_non_unique_dtype_mismatch(self):
- # GH 25459
- indexes, missing = pd.Index(["A", "B"]).get_indexer_non_unique(pd.Index([0]))
- tm.assert_numpy_array_equal(np.array([-1], dtype=np.intp), indexes)
- tm.assert_numpy_array_equal(np.array([0], dtype=np.int64), missing)
diff --git a/pandas/tests/base/test_transpose.py b/pandas/tests/base/test_transpose.py
new file mode 100644
index 0000000000000..5ba278368834c
--- /dev/null
+++ b/pandas/tests/base/test_transpose.py
@@ -0,0 +1,27 @@
+import numpy as np
+import pytest
+
+import pandas._testing as tm
+
+
+def test_transpose(index_or_series_obj):
+ obj = index_or_series_obj
+ tm.assert_equal(obj.transpose(), obj)
+
+
+def test_transpose_non_default_axes(index_or_series_obj):
+ msg = "the 'axes' parameter is not supported"
+ obj = index_or_series_obj
+ with pytest.raises(ValueError, match=msg):
+ obj.transpose(1)
+ with pytest.raises(ValueError, match=msg):
+ obj.transpose(axes=1)
+
+
+def test_numpy_transpose(index_or_series_obj):
+ msg = "the 'axes' parameter is not supported"
+ obj = index_or_series_obj
+ tm.assert_equal(np.transpose(obj), obj)
+
+ with pytest.raises(ValueError, match=msg):
+ np.transpose(obj, axes=1)
diff --git a/pandas/tests/base/test_unique.py b/pandas/tests/base/test_unique.py
new file mode 100644
index 0000000000000..c6225c9b5ca64
--- /dev/null
+++ b/pandas/tests/base/test_unique.py
@@ -0,0 +1,107 @@
+import numpy as np
+import pytest
+
+from pandas._libs.tslib import iNaT
+
+from pandas.core.dtypes.common import is_datetime64tz_dtype, needs_i8_conversion
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.tests.base.common import allow_na_ops
+
+
+def test_unique(index_or_series_obj):
+ obj = index_or_series_obj
+ obj = np.repeat(obj, range(1, len(obj) + 1))
+ result = obj.unique()
+
+ # dict.fromkeys preserves the order
+ unique_values = list(dict.fromkeys(obj.values))
+ if isinstance(obj, pd.MultiIndex):
+ expected = pd.MultiIndex.from_tuples(unique_values)
+ expected.names = obj.names
+ tm.assert_index_equal(result, expected)
+ elif isinstance(obj, pd.Index):
+ expected = pd.Index(unique_values, dtype=obj.dtype)
+ if is_datetime64tz_dtype(obj):
+ expected = expected.normalize()
+ tm.assert_index_equal(result, expected)
+ else:
+ expected = np.array(unique_values)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("null_obj", [np.nan, None])
+def test_unique_null(null_obj, index_or_series_obj):
+ obj = index_or_series_obj
+
+ if not allow_na_ops(obj):
+ pytest.skip("type doesn't allow for NA operations")
+ elif len(obj) < 1:
+ pytest.skip("Test doesn't make sense on empty data")
+ elif isinstance(obj, pd.MultiIndex):
+ pytest.skip(f"MultiIndex can't hold '{null_obj}'")
+
+ values = obj.values
+ if needs_i8_conversion(obj):
+ values[0:2] = iNaT
+ else:
+ values[0:2] = null_obj
+
+ klass = type(obj)
+ repeated_values = np.repeat(values, range(1, len(values) + 1))
+ obj = klass(repeated_values, dtype=obj.dtype)
+ result = obj.unique()
+
+ unique_values_raw = dict.fromkeys(obj.values)
+ # because np.nan == np.nan is False, but None == None is True
+ # np.nan would be duplicated, whereas None wouldn't
+ unique_values_not_null = [val for val in unique_values_raw if not pd.isnull(val)]
+ unique_values = [null_obj] + unique_values_not_null
+
+ if isinstance(obj, pd.Index):
+ expected = pd.Index(unique_values, dtype=obj.dtype)
+ if is_datetime64tz_dtype(obj):
+ result = result.normalize()
+ expected = expected.normalize()
+ elif isinstance(obj, pd.CategoricalIndex):
+ expected = expected.set_categories(unique_values_not_null)
+ tm.assert_index_equal(result, expected)
+ else:
+ expected = np.array(unique_values, dtype=obj.dtype)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_nunique(index_or_series_obj):
+ obj = index_or_series_obj
+ obj = np.repeat(obj, range(1, len(obj) + 1))
+ expected = len(obj.unique())
+ assert obj.nunique(dropna=False) == expected
+
+
+@pytest.mark.parametrize("null_obj", [np.nan, None])
+def test_nunique_null(null_obj, index_or_series_obj):
+ obj = index_or_series_obj
+
+ if not allow_na_ops(obj):
+ pytest.skip("type doesn't allow for NA operations")
+ elif isinstance(obj, pd.MultiIndex):
+ pytest.skip(f"MultiIndex can't hold '{null_obj}'")
+
+ values = obj.values
+ if needs_i8_conversion(obj):
+ values[0:2] = iNaT
+ else:
+ values[0:2] = null_obj
+
+ klass = type(obj)
+ repeated_values = np.repeat(values, range(1, len(values) + 1))
+ obj = klass(repeated_values, dtype=obj.dtype)
+
+ if isinstance(obj, pd.CategoricalIndex):
+ assert obj.nunique() == len(obj.categories)
+ assert obj.nunique(dropna=False) == len(obj.categories) + 1
+ else:
+ num_unique_values = len(obj.unique())
+ assert obj.nunique() == max(0, num_unique_values - 1)
+ assert obj.nunique(dropna=False) == max(0, num_unique_values)
diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py
new file mode 100644
index 0000000000000..d45feaff68dde
--- /dev/null
+++ b/pandas/tests/base/test_value_counts.py
@@ -0,0 +1,276 @@
+import collections
+from datetime import timedelta
+from io import StringIO
+
+import numpy as np
+import pytest
+
+from pandas._libs.tslib import iNaT
+from pandas.compat.numpy import np_array_datetime64_compat
+
+from pandas.core.dtypes.common import needs_i8_conversion
+
+import pandas as pd
+from pandas import (
+ DatetimeIndex,
+ Index,
+ Interval,
+ IntervalIndex,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+)
+import pandas._testing as tm
+from pandas.tests.base.common import allow_na_ops
+
+
+def test_value_counts(index_or_series_obj):
+ obj = index_or_series_obj
+ obj = np.repeat(obj, range(1, len(obj) + 1))
+ result = obj.value_counts()
+
+ counter = collections.Counter(obj)
+ expected = pd.Series(dict(counter.most_common()), dtype=np.int64, name=obj.name)
+ expected.index = expected.index.astype(obj.dtype)
+ if isinstance(obj, pd.MultiIndex):
+ expected.index = pd.Index(expected.index)
+
+ # TODO: Order of entries with the same count is inconsistent on CI (gh-32449)
+ if obj.duplicated().any():
+ result = result.sort_index()
+ expected = expected.sort_index()
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("null_obj", [np.nan, None])
+def test_value_counts_null(null_obj, index_or_series_obj):
+ orig = index_or_series_obj
+ obj = orig.copy()
+
+ if not allow_na_ops(obj):
+ pytest.skip("type doesn't allow for NA operations")
+ elif len(obj) < 1:
+ pytest.skip("Test doesn't make sense on empty data")
+ elif isinstance(orig, pd.MultiIndex):
+ pytest.skip(f"MultiIndex can't hold '{null_obj}'")
+
+ values = obj.values
+ if needs_i8_conversion(obj):
+ values[0:2] = iNaT
+ else:
+ values[0:2] = null_obj
+
+ klass = type(obj)
+ repeated_values = np.repeat(values, range(1, len(values) + 1))
+ obj = klass(repeated_values, dtype=obj.dtype)
+
+ # because np.nan == np.nan is False, but None == None is True
+ # np.nan would be duplicated, whereas None wouldn't
+ counter = collections.Counter(obj.dropna())
+ expected = pd.Series(dict(counter.most_common()), dtype=np.int64)
+ expected.index = expected.index.astype(obj.dtype)
+
+ result = obj.value_counts()
+ if obj.duplicated().any():
+ # TODO:
+ # Order of entries with the same count is inconsistent on CI (gh-32449)
+ expected = expected.sort_index()
+ result = result.sort_index()
+ tm.assert_series_equal(result, expected)
+
+ # can't use expected[null_obj] = 3 as
+ # IntervalIndex doesn't allow assignment
+ new_entry = pd.Series({np.nan: 3}, dtype=np.int64)
+ expected = expected.append(new_entry)
+
+ result = obj.value_counts(dropna=False)
+ if obj.duplicated().any():
+ # TODO:
+ # Order of entries with the same count is inconsistent on CI (gh-32449)
+ expected = expected.sort_index()
+ result = result.sort_index()
+ tm.assert_series_equal(result, expected)
+
+
+def test_value_counts_inferred(index_or_series):
+ klass = index_or_series
+ s_values = ["a", "b", "b", "b", "b", "c", "d", "d", "a", "a"]
+ s = klass(s_values)
+ expected = Series([4, 3, 2, 1], index=["b", "a", "d", "c"])
+ tm.assert_series_equal(s.value_counts(), expected)
+
+ if isinstance(s, Index):
+ exp = Index(np.unique(np.array(s_values, dtype=np.object_)))
+ tm.assert_index_equal(s.unique(), exp)
+ else:
+ exp = np.unique(np.array(s_values, dtype=np.object_))
+ tm.assert_numpy_array_equal(s.unique(), exp)
+
+ assert s.nunique() == 4
+ # don't sort, have to sort after the fact as not sorting is
+ # platform-dep
+ hist = s.value_counts(sort=False).sort_values()
+ expected = Series([3, 1, 4, 2], index=list("acbd")).sort_values()
+ tm.assert_series_equal(hist, expected)
+
+ # sort ascending
+ hist = s.value_counts(ascending=True)
+ expected = Series([1, 2, 3, 4], index=list("cdab"))
+ tm.assert_series_equal(hist, expected)
+
+ # relative histogram.
+ hist = s.value_counts(normalize=True)
+ expected = Series([0.4, 0.3, 0.2, 0.1], index=["b", "a", "d", "c"])
+ tm.assert_series_equal(hist, expected)
+
+
+def test_value_counts_bins(index_or_series):
+ klass = index_or_series
+ s_values = ["a", "b", "b", "b", "b", "c", "d", "d", "a", "a"]
+ s = klass(s_values)
+
+ # bins
+ msg = "bins argument only works with numeric data"
+ with pytest.raises(TypeError, match=msg):
+ s.value_counts(bins=1)
+
+ s1 = Series([1, 1, 2, 3])
+ res1 = s1.value_counts(bins=1)
+ exp1 = Series({Interval(0.997, 3.0): 4})
+ tm.assert_series_equal(res1, exp1)
+ res1n = s1.value_counts(bins=1, normalize=True)
+ exp1n = Series({Interval(0.997, 3.0): 1.0})
+ tm.assert_series_equal(res1n, exp1n)
+
+ if isinstance(s1, Index):
+ tm.assert_index_equal(s1.unique(), Index([1, 2, 3]))
+ else:
+ exp = np.array([1, 2, 3], dtype=np.int64)
+ tm.assert_numpy_array_equal(s1.unique(), exp)
+
+ assert s1.nunique() == 3
+
+ # these return the same
+ res4 = s1.value_counts(bins=4, dropna=True)
+ intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0])
+ exp4 = Series([2, 1, 1, 0], index=intervals.take([0, 3, 1, 2]))
+ tm.assert_series_equal(res4, exp4)
+
+ res4 = s1.value_counts(bins=4, dropna=False)
+ intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0])
+ exp4 = Series([2, 1, 1, 0], index=intervals.take([0, 3, 1, 2]))
+ tm.assert_series_equal(res4, exp4)
+
+ res4n = s1.value_counts(bins=4, normalize=True)
+ exp4n = Series([0.5, 0.25, 0.25, 0], index=intervals.take([0, 3, 1, 2]))
+ tm.assert_series_equal(res4n, exp4n)
+
+ # handle NA's properly
+ s_values = ["a", "b", "b", "b", np.nan, np.nan, "d", "d", "a", "a", "b"]
+ s = klass(s_values)
+ expected = Series([4, 3, 2], index=["b", "a", "d"])
+ tm.assert_series_equal(s.value_counts(), expected)
+
+ if isinstance(s, Index):
+ exp = Index(["a", "b", np.nan, "d"])
+ tm.assert_index_equal(s.unique(), exp)
+ else:
+ exp = np.array(["a", "b", np.nan, "d"], dtype=object)
+ tm.assert_numpy_array_equal(s.unique(), exp)
+ assert s.nunique() == 3
+
+ s = klass({}) if klass is dict else klass({}, dtype=object)
+ expected = Series([], dtype=np.int64)
+ tm.assert_series_equal(s.value_counts(), expected, check_index_type=False)
+ # returned dtype differs depending on original
+ if isinstance(s, Index):
+ tm.assert_index_equal(s.unique(), Index([]), exact=False)
+ else:
+ tm.assert_numpy_array_equal(s.unique(), np.array([]), check_dtype=False)
+
+ assert s.nunique() == 0
+
+
+def test_value_counts_datetime64(index_or_series):
+ klass = index_or_series
+
+ # GH 3002, datetime64[ns]
+ # don't test names though
+ txt = "\n".join(
+ [
+ "xxyyzz20100101PIE",
+ "xxyyzz20100101GUM",
+ "xxyyzz20100101EGG",
+ "xxyyww20090101EGG",
+ "foofoo20080909PIE",
+ "foofoo20080909GUM",
+ ]
+ )
+ f = StringIO(txt)
+ df = pd.read_fwf(
+ f, widths=[6, 8, 3], names=["person_id", "dt", "food"], parse_dates=["dt"]
+ )
+
+ s = klass(df["dt"].copy())
+ s.name = None
+ idx = pd.to_datetime(
+ ["2010-01-01 00:00:00", "2008-09-09 00:00:00", "2009-01-01 00:00:00"]
+ )
+ expected_s = Series([3, 2, 1], index=idx)
+ tm.assert_series_equal(s.value_counts(), expected_s)
+
+ expected = np_array_datetime64_compat(
+ ["2010-01-01 00:00:00", "2009-01-01 00:00:00", "2008-09-09 00:00:00"],
+ dtype="datetime64[ns]",
+ )
+ if isinstance(s, Index):
+ tm.assert_index_equal(s.unique(), DatetimeIndex(expected))
+ else:
+ tm.assert_numpy_array_equal(s.unique(), expected)
+
+ assert s.nunique() == 3
+
+ # with NaT
+ s = df["dt"].copy()
+ s = klass(list(s.values) + [pd.NaT])
+
+ result = s.value_counts()
+ assert result.index.dtype == "datetime64[ns]"
+ tm.assert_series_equal(result, expected_s)
+
+ result = s.value_counts(dropna=False)
+ expected_s[pd.NaT] = 1
+ tm.assert_series_equal(result, expected_s)
+
+ unique = s.unique()
+ assert unique.dtype == "datetime64[ns]"
+
+ # numpy_array_equal cannot compare pd.NaT
+ if isinstance(s, Index):
+ exp_idx = DatetimeIndex(expected.tolist() + [pd.NaT])
+ tm.assert_index_equal(unique, exp_idx)
+ else:
+ tm.assert_numpy_array_equal(unique[:3], expected)
+ assert pd.isna(unique[3])
+
+ assert s.nunique() == 3
+ assert s.nunique(dropna=False) == 4
+
+ # timedelta64[ns]
+ td = df.dt - df.dt + timedelta(1)
+ td = klass(td, name="dt")
+
+ result = td.value_counts()
+ expected_s = Series([6], index=[Timedelta("1day")], name="dt")
+ tm.assert_series_equal(result, expected_s)
+
+ expected = TimedeltaIndex(["1 days"], name="dt")
+ if isinstance(td, Index):
+ tm.assert_index_equal(td.unique(), expected)
+ else:
+ tm.assert_numpy_array_equal(td.unique(), expected.values)
+
+ td2 = timedelta(1) + (df.dt - df.dt)
+ td2 = klass(td2, name="dt")
+ result2 = td2.value_counts()
+ tm.assert_series_equal(result2, expected_s)
| As suggested by @jreback in [this PR comment](https://github.com/pandas-dev/pandas/pull/32725#issuecomment-599299873)
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/32744 | 2020-03-16T08:47:01Z | 2020-03-17T11:52:36Z | 2020-03-17T11:52:36Z | 2020-03-17T11:52:44Z |
Fix typo (add missing comma in list) | diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 8e38332e67439..7414165ab5711 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -565,7 +565,7 @@ def to_datetime(
Parameters
----------
- arg : int, float, str, datetime, list, tuple, 1-d array, Series DataFrame/dict-like
+ arg : int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like
The object to convert to a datetime.
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
- If 'raise', then invalid parsing will raise an exception.
| - [ ] 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/32743 | 2020-03-16T06:40:20Z | 2020-03-16T17:28:23Z | 2020-03-16T17:28:23Z | 2020-03-16T18:13:50Z |
BUG: read_csv: fix wrong exception on permissions issue | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 0d3a9a8f969a4..399e275bb371a 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -346,6 +346,7 @@ I/O
- Bug in :meth:`read_excel` where a UTF-8 string with a high surrogate would cause a segmentation violation (:issue:`23809`)
- Bug in :meth:`read_csv` was causing a file descriptor leak on an empty file (:issue:`31488`)
- Bug in :meth:`read_csv` was causing a segfault when there were blank lines between the header and data rows (:issue:`28071`)
+- Bug in :meth:`read_csv` was raising a misleading exception on a permissions issue (:issue:`23784`)
Plotting
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index 4f7d75e0aaad6..39195585ebfa6 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -241,9 +241,9 @@ cdef extern from "parser/io.h":
void* buffer_mmap_bytes(void *source, size_t nbytes,
size_t *bytes_read, int *status)
- void *new_file_source(char *fname, size_t buffer_size)
+ void *new_file_source(char *fname, size_t buffer_size) except NULL
- void *new_rd_source(object obj)
+ void *new_rd_source(object obj) except NULL
int del_file_source(void *src)
int del_rd_source(void *src)
@@ -667,26 +667,12 @@ cdef class TextReader:
ptr = new_file_source(source, self.parser.chunksize)
self.parser.cb_io = &buffer_file_bytes
self.parser.cb_cleanup = &del_file_source
-
- if ptr == NULL:
- if not os.path.exists(source):
-
- raise FileNotFoundError(
- ENOENT,
- f'File {usource} does not exist',
- usource)
- raise IOError('Initializing from file failed')
-
self.parser.source = ptr
elif hasattr(source, 'read'):
# e.g., StringIO
ptr = new_rd_source(source)
- if ptr == NULL:
- raise IOError('Initializing parser from file-like '
- 'object failed')
-
self.parser.source = ptr
self.parser.cb_io = &buffer_rd_bytes
self.parser.cb_cleanup = &del_rd_source
diff --git a/pandas/_libs/src/parser/io.c b/pandas/_libs/src/parser/io.c
index 1e3295fcb6fc7..51504527de5a2 100644
--- a/pandas/_libs/src/parser/io.c
+++ b/pandas/_libs/src/parser/io.c
@@ -28,6 +28,7 @@ The full license is in the LICENSE file, distributed with this software.
void *new_file_source(char *fname, size_t buffer_size) {
file_source *fs = (file_source *)malloc(sizeof(file_source));
if (fs == NULL) {
+ PyErr_NoMemory();
return NULL;
}
@@ -41,17 +42,20 @@ void *new_file_source(char *fname, size_t buffer_size) {
int required = MultiByteToWideChar(CP_UTF8, 0, fname, -1, NULL, 0);
if (required == 0) {
free(fs);
+ PyErr_SetFromWindowsErr(0);
return NULL;
}
wname = (wchar_t*)malloc(required * sizeof(wchar_t));
if (wname == NULL) {
free(fs);
+ PyErr_NoMemory();
return NULL;
}
if (MultiByteToWideChar(CP_UTF8, 0, fname, -1, wname, required) <
required) {
free(wname);
free(fs);
+ PyErr_SetFromWindowsErr(0);
return NULL;
}
fs->fd = _wopen(wname, O_RDONLY | O_BINARY);
@@ -62,6 +66,7 @@ void *new_file_source(char *fname, size_t buffer_size) {
#endif
if (fs->fd == -1) {
free(fs);
+ PyErr_SetFromErrnoWithFilename(PyExc_OSError, fname);
return NULL;
}
@@ -71,6 +76,7 @@ void *new_file_source(char *fname, size_t buffer_size) {
if (fs->buffer == NULL) {
close(fs->fd);
free(fs);
+ PyErr_NoMemory();
return NULL;
}
@@ -83,6 +89,10 @@ void *new_file_source(char *fname, size_t buffer_size) {
void *new_rd_source(PyObject *obj) {
rd_source *rds = (rd_source *)malloc(sizeof(rd_source));
+ if (rds == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
/* hold on to this object */
Py_INCREF(obj);
rds->obj = obj;
@@ -220,20 +230,15 @@ void *new_mmap(char *fname) {
mm = (memory_map *)malloc(sizeof(memory_map));
if (mm == NULL) {
- fprintf(stderr, "new_file_buffer: malloc() failed.\n");
- return (NULL);
+ return NULL;
}
mm->fd = open(fname, O_RDONLY | O_BINARY);
if (mm->fd == -1) {
- fprintf(stderr, "new_file_buffer: open(%s) failed. errno =%d\n",
- fname, errno);
free(mm);
return NULL;
}
if (fstat(mm->fd, &stat) == -1) {
- fprintf(stderr, "new_file_buffer: fstat() failed. errno =%d\n",
- errno);
close(mm->fd);
free(mm);
return NULL;
@@ -242,8 +247,6 @@ void *new_mmap(char *fname) {
mm->memmap = mmap(NULL, filesize, PROT_READ, MAP_SHARED, mm->fd, 0);
if (mm->memmap == MAP_FAILED) {
- /* XXX Eventually remove this print statement. */
- fprintf(stderr, "new_file_buffer: mmap() failed.\n");
close(mm->fd);
free(mm);
return NULL;
diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py
index 0f3a5be76ae60..9de2ec9799353 100644
--- a/pandas/tests/io/parser/test_common.py
+++ b/pandas/tests/io/parser/test_common.py
@@ -960,13 +960,23 @@ def test_nonexistent_path(all_parsers):
parser = all_parsers
path = f"{tm.rands(10)}.csv"
- msg = f"File {path} does not exist" if parser.engine == "c" else r"\[Errno 2\]"
+ msg = r"\[Errno 2\]"
with pytest.raises(FileNotFoundError, match=msg) as e:
parser.read_csv(path)
+ assert path == e.value.filename
- filename = e.value.filename
- assert path == filename
+@td.skip_if_windows # os.chmod does not work in windows
+def test_no_permission(all_parsers):
+ # GH 23784
+ parser = all_parsers
+
+ msg = r"\[Errno 13\]"
+ with tm.ensure_clean() as path:
+ os.chmod(path, 0) # make file unreadable
+ with pytest.raises(PermissionError, match=msg) as e:
+ parser.read_csv(path)
+ assert path == e.value.filename
def test_missing_trailing_delimiters(all_parsers):
| Get rid of all error printf's and produce proper Python exceptions
- [x] closes #23784
- [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/32737 | 2020-03-15T22:22:11Z | 2020-03-19T01:40:41Z | 2020-03-19T01:40:40Z | 2020-03-19T19:07:07Z |
REF: misplaced repr tests | diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py
index c5d4d59adbc35..48cf37a9abc8b 100644
--- a/pandas/tests/frame/test_repr_info.py
+++ b/pandas/tests/frame/test_repr_info.py
@@ -212,3 +212,8 @@ def test_repr_np_nat_with_object(self, arg, box, expected):
# GH 25445
result = repr(box([arg("NaT")], dtype=object))
assert result == expected
+
+ def test_frame_datetime64_pre1900_repr(self):
+ df = DataFrame({"year": date_range("1/1/1700", periods=50, freq="A-DEC")})
+ # it works!
+ repr(df)
diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py
index d8eeed69d66e2..452af895e4967 100644
--- a/pandas/tests/frame/test_timeseries.py
+++ b/pandas/tests/frame/test_timeseries.py
@@ -20,11 +20,6 @@ def test_frame_append_datetime64_column(self):
df["A"] = rng
assert np.issubdtype(df["A"].dtype, np.dtype("M8[ns]"))
- def test_frame_datetime64_pre1900_repr(self):
- df = DataFrame({"year": date_range("1/1/1700", periods=50, freq="A-DEC")})
- # it works!
- repr(df)
-
def test_frame_append_datetime64_col_other_units(self):
n = 100
diff --git a/pandas/tests/series/indexing/test_alter_index.py b/pandas/tests/series/indexing/test_alter_index.py
index 05bd967903e9d..a3c431696b689 100644
--- a/pandas/tests/series/indexing/test_alter_index.py
+++ b/pandas/tests/series/indexing/test_alter_index.py
@@ -523,9 +523,9 @@ def test_drop_unique_and_non_unique_index(
],
)
def test_drop_exception_raised(data, index, drop_labels, axis, error_type, error_desc):
-
+ ser = Series(data, index=index)
with pytest.raises(error_type, match=error_desc):
- Series(data, index=index).drop(drop_labels, axis=axis)
+ ser.drop(drop_labels, axis=axis)
def test_drop_with_ignore_errors():
@@ -565,6 +565,7 @@ def test_drop_empty_list(index, drop_labels):
)
def test_drop_non_empty_list(data, index, drop_labels):
# GH 21494 and GH 16877
+ dtype = object if data is None else None
+ ser = pd.Series(data=data, index=index, dtype=dtype)
with pytest.raises(KeyError, match="not found in axis"):
- dtype = object if data is None else None
- pd.Series(data=data, index=index, dtype=dtype).drop(drop_labels)
+ ser.drop(drop_labels)
diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py
index 64a8c4569406e..77f942a9e32ec 100644
--- a/pandas/tests/series/test_repr.py
+++ b/pandas/tests/series/test_repr.py
@@ -218,6 +218,25 @@ def test_index_repr_in_frame_with_nan(self):
assert repr(s) == exp
+ def test_format_pre_1900_dates(self):
+ rng = date_range("1/1/1850", "1/1/1950", freq="A-DEC")
+ rng.format()
+ ts = Series(1, index=rng)
+ repr(ts)
+
+ def test_series_repr_nat(self):
+ series = Series([0, 1000, 2000, pd.NaT.value], dtype="M8[ns]")
+
+ result = repr(series)
+ expected = (
+ "0 1970-01-01 00:00:00.000000\n"
+ "1 1970-01-01 00:00:00.000001\n"
+ "2 1970-01-01 00:00:00.000002\n"
+ "3 NaT\n"
+ "dtype: datetime64[ns]"
+ )
+ assert result == expected
+
class TestCategoricalRepr:
def test_categorical_repr_unicode(self):
diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py
index 9796a32532b99..563cfa57c9214 100644
--- a/pandas/tests/series/test_timeseries.py
+++ b/pandas/tests/series/test_timeseries.py
@@ -2,8 +2,6 @@
import numpy as np
-from pandas._libs.tslib import iNaT
-
import pandas as pd
from pandas import DataFrame, DatetimeIndex, Series, date_range, timedelta_range
import pandas._testing as tm
@@ -88,19 +86,6 @@ def test_series_ctor_datetime64(self):
series = Series(dates)
assert np.issubdtype(series.dtype, np.dtype("M8[ns]"))
- def test_series_repr_nat(self):
- series = Series([0, 1000, 2000, iNaT], dtype="M8[ns]")
-
- result = repr(series)
- expected = (
- "0 1970-01-01 00:00:00.000000\n"
- "1 1970-01-01 00:00:00.000001\n"
- "2 1970-01-01 00:00:00.000002\n"
- "3 NaT\n"
- "dtype: datetime64[ns]"
- )
- assert result == expected
-
def test_promote_datetime_date(self):
rng = date_range("1/1/2000", periods=20)
ts = Series(np.random.randn(20), index=rng)
@@ -124,12 +109,6 @@ def test_promote_datetime_date(self):
expected = rng.get_indexer(ts_slice.index)
tm.assert_numpy_array_equal(result, expected)
- def test_format_pre_1900_dates(self):
- rng = date_range("1/1/1850", "1/1/1950", freq="A-DEC")
- rng.format()
- ts = Series(1, index=rng)
- repr(ts)
-
def test_groupby_count_dateparseerror(self):
dr = date_range(start="1/1/2012", freq="5min", periods=10)
| https://api.github.com/repos/pandas-dev/pandas/pulls/32736 | 2020-03-15T21:08:40Z | 2020-03-16T02:19:12Z | 2020-03-16T02:19:12Z | 2020-03-16T03:57:44Z | |
BUG: arithmetic with reindex pow | diff --git a/doc/source/whatsnew/v1.0.3.rst b/doc/source/whatsnew/v1.0.3.rst
index 482222fbddbb8..0ca5f5f548885 100644
--- a/doc/source/whatsnew/v1.0.3.rst
+++ b/doc/source/whatsnew/v1.0.3.rst
@@ -16,6 +16,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in ``resample.agg`` when the underlying data is non-writeable (:issue:`31710`)
+- Fixed regression in :class:`DataFrame` exponentiation with reindexing (:issue:`32685`)
.. _whatsnew_103.bug_fixes:
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py
index ed779c5da6d14..3153a9ac28c10 100644
--- a/pandas/core/ops/__init__.py
+++ b/pandas/core/ops/__init__.py
@@ -711,13 +711,17 @@ def to_series(right):
def _should_reindex_frame_op(
- left: "DataFrame", right, axis, default_axis: int, fill_value, level
+ left: "DataFrame", right, op, axis, default_axis: int, fill_value, level
) -> bool:
"""
Check if this is an operation between DataFrames that will need to reindex.
"""
assert isinstance(left, ABCDataFrame)
+ if op is operator.pow or op is rpow:
+ # GH#32685 pow has special semantics for operating with null values
+ return False
+
if not isinstance(right, ABCDataFrame):
return False
@@ -779,7 +783,9 @@ def _arith_method_FRAME(cls, op, special):
@Appender(doc)
def f(self, other, axis=default_axis, level=None, fill_value=None):
- if _should_reindex_frame_op(self, other, axis, default_axis, fill_value, level):
+ if _should_reindex_frame_op(
+ self, other, op, axis, default_axis, fill_value, level
+ ):
return _frame_arith_method_with_reindex(self, other, op)
self, other = _align_method_FRAME(self, other, axis, flex=True, level=level)
diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py
index 92d86c8b602ff..b39c58b9931ab 100644
--- a/pandas/tests/frame/test_arithmetic.py
+++ b/pandas/tests/frame/test_arithmetic.py
@@ -823,3 +823,27 @@ def test_align_frame(self):
half = ts[::2]
result = ts + half.take(np.random.permutation(len(half)))
tm.assert_frame_equal(result, expected)
+
+
+def test_pow_with_realignment():
+ # GH#32685 pow has special semantics for operating with null values
+ left = pd.DataFrame({"A": [0, 1, 2]})
+ right = pd.DataFrame(index=[0, 1, 2])
+
+ result = left ** right
+ expected = pd.DataFrame({"A": [np.nan, 1.0, np.nan]})
+ tm.assert_frame_equal(result, expected)
+
+
+# TODO: move to tests.arithmetic and parametrize
+def test_pow_nan_with_zero():
+ left = pd.DataFrame({"A": [np.nan, np.nan, np.nan]})
+ right = pd.DataFrame({"A": [0, 0, 0]})
+
+ expected = pd.DataFrame({"A": [1.0, 1.0, 1.0]})
+
+ result = left ** right
+ tm.assert_frame_equal(result, expected)
+
+ result = left["A"] ** right["A"]
+ tm.assert_series_equal(result, expected["A"])
| - [x] closes #32685
- [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/32734 | 2020-03-15T19:52:43Z | 2020-03-17T15:41:09Z | 2020-03-17T15:41:09Z | 2020-03-17T19:15:08Z |
FIX: series.fillna doesn't shallow copy if len(series) == 0 | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 21e59805fa143..fb45a9390e1d8 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -303,8 +303,8 @@ Indexing
Missing
^^^^^^^
--
--
+- Calling :meth:`fillna` on an empty Series now correctly returns a shallow copied object. The behaviour is now consistent with :class:`Index`, :class:`DataFrame` and a non-empty :class:`Series` (:issue:`32543`).
+
MultiIndex
^^^^^^^^^^
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 8d56311331d4d..88c2ea810b3b6 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6081,9 +6081,6 @@ def fillna(
downcast=downcast,
)
else:
- if len(self._get_axis(axis)) == 0:
- return self
-
if self.ndim == 1:
if isinstance(value, (dict, ABCSeries)):
value = create_series_with_explicit_dtype(
diff --git a/pandas/tests/base/test_ops.py b/pandas/tests/base/test_ops.py
index 5a78e5d6352a9..9f94a74fbb581 100644
--- a/pandas/tests/base/test_ops.py
+++ b/pandas/tests/base/test_ops.py
@@ -611,9 +611,6 @@ def test_fillna(self, index_or_series_obj):
tm.assert_series_equal(obj, result)
# check shallow_copied
- if isinstance(obj, Series) and len(obj) == 0:
- # TODO: GH-32543
- pytest.xfail("Shallow copy for empty Series is bugged")
assert obj is not result
@pytest.mark.parametrize("null_obj", [np.nan, None])
| - [x] closes #32543
- [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/32733 | 2020-03-15T19:09:12Z | 2020-03-16T22:34:14Z | 2020-03-16T22:34:13Z | 2020-03-16T22:41:33Z |
REF: simplify json get_values | diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c
index 1d17cce0bc3a9..e2deffb46c4e6 100644
--- a/pandas/_libs/src/ujson/python/objToJSON.c
+++ b/pandas/_libs/src/ujson/python/objToJSON.c
@@ -237,21 +237,6 @@ static PyObject *get_values(PyObject *obj) {
}
}
- if ((values == NULL) && PyObject_HasAttrString(obj, "get_block_values_for_json")) {
- PRINTMARK();
- values = PyObject_CallMethod(obj, "get_block_values_for_json", NULL);
-
- if (values == NULL) {
- // Clear so we can subsequently try another method
- PyErr_Clear();
- } else if (!PyArray_CheckExact(values)) {
- // Didn't get a numpy array, so keep trying
- PRINTMARK();
- Py_DECREF(values);
- values = NULL;
- }
- }
-
if (values == NULL) {
PyObject *typeRepr = PyObject_Repr((PyObject *)Py_TYPE(obj));
PyObject *repr;
@@ -780,7 +765,7 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) {
goto BLKRET;
}
- tmp = get_values(block);
+ tmp = PyObject_CallMethod(block, "get_block_values_for_json", NULL);
if (!tmp) {
((JSONObjectEncoder *)tc->encoder)->errorMsg = "";
Py_DECREF(block);
@@ -1266,7 +1251,7 @@ int DataFrame_iterNext(JSOBJ obj, JSONTypeContext *tc) {
} else if (index == 2) {
memcpy(GET_TC(tc)->cStr, "data", sizeof(char) * 5);
if (is_simple_frame(obj)) {
- GET_TC(tc)->itemValue = get_values(obj);
+ GET_TC(tc)->itemValue = PyObject_GetAttrString(obj, "values");
if (!GET_TC(tc)->itemValue) {
return 0;
}
@@ -1935,7 +1920,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) {
pc->iterNext = NpyArr_iterNext;
pc->iterGetName = NpyArr_iterGetName;
- pc->newObj = get_values(obj);
+ pc->newObj = PyObject_GetAttrString(obj, "values");
if (!pc->newObj) {
goto INVALID;
}
| cc @WillAyd trying to get away from _internal_get_values in the json code; this is zero-logic-changing to narrow the scope of what gets passed to _internal_get_values.
AFAICT replacing the _internal_get_values call with calling `__array__` doesnt break any tests, but in general the two are not always equivalent and it isnt obvious to me whether there are untested cases where it matters. | https://api.github.com/repos/pandas-dev/pandas/pulls/32731 | 2020-03-15T18:06:30Z | 2020-03-16T01:26:32Z | 2020-03-16T01:26:32Z | 2020-03-16T16:09:33Z |
TYP: annotate | diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 6aa303dd04703..9aeaa827fe8b0 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -21,7 +21,7 @@
from pandas.core.dtypes.common import is_array_like, is_list_like
from pandas.core.dtypes.dtypes import ExtensionDtype
-from pandas.core.dtypes.generic import ABCExtensionArray, ABCIndexClass, ABCSeries
+from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
from pandas.core.dtypes.missing import isna
from pandas.core import ops
@@ -590,7 +590,7 @@ def dropna(self):
"""
return self[~self.isna()]
- def shift(self, periods: int = 1, fill_value: object = None) -> ABCExtensionArray:
+ def shift(self, periods: int = 1, fill_value: object = None) -> "ExtensionArray":
"""
Shift values by desired number.
@@ -727,7 +727,7 @@ def _values_for_factorize(self) -> Tuple[np.ndarray, Any]:
"""
return self.astype(object), np.nan
- def factorize(self, na_sentinel: int = -1) -> Tuple[np.ndarray, ABCExtensionArray]:
+ def factorize(self, na_sentinel: int = -1) -> Tuple[np.ndarray, "ExtensionArray"]:
"""
Encode the extension array as an enumerated type.
@@ -832,7 +832,7 @@ def repeat(self, repeats, axis=None):
def take(
self, indices: Sequence[int], allow_fill: bool = False, fill_value: Any = None
- ) -> ABCExtensionArray:
+ ) -> "ExtensionArray":
"""
Take elements from an array.
@@ -921,7 +921,7 @@ def take(self, indices, allow_fill=False, fill_value=None):
# pandas.api.extensions.take
raise AbstractMethodError(self)
- def copy(self) -> ABCExtensionArray:
+ def copy(self) -> "ExtensionArray":
"""
Return a copy of the array.
@@ -931,7 +931,7 @@ def copy(self) -> ABCExtensionArray:
"""
raise AbstractMethodError(self)
- def view(self, dtype=None) -> Union[ABCExtensionArray, np.ndarray]:
+ def view(self, dtype=None) -> ArrayLike:
"""
Return a view on the array.
@@ -942,8 +942,8 @@ def view(self, dtype=None) -> Union[ABCExtensionArray, np.ndarray]:
Returns
-------
- ExtensionArray
- A view of the :class:`ExtensionArray`.
+ ExtensionArray or np.ndarray
+ A view on the :class:`ExtensionArray`'s data.
"""
# NB:
# - This must return a *new* object referencing the same data, not self.
@@ -1001,7 +1001,7 @@ def _formatter(self, boxed: bool = False) -> Callable[[Any], Optional[str]]:
# Reshaping
# ------------------------------------------------------------------------
- def ravel(self, order="C") -> ABCExtensionArray:
+ def ravel(self, order="C") -> "ExtensionArray":
"""
Return a flattened view on this array.
@@ -1022,8 +1022,8 @@ def ravel(self, order="C") -> ABCExtensionArray:
@classmethod
def _concat_same_type(
- cls, to_concat: Sequence[ABCExtensionArray]
- ) -> ABCExtensionArray:
+ cls, to_concat: Sequence["ExtensionArray"]
+ ) -> "ExtensionArray":
"""
Concatenate multiple array.
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 105d9581b1a25..5bcefcfbc2d19 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -130,7 +130,7 @@ class AttributesMixin:
_data: np.ndarray
@classmethod
- def _simple_new(cls, values, **kwargs):
+ def _simple_new(cls, values: np.ndarray, **kwargs):
raise AbstractMethodError(cls)
@property
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 5eeee644b3854..680b37c955278 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -31,13 +31,7 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import PeriodDtype
-from pandas.core.dtypes.generic import (
- ABCIndexClass,
- ABCPeriod,
- ABCPeriodArray,
- ABCPeriodIndex,
- ABCSeries,
-)
+from pandas.core.dtypes.generic import ABCIndexClass, ABCPeriodIndex, ABCSeries
from pandas.core.dtypes.missing import isna, notna
import pandas.core.algorithms as algos
@@ -48,7 +42,7 @@
from pandas.tseries.offsets import DateOffset, Tick, _delta_to_tick
-def _field_accessor(name, alias, docstring=None):
+def _field_accessor(name: str, alias: int, docstring=None):
def f(self):
base, mult = libfrequencies.get_freq_code(self.freq)
result = get_period_field_arr(alias, self.asi8, base)
@@ -170,7 +164,7 @@ def __init__(self, values, freq=None, dtype=None, copy=False):
self._dtype = PeriodDtype(freq)
@classmethod
- def _simple_new(cls, values: np.ndarray, freq=None, **kwargs):
+ def _simple_new(cls, values: np.ndarray, freq=None, **kwargs) -> "PeriodArray":
# alias for PeriodArray.__init__
assert isinstance(values, np.ndarray) and values.dtype == "i8"
return cls(values, freq=freq, **kwargs)
@@ -181,7 +175,7 @@ def _from_sequence(
scalars: Sequence[Optional[Period]],
dtype: Optional[PeriodDtype] = None,
copy: bool = False,
- ) -> ABCPeriodArray:
+ ) -> "PeriodArray":
if dtype:
freq = dtype.freq
else:
@@ -202,11 +196,13 @@ def _from_sequence(
return cls(ordinals, freq=freq)
@classmethod
- def _from_sequence_of_strings(cls, strings, dtype=None, copy=False):
+ def _from_sequence_of_strings(
+ cls, strings, dtype=None, copy=False
+ ) -> "PeriodArray":
return cls._from_sequence(strings, dtype, copy)
@classmethod
- def _from_datetime64(cls, data, freq, tz=None):
+ def _from_datetime64(cls, data, freq, tz=None) -> "PeriodArray":
"""
Construct a PeriodArray from a datetime64 array
@@ -270,12 +266,12 @@ def _check_compatible_with(self, other, setitem: bool = False):
# Data / Attributes
@cache_readonly
- def dtype(self):
+ def dtype(self) -> PeriodDtype:
return self._dtype
# error: Read-only property cannot override read-write property [misc]
@property # type: ignore
- def freq(self):
+ def freq(self) -> DateOffset:
"""
Return the frequency object for this PeriodArray.
"""
@@ -402,7 +398,7 @@ def __arrow_array__(self, type=None):
daysinmonth = days_in_month
@property
- def is_leap_year(self):
+ def is_leap_year(self) -> np.ndarray:
"""
Logical indicating if the date belongs to a leap year.
"""
@@ -458,12 +454,6 @@ def to_timestamp(self, freq=None, how="start"):
new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base)
return DatetimeArray._from_sequence(new_data, freq="infer")
- # --------------------------------------------------------------------
- # Array-like / EA-Interface Methods
-
- def _values_for_argsort(self):
- return self._data
-
# --------------------------------------------------------------------
def _time_shift(self, periods, freq=None):
@@ -495,7 +485,7 @@ def _time_shift(self, periods, freq=None):
def _box_func(self):
return lambda x: Period._from_ordinal(ordinal=x, freq=self.freq)
- def asfreq(self, freq=None, how="E"):
+ def asfreq(self, freq=None, how="E") -> "PeriodArray":
"""
Convert the Period Array/Index to the specified frequency `freq`.
@@ -557,7 +547,7 @@ def asfreq(self, freq=None, how="E"):
# ------------------------------------------------------------------
# Rendering Methods
- def _formatter(self, boxed=False):
+ def _formatter(self, boxed: bool = False):
if boxed:
return str
return "'{}'".format
@@ -584,7 +574,7 @@ def _format_native_types(self, na_rep="NaT", date_format=None, **kwargs):
# ------------------------------------------------------------------
- def astype(self, dtype, copy=True):
+ def astype(self, dtype, copy: bool = True):
# We handle Period[T] -> Period[U]
# Our parent handles everything else.
dtype = pandas_dtype(dtype)
@@ -965,8 +955,8 @@ def _get_ordinal_range(start, end, periods, freq, mult=1):
if end is not None:
end = Period(end, freq)
- is_start_per = isinstance(start, ABCPeriod)
- is_end_per = isinstance(end, ABCPeriod)
+ is_start_per = isinstance(start, Period)
+ is_end_per = isinstance(end, Period)
if is_start_per and is_end_per and start.freq != end.freq:
raise ValueError("start and end must have same freq")
diff --git a/pandas/core/ops/dispatch.py b/pandas/core/ops/dispatch.py
index 61a3032c7a02c..5c34cb20be266 100644
--- a/pandas/core/ops/dispatch.py
+++ b/pandas/core/ops/dispatch.py
@@ -1,10 +1,12 @@
"""
Functions for defining unary operations.
"""
-from typing import Any, Union
+from typing import Any
import numpy as np
+from pandas._typing import ArrayLike
+
from pandas.core.dtypes.common import (
is_datetime64_dtype,
is_extension_array_dtype,
@@ -13,7 +15,7 @@
is_scalar,
is_timedelta64_dtype,
)
-from pandas.core.dtypes.generic import ABCExtensionArray, ABCSeries
+from pandas.core.dtypes.generic import ABCSeries
from pandas.core.construction import array
@@ -93,9 +95,7 @@ def should_series_dispatch(left, right, op):
return False
-def dispatch_to_extension_op(
- op, left: Union[ABCExtensionArray, np.ndarray], right: Any,
-):
+def dispatch_to_extension_op(op, left: ArrayLike, right: Any):
"""
Assume that left or right is a Series backed by an ExtensionArray,
apply the operator defined by op.
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 7aeed5c316d7f..544d45999c14b 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2202,7 +2202,7 @@ def __eq__(self, other: Any) -> bool:
for a in ["name", "cname", "dtype", "pos"]
)
- def set_data(self, data: Union[np.ndarray, ABCExtensionArray]):
+ def set_data(self, data: ArrayLike):
assert data is not None
assert self.dtype is None
@@ -4959,11 +4959,11 @@ def _dtype_to_kind(dtype_str: str) -> str:
return kind
-def _get_data_and_dtype_name(data: Union[np.ndarray, ABCExtensionArray]):
+def _get_data_and_dtype_name(data: ArrayLike):
"""
Convert the passed data into a storable form and a dtype string.
"""
- if is_categorical_dtype(data.dtype):
+ if isinstance(data, Categorical):
data = data.codes
# For datetime64tz we need to drop the TZ in tests TODO: why?
| cc @simonjayhawkins had to revert some annotations because mypy couldn't tell that ArrayLike had "copy" or "view". Is a fix for that depending on numpy making annotations/stubs? | https://api.github.com/repos/pandas-dev/pandas/pulls/32730 | 2020-03-15T17:34:08Z | 2020-03-19T11:33:30Z | 2020-03-19T11:33:30Z | 2020-03-19T15:43:49Z |
DOC: Edit release notes | diff --git a/doc/source/whatsnew/v1.0.2.rst b/doc/source/whatsnew/v1.0.2.rst
index 97260ec5e9f0e..600b189ed3ec1 100644
--- a/doc/source/whatsnew/v1.0.2.rst
+++ b/doc/source/whatsnew/v1.0.2.rst
@@ -17,7 +17,7 @@ Fixed regressions
**Groupby**
-- Fixed regression in :meth:`groupby(..).agg() <pandas.core.groupby.GroupBy.agg>` which was failing on frames with MultiIndex columns and a custom function (:issue:`31777`)
+- Fixed regression in :meth:`groupby(..).agg() <pandas.core.groupby.GroupBy.agg>` which was failing on frames with :class:`MultiIndex` columns and a custom function (:issue:`31777`)
- Fixed regression in ``groupby(..).rolling(..).apply()`` (``RollingGroupby``) where the ``raw`` parameter was ignored (:issue:`31754`)
- Fixed regression in :meth:`rolling(..).corr() <pandas.core.window.rolling.Rolling.corr>` when using a time offset (:issue:`31789`)
- Fixed regression in :meth:`groupby(..).nunique() <pandas.core.groupby.DataFrameGroupBy.nunique>` which was modifying the original values if ``NaN`` values were present (:issue:`31950`)
@@ -33,7 +33,7 @@ Fixed regressions
**Reindexing/alignment**
-- Fixed regression in :meth:`Series.align` when ``other`` is a DataFrame and ``method`` is not None (:issue:`31785`)
+- Fixed regression in :meth:`Series.align` when ``other`` is a :class:`DataFrame` and ``method`` is not ``None`` (:issue:`31785`)
- Fixed regression in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with (tz-aware) index and ``method=nearest`` (:issue:`26683`)
- Fixed regression in :meth:`DataFrame.reindex_like` on a :class:`DataFrame` subclass raised an ``AssertionError`` (:issue:`31925`)
- Fixed regression in :class:`DataFrame` arithmetic operations with mis-matched columns (:issue:`31623`)
@@ -81,7 +81,7 @@ Bug fixes
**Datetimelike**
-- Bug in :meth:`Series.astype` not copying for tz-naive and tz-aware datetime64 dtype (:issue:`32490`)
+- Bug in :meth:`Series.astype` not copying for tz-naive and tz-aware ``datetime64`` dtype (:issue:`32490`)
- Bug where :func:`to_datetime` would raise when passed ``pd.NA`` (:issue:`32213`)
- Improved error message when subtracting two :class:`Timestamp` that result in an out-of-bounds :class:`Timedelta` (:issue:`31774`)
| Small cosmetic changes to rendering of release notes | https://api.github.com/repos/pandas-dev/pandas/pulls/32729 | 2020-03-15T17:15:04Z | 2020-03-16T01:27:33Z | 2020-03-16T01:27:33Z | 2020-03-16T15:40:50Z |
CLN: Use keep fixture in more places | diff --git a/pandas/tests/frame/methods/test_duplicated.py b/pandas/tests/frame/methods/test_duplicated.py
index 38b9d7fd049ab..34751b565a24b 100644
--- a/pandas/tests/frame/methods/test_duplicated.py
+++ b/pandas/tests/frame/methods/test_duplicated.py
@@ -64,7 +64,6 @@ def test_duplicated_nan_none(keep, expected):
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("keep", ["first", "last", False])
@pytest.mark.parametrize("subset", [None, ["A", "B"], "A"])
def test_duplicated_subset(subset, keep):
df = DataFrame(
diff --git a/pandas/tests/indexes/multi/test_duplicates.py b/pandas/tests/indexes/multi/test_duplicates.py
index 5e17a19335c7e..433b631ab9472 100644
--- a/pandas/tests/indexes/multi/test_duplicates.py
+++ b/pandas/tests/indexes/multi/test_duplicates.py
@@ -238,7 +238,6 @@ def test_duplicated(idx_dup, keep, expected):
tm.assert_numpy_array_equal(result, expected)
-@pytest.mark.parametrize("keep", ["first", "last", False])
def test_duplicated_large(keep):
# GH 9125
n, k = 200, 5000
| Follow up of #32487 - for [this comment of jreback](https://github.com/pandas-dev/pandas/pull/32487#issuecomment-599153289) in particular
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/32726 | 2020-03-15T11:08:15Z | 2020-03-16T01:36:54Z | 2020-03-16T01:36:53Z | 2020-03-16T01:36:59Z |
CLN: Remove Ops Mixin from pandas/tests/base | diff --git a/pandas/tests/base/test_ops.py b/pandas/tests/base/test_ops.py
index 5a78e5d6352a9..576206ebaacae 100644
--- a/pandas/tests/base/test_ops.py
+++ b/pandas/tests/base/test_ops.py
@@ -40,50 +40,6 @@ def allow_na_ops(obj: Any) -> bool:
return not is_bool_index and obj._can_hold_na
-class Ops:
- def setup_method(self, method):
- self.bool_index = tm.makeBoolIndex(10, name="a")
- self.int_index = tm.makeIntIndex(10, name="a")
- self.float_index = tm.makeFloatIndex(10, name="a")
- self.dt_index = tm.makeDateIndex(10, name="a")
- self.dt_tz_index = tm.makeDateIndex(10, name="a").tz_localize(tz="US/Eastern")
- self.period_index = tm.makePeriodIndex(10, name="a")
- self.string_index = tm.makeStringIndex(10, name="a")
- self.unicode_index = tm.makeUnicodeIndex(10, name="a")
-
- arr = np.random.randn(10)
- self.bool_series = Series(arr, index=self.bool_index, name="a")
- self.int_series = Series(arr, index=self.int_index, name="a")
- self.float_series = Series(arr, index=self.float_index, name="a")
- self.dt_series = Series(arr, index=self.dt_index, name="a")
- self.dt_tz_series = self.dt_tz_index.to_series()
- self.period_series = Series(arr, index=self.period_index, name="a")
- self.string_series = Series(arr, index=self.string_index, name="a")
- self.unicode_series = Series(arr, index=self.unicode_index, name="a")
-
- types = ["bool", "int", "float", "dt", "dt_tz", "period", "string", "unicode"]
- self.indexes = [getattr(self, f"{t}_index") for t in types]
- self.series = [getattr(self, f"{t}_series") for t in types]
-
- # To test narrow dtypes, we use narrower *data* elements, not *index* elements
- index = self.int_index
- self.float32_series = Series(arr.astype(np.float32), index=index, name="a")
-
- arr_int = np.random.choice(10, size=10, replace=False)
- self.int8_series = Series(arr_int.astype(np.int8), index=index, name="a")
- self.int16_series = Series(arr_int.astype(np.int16), index=index, name="a")
- self.int32_series = Series(arr_int.astype(np.int32), index=index, name="a")
-
- self.uint8_series = Series(arr_int.astype(np.uint8), index=index, name="a")
- self.uint16_series = Series(arr_int.astype(np.uint16), index=index, name="a")
- self.uint32_series = Series(arr_int.astype(np.uint32), index=index, name="a")
-
- nrw_types = ["float32", "int8", "int16", "int32", "uint8", "uint16", "uint32"]
- self.narrow_series = [getattr(self, f"{t}_series") for t in nrw_types]
-
- self.objs = self.indexes + self.series + self.narrow_series
-
-
@pytest.mark.parametrize(
"op_name, op",
[
@@ -132,12 +88,7 @@ def test_numpy_transpose(self, index_or_series_obj):
np.transpose(obj, axes=1)
-class TestIndexOps(Ops):
- def setup_method(self, method):
- super().setup_method(method)
- self.is_valid_objs = self.objs
- self.not_valid_objs = []
-
+class TestIndexOps:
def test_none_comparison(self, series_with_simple_index):
series = series_with_simple_index
if isinstance(series.index, IntervalIndex):
| 11 PRs later, the moment has finally come: closes #23877 🎉
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/32725 | 2020-03-15T11:03:39Z | 2020-03-16T01:37:45Z | 2020-03-16T01:37:44Z | 2020-03-16T01:38:06Z |
BUG: Fix HDFStore empty keys on native HDF5 file by adding keyword include | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 2a02041244362..169bf17aa5759 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -962,6 +962,7 @@ I/O
- Bug in :meth:`~DataFrame.to_excel` could not handle the column name `render` and was raising an ``KeyError`` (:issue:`34331`)
- Bug in :meth:`~SQLDatabase.execute` was raising a ``ProgrammingError`` for some DB-API drivers when the SQL statement contained the `%` character and no parameters were present (:issue:`34211`)
- Bug in :meth:`~pandas.io.stata.StataReader` which resulted in categorical variables with difference dtypes when reading data using an iterator. (:issue:`31544`)
+- :meth:`HDFStore.keys` has now an optional `include` parameter that allows the retrieval of all native HDF5 table names (:issue:`29916`)
Plotting
^^^^^^^^
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 497b25d73df3e..8aac8f9531512 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -580,16 +580,39 @@ def __enter__(self):
def __exit__(self, exc_type, exc_value, traceback):
self.close()
- def keys(self) -> List[str]:
+ def keys(self, include: str = "pandas") -> List[str]:
"""
Return a list of keys corresponding to objects stored in HDFStore.
+ Parameters
+ ----------
+
+ include : str, default 'pandas'
+ When kind equals 'pandas' return pandas objects
+ When kind equals 'native' return native HDF5 Table objects
+
+ .. versionadded:: 1.1.0
+
Returns
-------
list
List of ABSOLUTE path-names (e.g. have the leading '/').
+
+ Raises
+ ------
+ raises ValueError if kind has an illegal value
"""
- return [n._v_pathname for n in self.groups()]
+ if include == "pandas":
+ return [n._v_pathname for n in self.groups()]
+
+ elif include == "native":
+ assert self._handle is not None # mypy
+ return [
+ n._v_pathname for n in self._handle.walk_nodes("/", classname="Table")
+ ]
+ raise ValueError(
+ f"`include` should be either 'pandas' or 'native' but is '{include}'"
+ )
def __iter__(self):
return iter(self.keys())
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index fe59b989bab7e..30b64b1750aa9 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -341,6 +341,40 @@ def create_h5_and_return_checksum(track_times):
# checksums are NOT same if track_time = True
assert checksum_0_tt_true != checksum_1_tt_true
+ def test_non_pandas_keys(self, setup_path):
+ class Table1(tables.IsDescription):
+ value1 = tables.Float32Col()
+
+ class Table2(tables.IsDescription):
+ value2 = tables.Float32Col()
+
+ class Table3(tables.IsDescription):
+ value3 = tables.Float32Col()
+
+ with ensure_clean_path(setup_path) as path:
+ with tables.open_file(path, mode="w") as h5file:
+ group = h5file.create_group("/", "group")
+ h5file.create_table(group, "table1", Table1, "Table 1")
+ h5file.create_table(group, "table2", Table2, "Table 2")
+ h5file.create_table(group, "table3", Table3, "Table 3")
+ with HDFStore(path) as store:
+ assert len(store.keys(include="native")) == 3
+ expected = {"/group/table1", "/group/table2", "/group/table3"}
+ assert set(store.keys(include="native")) == expected
+ assert set(store.keys(include="pandas")) == set()
+ for name in expected:
+ df = store.get(name)
+ assert len(df.columns) == 1
+
+ def test_keys_illegal_include_keyword_value(self, setup_path):
+ with ensure_clean_store(setup_path) as store:
+ with pytest.raises(
+ ValueError,
+ match="`include` should be either 'pandas' or 'native' "
+ "but is 'illegal'",
+ ):
+ store.keys(include="illegal")
+
def test_keys_ignore_hdf_softlink(self, setup_path):
# GH 20523
| - [x] closes #29916
- [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/32723 | 2020-03-15T10:44:05Z | 2020-06-14T22:20:20Z | 2020-06-14T22:20:19Z | 2020-06-16T18:47:24Z |
TST: Fix HDFStore leak in tests/io/pytables/test_store.py | diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index 61ca2e7f5f19d..9a0788ea068ad 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -1217,14 +1217,14 @@ def test_read_missing_key_opened_store(self, setup_path):
df = pd.DataFrame({"a": range(2), "b": range(2)})
df.to_hdf(path, "k1")
- store = pd.HDFStore(path, "r")
+ with pd.HDFStore(path, "r") as store:
- with pytest.raises(KeyError, match="'No object named k2 in the file'"):
- pd.read_hdf(store, "k2")
+ with pytest.raises(KeyError, match="'No object named k2 in the file'"):
+ pd.read_hdf(store, "k2")
- # Test that the file is still open after a KeyError and that we can
- # still read from it.
- pd.read_hdf(store, "k1")
+ # Test that the file is still open after a KeyError and that we can
+ # still read from it.
+ pd.read_hdf(store, "k1")
def test_append_frame_column_oriented(self, setup_path):
with ensure_clean_store(setup_path) as store:
|
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/32722 | 2020-03-15T10:37:29Z | 2020-03-16T02:33:50Z | 2020-03-16T02:33:50Z | 2020-03-16T20:27:32Z |
CLN: Switch to using `is not None` rather than `bool()` | diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index 71d9e8e7a577c..fbc87b1fdac04 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -446,7 +446,7 @@ def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True):
stacklevel=3,
)
- f = lambda x: bool(regex.search(x))
+ f = lambda x: regex.search(x) is not None
else:
if case:
f = lambda x: pat in x
@@ -818,7 +818,7 @@ def str_match(arr, pat, case=True, flags=0, na=np.nan):
regex = re.compile(pat, flags=flags)
dtype = bool
- f = lambda x: bool(regex.match(x))
+ f = lambda x: regex.match(x) is not None
return _na_map(f, arr, na, dtype=dtype)
| - [x] closes #32720
- [ ] tests added / passed - This change seemed trivial to *add* tests and should be covered by existing ones.
- [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/32721 | 2020-03-15T09:57:10Z | 2020-03-15T14:07:59Z | 2020-03-15T14:07:59Z | 2020-03-15T16:59:57Z |
DOC: Fix PR01, PR07 in Index.min and Index.max | diff --git a/pandas/core/base.py b/pandas/core/base.py
index 40ff0640a5bc4..e9ad076830899 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -885,6 +885,9 @@ def max(self, axis=None, skipna=True, *args, **kwargs):
axis : int, optional
For compatibility with NumPy. Only 0 or None are allowed.
skipna : bool, default True
+ Exclude NA/null values when showing the result.
+ *args, **kwargs
+ Additional arguments and keywords for compatibility with NumPy.
Returns
-------
@@ -982,6 +985,9 @@ def min(self, axis=None, skipna=True, *args, **kwargs):
axis : {None}
Dummy argument for consistency with Series.
skipna : bool, default True
+ Exclude NA/null values when showing the result.
+ *args, **kwargs
+ Additional arguments and keywords for compatibility with NumPy.
Returns
-------
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Related to #27977.
Output for pandas.Index.min:
```
################################################################################
################################## Validation ##################################
################################################################################
1 Errors found:
No extended summary found
```
and output for pandas.Index.max:
```
################################################################################
################################## Validation ##################################
################################################################################
1 Errors found:
No extended summary found
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/32718 | 2020-03-15T07:06:11Z | 2020-03-16T22:26:32Z | 2020-03-16T22:26:32Z | 2020-03-16T22:26:39Z |
CLN: remove SingleBlockManager._values | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 6362f11a3e032..19e51d05feb92 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1896,7 +1896,7 @@ def pre_processor(vals: np.ndarray) -> Tuple[np.ndarray, Optional[Type]]:
inference = np.int64
elif is_datetime64_dtype(vals):
inference = "datetime64[ns]"
- vals = vals.astype(np.float)
+ vals = np.asarray(vals).astype(np.float)
return vals, inference
@@ -2271,7 +2271,7 @@ def _get_cythonized_result(
for idx, obj in enumerate(self._iterate_slices()):
name = obj.name
- values = obj._data._values
+ values = obj._values
if aggregate:
result_sz = ngroups
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 3a7ab98ea6baf..88cefd3ebfebf 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1552,10 +1552,6 @@ def _post_setstate(self):
def _block(self) -> Block:
return self.blocks[0]
- @property
- def _values(self):
- return self._block.values
-
@property
def _blknos(self):
""" compat with BlockManager """
| https://api.github.com/repos/pandas-dev/pandas/pulls/32716 | 2020-03-15T05:19:02Z | 2020-03-17T16:41:21Z | 2020-03-17T16:41:21Z | 2020-03-17T16:41:42Z | |
CLN: remove values_from_object | diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index db1abae4d6ff3..dc2e8c097bc14 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -94,20 +94,6 @@ cdef:
float64_t NaN = <float64_t>np.NaN
-def values_from_object(obj: object):
- """
- Return my values or the object if we are say an ndarray.
- """
- func: object
-
- func = getattr(obj, '_internal_get_values', None)
- if func is not None:
- # Includes DataFrame, for which we get frame.values
- obj = func()
-
- return obj
-
-
@cython.wraparound(False)
@cython.boundscheck(False)
def memory_usage_of_objects(arr: object[:]) -> int64_t:
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 6230ee34bcd50..056b564ead0e0 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -87,9 +87,6 @@ def maybe_box_datetimelike(value, dtype=None):
return value
-values_from_object = lib.values_from_object
-
-
def is_bool_indexer(key: Any) -> bool:
"""
Check whether `key` is a valid boolean indexer.
diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py
index fdc299ccdfde8..7f93472c766d7 100644
--- a/pandas/core/computation/expressions.py
+++ b/pandas/core/computation/expressions.py
@@ -121,12 +121,12 @@ def _evaluate_numexpr(op, op_str, a, b):
def _where_standard(cond, a, b):
- # Caller is responsible for calling values_from_object if necessary
+ # Caller is responsible for extracting ndarray if necessary
return np.where(cond, a, b)
def _where_numexpr(cond, a, b):
- # Caller is responsible for calling values_from_object if necessary
+ # Caller is responsible for extracting ndarray if necessary
result = None
if _can_use_numexpr(None, "where", a, b, "where"):
| https://api.github.com/repos/pandas-dev/pandas/pulls/32715 | 2020-03-15T02:46:07Z | 2020-03-16T02:22:32Z | 2020-03-16T02:22:32Z | 2020-03-16T02:48:28Z | |
REF: merge NonConsolidateableMixin into ExtensionArray | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 1a92a9486e9e4..07707e1b0093c 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1598,12 +1598,22 @@ def _replace_coerce(
return self
-class NonConsolidatableMixIn:
- """ hold methods for the nonconsolidatable blocks """
+class ExtensionBlock(Block):
+ """
+ Block for holding extension types.
+
+ Notes
+ -----
+ This holds all 3rd-party extension array types. It's also the immediate
+ parent class for our internal extension types' blocks, CategoricalBlock.
+
+ ExtensionArrays are limited to 1-D.
+ """
_can_consolidate = False
_verify_integrity = False
_validate_ndim = False
+ is_extension = True
def __init__(self, values, placement, ndim=None):
"""
@@ -1614,6 +1624,8 @@ def __init__(self, values, placement, ndim=None):
This will call continue to call __init__ for the other base
classes mixed in with this Mixin.
"""
+ values = self._maybe_coerce_values(values)
+
# Placement must be converted to BlockPlacement so that we can check
# its length
if not isinstance(placement, libinternals.BlockPlacement):
@@ -1627,6 +1639,10 @@ def __init__(self, values, placement, ndim=None):
ndim = 2
super().__init__(values, placement, ndim=ndim)
+ if self.ndim == 2 and len(self.mgr_locs) != 1:
+ # TODO(2DEA): check unnecessary with 2D EAs
+ raise AssertionError("block.size != values.size")
+
@property
def shape(self):
if self.ndim == 1:
@@ -1722,29 +1738,6 @@ def _get_unstack_items(self, unstacker, new_columns):
mask = mask.any(0)
return new_placement, new_values, mask
-
-class ExtensionBlock(NonConsolidatableMixIn, Block):
- """
- Block for holding extension types.
-
- Notes
- -----
- This holds all 3rd-party extension array types. It's also the immediate
- parent class for our internal extension types' blocks, CategoricalBlock.
-
- ExtensionArrays are limited to 1-D.
- """
-
- is_extension = True
-
- def __init__(self, values, placement, ndim=None):
- values = self._maybe_coerce_values(values)
- super().__init__(values, placement, ndim)
-
- if self.ndim == 2 and len(self.mgr_locs) != 1:
- # TODO(2DEA): check unnecessary with 2D EAs
- raise AssertionError("block.size != values.size")
-
def _maybe_coerce_values(self, values):
"""
Unbox to an extension array.
diff --git a/pandas/tests/extension/test_external_block.py b/pandas/tests/extension/test_external_block.py
index 8a8dac54cf96a..26606d7e799e8 100644
--- a/pandas/tests/extension/test_external_block.py
+++ b/pandas/tests/extension/test_external_block.py
@@ -3,12 +3,13 @@
import pandas as pd
from pandas.core.internals import BlockManager, SingleBlockManager
-from pandas.core.internals.blocks import Block, NonConsolidatableMixIn
+from pandas.core.internals.blocks import ExtensionBlock
-class CustomBlock(NonConsolidatableMixIn, Block):
+class CustomBlock(ExtensionBlock):
_holder = np.ndarray
+ _can_hold_na = False
def concat_same_type(self, to_concat, placement=None):
"""
| without this mypy complains when we try to annotate some NonConsolidateableMixin methods | https://api.github.com/repos/pandas-dev/pandas/pulls/32714 | 2020-03-15T02:25:19Z | 2020-03-16T02:23:32Z | 2020-03-16T02:23:32Z | 2020-03-16T03:58:07Z |
REF: misplaced tests | diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py
new file mode 100644
index 0000000000000..e6d002369f758
--- /dev/null
+++ b/pandas/tests/frame/methods/test_drop.py
@@ -0,0 +1,54 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas._testing as tm
+
+
+@pytest.mark.parametrize(
+ "msg,labels,level",
+ [
+ (r"labels \[4\] not found in level", 4, "a"),
+ (r"labels \[7\] not found in level", 7, "b"),
+ ],
+)
+def test_drop_raise_exception_if_labels_not_in_level(msg, labels, level):
+ # GH 8594
+ mi = pd.MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"])
+ s = pd.Series([10, 20, 30], index=mi)
+ df = pd.DataFrame([10, 20, 30], index=mi)
+
+ with pytest.raises(KeyError, match=msg):
+ s.drop(labels, level=level)
+ with pytest.raises(KeyError, match=msg):
+ df.drop(labels, level=level)
+
+
+@pytest.mark.parametrize("labels,level", [(4, "a"), (7, "b")])
+def test_drop_errors_ignore(labels, level):
+ # GH 8594
+ mi = pd.MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"])
+ s = pd.Series([10, 20, 30], index=mi)
+ df = pd.DataFrame([10, 20, 30], index=mi)
+
+ expected_s = s.drop(labels, level=level, errors="ignore")
+ tm.assert_series_equal(s, expected_s)
+
+ expected_df = df.drop(labels, level=level, errors="ignore")
+ tm.assert_frame_equal(df, expected_df)
+
+
+def test_drop_with_non_unique_datetime_index_and_invalid_keys():
+ # GH 30399
+
+ # define dataframe with unique datetime index
+ df = pd.DataFrame(
+ np.random.randn(5, 3),
+ columns=["a", "b", "c"],
+ index=pd.date_range("2012", freq="H", periods=5),
+ )
+ # create dataframe with non-unique datetime index
+ df = df.iloc[[0, 2, 2, 3]].copy()
+
+ with pytest.raises(KeyError, match="not found in axis"):
+ df.drop(["a", "b"]) # Dropping with labels not exist in the index
diff --git a/pandas/tests/indexes/multi/test_drop.py b/pandas/tests/indexes/multi/test_drop.py
index b909025b3f2f9..6ba565f0406ab 100644
--- a/pandas/tests/indexes/multi/test_drop.py
+++ b/pandas/tests/indexes/multi/test_drop.py
@@ -139,52 +139,3 @@ def test_drop_not_lexsorted():
tm.assert_index_equal(lexsorted_mi, not_lexsorted_mi)
with tm.assert_produces_warning(PerformanceWarning):
tm.assert_index_equal(lexsorted_mi.drop("a"), not_lexsorted_mi.drop("a"))
-
-
-@pytest.mark.parametrize(
- "msg,labels,level",
- [
- (r"labels \[4\] not found in level", 4, "a"),
- (r"labels \[7\] not found in level", 7, "b"),
- ],
-)
-def test_drop_raise_exception_if_labels_not_in_level(msg, labels, level):
- # GH 8594
- mi = MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"])
- s = pd.Series([10, 20, 30], index=mi)
- df = pd.DataFrame([10, 20, 30], index=mi)
-
- with pytest.raises(KeyError, match=msg):
- s.drop(labels, level=level)
- with pytest.raises(KeyError, match=msg):
- df.drop(labels, level=level)
-
-
-@pytest.mark.parametrize("labels,level", [(4, "a"), (7, "b")])
-def test_drop_errors_ignore(labels, level):
- # GH 8594
- mi = MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"])
- s = pd.Series([10, 20, 30], index=mi)
- df = pd.DataFrame([10, 20, 30], index=mi)
-
- expected_s = s.drop(labels, level=level, errors="ignore")
- tm.assert_series_equal(s, expected_s)
-
- expected_df = df.drop(labels, level=level, errors="ignore")
- tm.assert_frame_equal(df, expected_df)
-
-
-def test_drop_with_non_unique_datetime_index_and_invalid_keys():
- # GH 30399
-
- # define dataframe with unique datetime index
- df = pd.DataFrame(
- np.random.randn(5, 3),
- columns=["a", "b", "c"],
- index=pd.date_range("2012", freq="H", periods=5),
- )
- # create dataframe with non-unique datetime index
- df = df.iloc[[0, 2, 2, 3]].copy()
-
- with pytest.raises(KeyError, match="not found in axis"):
- df.drop(["a", "b"]) # Dropping with labels not exist in the index
| https://api.github.com/repos/pandas-dev/pandas/pulls/32713 | 2020-03-15T01:19:08Z | 2020-03-16T02:31:03Z | 2020-03-16T02:31:03Z | 2020-03-16T03:57:17Z | |
CLN: Prelims for stronger typing in Block methods | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index b0909e23b44c5..eb8e6a70bb54e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -6464,7 +6464,7 @@ def melt(
# ----------------------------------------------------------------------
# Time series-related
- def diff(self, periods=1, axis=0) -> "DataFrame":
+ def diff(self, periods: int = 1, axis: Axis = 0) -> "DataFrame":
"""
First discrete difference of element.
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 8d56311331d4d..9720819adeb16 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8587,12 +8587,15 @@ def _where(
for dt in cond.dtypes:
if not is_bool_dtype(dt):
raise ValueError(msg.format(dtype=dt))
+ else:
+ # GH#21947 we have an empty DataFrame, could be object-dtype
+ cond = cond.astype(bool)
cond = -cond if inplace else cond
# try to align with other
try_quick = True
- if hasattr(other, "align"):
+ if isinstance(other, NDFrame):
# align with me
if other.ndim <= self.ndim:
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 93d4b02310d54..3a7ab98ea6baf 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -569,8 +569,8 @@ def setitem(self, indexer, value) -> "BlockManager":
def putmask(self, **kwargs):
return self.apply("putmask", **kwargs)
- def diff(self, **kwargs) -> "BlockManager":
- return self.apply("diff", **kwargs)
+ def diff(self, n: int, axis: int) -> "BlockManager":
+ return self.apply("diff", n=n, axis=axis)
def interpolate(self, **kwargs) -> "BlockManager":
return self.apply("interpolate", **kwargs)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 2d8eb9b29498a..1c815fa8f52f5 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -872,6 +872,7 @@ def __getitem__(self, key):
if com.is_bool_indexer(key):
key = check_bool_indexer(self.index, key)
+ key = np.asarray(key, dtype=bool)
return self._get_values(key)
return self._get_with(key)
@@ -993,6 +994,7 @@ def __setitem__(self, key, value):
if com.is_bool_indexer(key):
key = check_bool_indexer(self.index, key)
+ key = np.asarray(key, dtype=bool)
try:
self._where(~key, value, inplace=True)
return
@@ -2240,7 +2242,7 @@ def cov(self, other, min_periods=None) -> float:
return np.nan
return nanops.nancov(this.values, other.values, min_periods=min_periods)
- def diff(self, periods=1) -> "Series":
+ def diff(self, periods: int = 1) -> "Series":
"""
First discrete difference of element.
diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py
index eee754a47fb8c..bbf8ee5978e7c 100644
--- a/pandas/tests/frame/indexing/test_where.py
+++ b/pandas/tests/frame/indexing/test_where.py
@@ -397,7 +397,8 @@ def test_where_none(self):
def test_where_empty_df_and_empty_cond_having_non_bool_dtypes(self):
# see gh-21947
df = pd.DataFrame(columns=["a"])
- cond = df.applymap(lambda x: x > 0)
+ cond = df
+ assert (cond.dtypes == object).all()
result = df.where(cond)
tm.assert_frame_equal(result, df)
| https://api.github.com/repos/pandas-dev/pandas/pulls/32712 | 2020-03-15T01:13:09Z | 2020-03-16T02:28:56Z | 2020-03-16T02:28:56Z | 2020-03-16T14:59:39Z | |
Requested follow-up whatsnews | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 9be994ee7104f..11757e1bf14e0 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -238,7 +238,7 @@ Categorical
- Bug where :func:`merge` was unable to join on non-unique categorical indices (:issue:`28189`)
- Bug when passing categorical data to :class:`Index` constructor along with ``dtype=object`` incorrectly returning a :class:`CategoricalIndex` instead of object-dtype :class:`Index` (:issue:`32167`)
- Bug where :class:`Categorical` comparison operator ``__ne__`` would incorrectly evaluate to ``False`` when either element was missing (:issue:`32276`)
--
+- :meth:`Categorical.fillna` now accepts :class:`Categorical` ``other`` argument (:issue:`32420`)
Datetimelike
^^^^^^^^^^^^
@@ -269,6 +269,7 @@ Numeric
- Bug in :meth:`DataFrame.floordiv` with ``axis=0`` not treating division-by-zero like :meth:`Series.floordiv` (:issue:`31271`)
- Bug in :meth:`to_numeric` with string argument ``"uint64"`` and ``errors="coerce"`` silently fails (:issue:`32394`)
- Bug in :meth:`to_numeric` with ``downcast="unsigned"`` fails for empty data (:issue:`32493`)
+- Bug in :meth:`DataFrame.mean` with ``numeric_only=False`` and either ``datetime64`` dtype or ``PeriodDtype`` column incorrectly raising ``TypeError`` (:issue:`32426`)
-
Conversion
@@ -377,7 +378,7 @@ Reshaping
Sparse
^^^^^^
-
+- Creating a :class:`SparseArray` from timezone-aware dtype will issue a warning before dropping timezone information, instead of doing so silently (:issue:`32501`)
-
-
@@ -395,6 +396,7 @@ Other
- Set operations on an object-dtype :class:`Index` now always return object-dtype results (:issue:`31401`)
- Bug in :meth:`AbstractHolidayCalendar.holidays` when no rules were defined (:issue:`31415`)
- Bug in :meth:`DataFrame.to_records` incorrectly losing timezone information in timezone-aware ``datetime64`` columns (:issue:`32535`)
+- :meth:`IntegerArray.astype` now supports ``datetime64`` dtype (:issue:32538`)
.. ---------------------------------------------------------------------------
| https://api.github.com/repos/pandas-dev/pandas/pulls/32711 | 2020-03-15T01:06:58Z | 2020-03-16T16:40:54Z | 2020-03-16T16:40:54Z | 2020-03-16T16:41:13Z | |
REF: avoid runtime import of Index | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 1a51101bc8db8..5b324bc5753ec 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -2025,9 +2025,7 @@ def sort_mixed(values):
)
codes = ensure_platform_int(np.asarray(codes))
- from pandas import Index
-
- if not assume_unique and not Index(values).is_unique:
+ if not assume_unique and not len(unique(values)) == len(values):
raise ValueError("values should be unique if codes is not None")
if sorter is None:
| https://api.github.com/repos/pandas-dev/pandas/pulls/32710 | 2020-03-15T00:00:24Z | 2020-03-15T00:31:44Z | 2020-03-15T00:31:44Z | 2020-03-15T01:27:43Z | |
skip 32 bit linux | diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml
index c9a2e4eefd19d..437cc9b161e8a 100644
--- a/ci/azure/posix.yml
+++ b/ci/azure/posix.yml
@@ -38,11 +38,11 @@ jobs:
LC_ALL: "it_IT.utf8"
EXTRA_APT: "language-pack-it xsel"
- py36_32bit:
- ENV_FILE: ci/deps/azure-36-32bit.yaml
- CONDA_PY: "36"
- PATTERN: "not slow and not network and not clipboard"
- BITS32: "yes"
+ #py36_32bit:
+ # ENV_FILE: ci/deps/azure-36-32bit.yaml
+ # CONDA_PY: "36"
+ # PATTERN: "not slow and not network and not clipboard"
+ # BITS32: "yes"
py37_locale:
ENV_FILE: ci/deps/azure-37-locale.yaml
| follow up to #32706 | https://api.github.com/repos/pandas-dev/pandas/pulls/32708 | 2020-03-14T19:32:57Z | 2020-03-14T19:39:09Z | 2020-03-14T19:39:09Z | 2020-08-26T13:19:15Z |
CLN: unnecessary usages of Block.get_values | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 83980e9028e9a..1a92a9486e9e4 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -605,7 +605,9 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
# astype formatting
else:
- values = self.get_values()
+ # Because we have neither is_extension nor is_datelike,
+ # self.values already has the correct shape
+ values = self.values
else:
values = self.get_values(dtype=dtype)
@@ -663,7 +665,7 @@ def _can_hold_element(self, element: Any) -> bool:
def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs):
""" convert to our native types format, slicing if desired """
- values = self.get_values()
+ values = self.values
if slicer is not None:
values = values[:, slicer]
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 7570f6eddbd9c..6839d138fbf73 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -217,7 +217,7 @@ def get_reindexed_values(self, empty_dtype, upcasted_na):
else:
# No dtype upcasting is done here, it will be performed during
# concatenation itself.
- values = self.block.get_values()
+ values = self.block.values
if not self.indexers:
# If there's no indexing to be done, we want to signal outside
| https://api.github.com/repos/pandas-dev/pandas/pulls/32707 | 2020-03-14T18:29:17Z | 2020-03-14T21:31:18Z | 2020-03-14T21:31:18Z | 2020-03-14T21:41:11Z | |
CI: Update pipelines config to trigger on PRs | diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 42a039af46e94..d042bda77d4e8 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -1,4 +1,10 @@
# Adapted from https://github.com/numba/numba/blob/master/azure-pipelines.yml
+trigger:
+- master
+
+pr:
+- master
+
jobs:
# Mac and Linux use the same template
- template: ci/azure/posix.yml
| - [X] closes #32705
| https://api.github.com/repos/pandas-dev/pandas/pulls/32706 | 2020-03-14T18:26:00Z | 2020-03-14T19:30:03Z | 2020-03-14T19:30:02Z | 2020-06-15T15:57:58Z |
DOC: Add examples to Series operators (#24589) | diff --git a/pandas/core/ops/docstrings.py b/pandas/core/ops/docstrings.py
index 203ea3946d1b2..7b03b4b449ea5 100644
--- a/pandas/core/ops/docstrings.py
+++ b/pandas/core/ops/docstrings.py
@@ -53,7 +53,7 @@ def _make_flex_doc(op_name, typ):
return doc
-_add_example_SERIES = """
+_common_examples_algebra_SERIES = """
Examples
--------
>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
@@ -69,33 +69,44 @@ def _make_flex_doc(op_name, typ):
b NaN
d 1.0
e NaN
-dtype: float64
->>> a.add(b, fill_value=0)
-a 2.0
-b 1.0
-c 1.0
-d 1.0
-e NaN
-dtype: float64
-"""
+dtype: float64"""
-_sub_example_SERIES = """
+_common_examples_comparison_SERIES = """
Examples
--------
->>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
+>>> a = pd.Series([1, 1, 1, np.nan, 1], index=['a', 'b', 'c', 'd', 'e'])
>>> a
a 1.0
b 1.0
c 1.0
d NaN
+e 1.0
dtype: float64
->>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
+>>> b = pd.Series([0, 1, 2, np.nan, 1], index=['a', 'b', 'c', 'd', 'f'])
>>> b
-a 1.0
-b NaN
+a 0.0
+b 1.0
+c 2.0
+d NaN
+f 1.0
+dtype: float64"""
+
+_add_example_SERIES = (
+ _common_examples_algebra_SERIES
+ + """
+>>> a.add(b, fill_value=0)
+a 2.0
+b 1.0
+c 1.0
d 1.0
e NaN
dtype: float64
+"""
+)
+
+_sub_example_SERIES = (
+ _common_examples_algebra_SERIES
+ + """
>>> a.subtract(b, fill_value=0)
a 0.0
b 1.0
@@ -104,24 +115,11 @@ def _make_flex_doc(op_name, typ):
e NaN
dtype: float64
"""
+)
-_mul_example_SERIES = """
-Examples
---------
->>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
->>> a
-a 1.0
-b 1.0
-c 1.0
-d NaN
-dtype: float64
->>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
->>> b
-a 1.0
-b NaN
-d 1.0
-e NaN
-dtype: float64
+_mul_example_SERIES = (
+ _common_examples_algebra_SERIES
+ + """
>>> a.multiply(b, fill_value=0)
a 1.0
b 0.0
@@ -130,24 +128,11 @@ def _make_flex_doc(op_name, typ):
e NaN
dtype: float64
"""
+)
-_div_example_SERIES = """
-Examples
---------
->>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
->>> a
-a 1.0
-b 1.0
-c 1.0
-d NaN
-dtype: float64
->>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
->>> b
-a 1.0
-b NaN
-d 1.0
-e NaN
-dtype: float64
+_div_example_SERIES = (
+ _common_examples_algebra_SERIES
+ + """
>>> a.divide(b, fill_value=0)
a 1.0
b inf
@@ -156,24 +141,11 @@ def _make_flex_doc(op_name, typ):
e NaN
dtype: float64
"""
+)
-_floordiv_example_SERIES = """
-Examples
---------
->>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
->>> a
-a 1.0
-b 1.0
-c 1.0
-d NaN
-dtype: float64
->>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
->>> b
-a 1.0
-b NaN
-d 1.0
-e NaN
-dtype: float64
+_floordiv_example_SERIES = (
+ _common_examples_algebra_SERIES
+ + """
>>> a.floordiv(b, fill_value=0)
a 1.0
b NaN
@@ -182,24 +154,11 @@ def _make_flex_doc(op_name, typ):
e NaN
dtype: float64
"""
+)
-_mod_example_SERIES = """
-Examples
---------
->>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
->>> a
-a 1.0
-b 1.0
-c 1.0
-d NaN
-dtype: float64
->>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
->>> b
-a 1.0
-b NaN
-d 1.0
-e NaN
-dtype: float64
+_mod_example_SERIES = (
+ _common_examples_algebra_SERIES
+ + """
>>> a.mod(b, fill_value=0)
a 0.0
b NaN
@@ -208,23 +167,10 @@ def _make_flex_doc(op_name, typ):
e NaN
dtype: float64
"""
-_pow_example_SERIES = """
-Examples
---------
->>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
->>> a
-a 1.0
-b 1.0
-c 1.0
-d NaN
-dtype: float64
->>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
->>> b
-a 1.0
-b NaN
-d 1.0
-e NaN
-dtype: float64
+)
+_pow_example_SERIES = (
+ _common_examples_algebra_SERIES
+ + """
>>> a.pow(b, fill_value=0)
a 1.0
b 1.0
@@ -233,6 +179,89 @@ def _make_flex_doc(op_name, typ):
e NaN
dtype: float64
"""
+)
+
+_ne_example_SERIES = (
+ _common_examples_algebra_SERIES
+ + """
+>>> a.ne(b, fill_value=0)
+a False
+b True
+c True
+d True
+e True
+dtype: bool
+"""
+)
+
+_eq_example_SERIES = (
+ _common_examples_algebra_SERIES
+ + """
+>>> a.eq(b, fill_value=0)
+a True
+b False
+c False
+d False
+e False
+dtype: bool
+"""
+)
+
+_lt_example_SERIES = (
+ _common_examples_comparison_SERIES
+ + """
+>>> a.lt(b, fill_value=0)
+a False
+b False
+c True
+d False
+e False
+f True
+dtype: bool
+"""
+)
+
+_le_example_SERIES = (
+ _common_examples_comparison_SERIES
+ + """
+>>> a.le(b, fill_value=0)
+a False
+b True
+c True
+d False
+e False
+f True
+dtype: bool
+"""
+)
+
+_gt_example_SERIES = (
+ _common_examples_comparison_SERIES
+ + """
+>>> a.gt(b, fill_value=0)
+a True
+b False
+c False
+d False
+e True
+f False
+dtype: bool
+"""
+)
+
+_ge_example_SERIES = (
+ _common_examples_comparison_SERIES
+ + """
+>>> a.ge(b, fill_value=0)
+a True
+b True
+c False
+d False
+e True
+f False
+dtype: bool
+"""
+)
_returns_series = """Series\n The result of the operation."""
@@ -306,42 +335,42 @@ def _make_flex_doc(op_name, typ):
"op": "==",
"desc": "Equal to",
"reverse": None,
- "series_examples": None,
+ "series_examples": _eq_example_SERIES,
"series_returns": _returns_series,
},
"ne": {
"op": "!=",
"desc": "Not equal to",
"reverse": None,
- "series_examples": None,
+ "series_examples": _ne_example_SERIES,
"series_returns": _returns_series,
},
"lt": {
"op": "<",
"desc": "Less than",
"reverse": None,
- "series_examples": None,
+ "series_examples": _lt_example_SERIES,
"series_returns": _returns_series,
},
"le": {
"op": "<=",
"desc": "Less than or equal to",
"reverse": None,
- "series_examples": None,
+ "series_examples": _le_example_SERIES,
"series_returns": _returns_series,
},
"gt": {
"op": ">",
"desc": "Greater than",
"reverse": None,
- "series_examples": None,
+ "series_examples": _gt_example_SERIES,
"series_returns": _returns_series,
},
"ge": {
"op": ">=",
"desc": "Greater than or equal to",
"reverse": None,
- "series_examples": None,
+ "series_examples": _ge_example_SERIES,
"series_returns": _returns_series,
},
}
| Further work on #24589. PR #25524 added examples for many operations but not `pandas.Series.eq`, `pandas.Series.ne`, `pandas.Series.gt`, `pandas.Series.ge`, `pandas.series.le`, and `pandas.series.lt`. This adds examples for those.
`pandas.Series.divmod` is still missing an example as discussed in #25524.
| https://api.github.com/repos/pandas-dev/pandas/pulls/32704 | 2020-03-14T16:33:25Z | 2020-03-24T21:31:21Z | 2020-03-24T21:31:21Z | 2020-03-28T20:12:11Z |
BUG: Add errors argument to to_csv() call to enable error handling for encoders | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 2243790a663df..5fd90e8726264 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -288,6 +288,7 @@ Other enhancements
- :meth:`HDFStore.put` now accepts `track_times` parameter. Parameter is passed to ``create_table`` method of ``PyTables`` (:issue:`32682`).
- Make :class:`pandas.core.window.Rolling` and :class:`pandas.core.window.Expanding` iterable(:issue:`11704`)
- Make ``option_context`` a :class:`contextlib.ContextDecorator`, which allows it to be used as a decorator over an entire function (:issue:`34253`).
+- :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` now accept an ``errors`` argument (:issue:`22610`)
- :meth:`groupby.transform` now allows ``func`` to be ``pad``, ``backfill`` and ``cumcount`` (:issue:`31269`).
- :meth:`~pandas.io.json.read_json` now accepts `nrows` parameter. (:issue:`33916`).
- :meth `~pandas.io.gbq.read_gbq` now allows to disable progress bar (:issue:`33360`).
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 8c57c2b8b851b..87bb4ce7055be 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3049,6 +3049,7 @@ def to_csv(
doublequote: bool_t = True,
escapechar: Optional[str] = None,
decimal: Optional[str] = ".",
+ errors: str = "strict",
) -> Optional[str]:
r"""
Write object to a comma-separated values (csv) file.
@@ -3143,6 +3144,12 @@ def to_csv(
decimal : str, default '.'
Character recognized as decimal separator. E.g. use ',' for
European data.
+ errors : str, default 'strict'
+ Specifies how encoding and decoding errors are to be handled.
+ See the errors argument for :func:`open` for a full list
+ of options.
+
+ .. versionadded:: 1.1.0
Returns
-------
@@ -3180,6 +3187,7 @@ def to_csv(
line_terminator=line_terminator,
sep=sep,
encoding=encoding,
+ errors=errors,
compression=compression,
quoting=quoting,
na_rep=na_rep,
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 8349acafca1e3..055f84970e916 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -352,6 +352,7 @@ def get_handle(
compression: Optional[Union[str, Mapping[str, Any]]] = None,
memory_map: bool = False,
is_text: bool = True,
+ errors=None,
):
"""
Get file handle for given path/buffer and mode.
@@ -390,6 +391,12 @@ def get_handle(
is_text : boolean, default True
whether file/buffer is in text format (csv, json, etc.), or in binary
mode (pickle, etc.).
+ errors : str, default 'strict'
+ Specifies how encoding and decoding errors are to be handled.
+ See the errors argument for :func:`open` for a full list
+ of options.
+
+ .. versionadded:: 1.1.0
Returns
-------
@@ -475,7 +482,7 @@ def get_handle(
elif is_path:
if encoding:
# Encoding
- f = open(path_or_buf, mode, encoding=encoding, newline="")
+ f = open(path_or_buf, mode, encoding=encoding, errors=errors, newline="")
elif is_text:
# No explicit encoding
f = open(path_or_buf, mode, errors="replace", newline="")
@@ -488,7 +495,7 @@ def get_handle(
if is_text and (compression or isinstance(f, need_text_wrapping)):
from io import TextIOWrapper
- g = TextIOWrapper(f, encoding=encoding, newline="")
+ g = TextIOWrapper(f, encoding=encoding, errors=errors, newline="")
if not isinstance(f, (BufferedIOBase, RawIOBase)):
handles.append(g)
f = g
diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py
index dcd764bec7426..5bd51dc8351f6 100644
--- a/pandas/io/formats/csvs.py
+++ b/pandas/io/formats/csvs.py
@@ -44,6 +44,7 @@ def __init__(
index_label: Optional[Union[bool, Hashable, Sequence[Hashable]]] = None,
mode: str = "w",
encoding: Optional[str] = None,
+ errors: str = "strict",
compression: Union[str, Mapping[str, str], None] = "infer",
quoting: Optional[int] = None,
line_terminator="\n",
@@ -77,6 +78,7 @@ def __init__(
if encoding is None:
encoding = "utf-8"
self.encoding = encoding
+ self.errors = errors
self.compression = infer_compression(self.path_or_buf, compression)
if quoting is None:
@@ -184,6 +186,7 @@ def save(self) -> None:
self.path_or_buf,
self.mode,
encoding=self.encoding,
+ errors=self.errors,
compression=dict(self.compression_args, method=self.compression),
)
close = True
@@ -215,6 +218,7 @@ def save(self) -> None:
self.path_or_buf,
self.mode,
encoding=self.encoding,
+ errors=self.errors,
compression=compression,
)
f.write(buf)
diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py
index b3ee8da52dece..4c86e3a16b135 100644
--- a/pandas/tests/io/formats/test_to_csv.py
+++ b/pandas/tests/io/formats/test_to_csv.py
@@ -597,3 +597,13 @@ def test_na_rep_truncated(self):
result = pd.Series([1.1, 2.2]).to_csv(na_rep=".")
expected = tm.convert_rows_list_to_csv_str([",0", "0,1.1", "1,2.2"])
assert result == expected
+
+ @pytest.mark.parametrize("errors", ["surrogatepass", "ignore", "replace"])
+ def test_to_csv_errors(self, errors):
+ # GH 22610
+ data = ["\ud800foo"]
+ ser = pd.Series(data, index=pd.Index(data))
+ with tm.ensure_clean("test.csv") as path:
+ ser.to_csv(path, errors=errors)
+ # No use in reading back the data as it is not the same anymore
+ # due to the error handling
| - [x] closes #22610
- [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/32702 | 2020-03-14T15:59:58Z | 2020-06-08T23:36:05Z | 2020-06-08T23:36:05Z | 2020-06-09T19:13:07Z |
BUG: Fix segfault on dir of a DataFrame with a unicode surrogate character in the column name | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 0d3a9a8f969a4..b97dd580e2d8a 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -402,6 +402,7 @@ Other
- Fixed :func:`pandas.testing.assert_series_equal` to correctly raise if left object is a different subclass with ``check_series_type=True`` (:issue:`32670`).
- :meth:`IntegerArray.astype` now supports ``datetime64`` dtype (:issue:32538`)
- Fixed bug in :func:`pandas.testing.assert_series_equal` where dtypes were checked for ``Interval`` and ``ExtensionArray`` operands when ``check_dtype`` was ``False`` (:issue:`32747`)
+- Bug in :meth:`DataFrame.__dir__` caused a segfault when using unicode surrogates in a column name (:issue:`25509`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in
index 811025a4b5764..d662e03304e2e 100644
--- a/pandas/_libs/hashtable_class_helper.pxi.in
+++ b/pandas/_libs/hashtable_class_helper.pxi.in
@@ -12,6 +12,9 @@ WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in
from pandas._libs.tslibs.util cimport get_c_string
from pandas._libs.missing cimport C_NA
+cdef extern from "Python.h":
+ void PyErr_Clear()
+
{{py:
# name, dtype, c_type
@@ -790,6 +793,9 @@ cdef class StringHashTable(HashTable):
else:
# if ignore_na is False, we also stringify NaN/None/etc.
v = get_c_string(<str>val)
+ if v == NULL:
+ PyErr_Clear()
+ v = get_c_string(<str>repr(val))
vecs[i] = v
# compute
diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py
index a021dd91a7d26..940a76601b75e 100644
--- a/pandas/tests/frame/test_api.py
+++ b/pandas/tests/frame/test_api.py
@@ -127,6 +127,14 @@ def test_not_hashable(self):
with pytest.raises(TypeError, match=msg):
hash(empty_frame)
+ def test_column_name_contains_unicode_surrogate(self):
+ # GH 25509
+ colname = "\ud83d"
+ df = DataFrame({colname: []})
+ # this should not crash
+ assert colname not in dir(df)
+ assert df.columns[0] == colname
+
def test_new_empty_index(self):
df1 = DataFrame(np.random.randn(0, 3))
df2 = DataFrame(np.random.randn(0, 3))
diff --git a/pandas/tests/io/parser/test_dtypes.py b/pandas/tests/io/parser/test_dtypes.py
index 11dcf7f04f76b..e68dcb3aa577e 100644
--- a/pandas/tests/io/parser/test_dtypes.py
+++ b/pandas/tests/io/parser/test_dtypes.py
@@ -192,7 +192,7 @@ def test_categorical_dtype_utf16(all_parsers, csv_dir_path):
pth = os.path.join(csv_dir_path, "utf16_ex.txt")
parser = all_parsers
encoding = "utf-16"
- sep = ","
+ sep = "\t"
expected = parser.read_csv(pth, sep=sep, encoding=encoding)
expected = expected.apply(Categorical)
| Return a `repr()` version if the column name string is not printable. This also means the the column name is not present in the output of `dir()`
- [x] closes #25509
- [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/32701 | 2020-03-14T15:13:37Z | 2020-03-19T19:50:40Z | 2020-03-19T19:50:39Z | 2020-03-19T22:02:36Z |
Track times | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 5c74965bffdd7..1437006ee3fb8 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -234,6 +234,7 @@ Other enhancements
compression library. Compression was also added to the low-level Stata-file writers
:class:`~pandas.io.stata.StataWriter`, :class:`~pandas.io.stata.StataWriter117`,
and :class:`~pandas.io.stata.StataWriterUTF8` (:issue:`26599`).
+- :meth:`HDFStore.put` now accepts `track_times` parameter. Parameter is passed to ``create_table`` method of ``PyTables`` (:issue:`32682`).
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 345402e619ff2..85fcfd107b121 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -984,6 +984,7 @@ def put(
data_columns: Optional[List[str]] = None,
encoding=None,
errors: str = "strict",
+ track_times: bool = True,
):
"""
Store object in HDFStore.
@@ -1010,6 +1011,12 @@ def put(
Provide an encoding for strings.
dropna : bool, default False, do not write an ALL nan row to
The store settable by the option 'io.hdf.dropna_table'.
+ track_times : bool, default True
+ Parameter is propagated to 'create_table' method of 'PyTables'.
+ If set to False it enables to have the same h5 files (same hashes)
+ independent on creation time.
+
+ .. versionadded:: 1.1.0
"""
if format is None:
format = get_option("io.hdf.default_format") or "fixed"
@@ -1027,6 +1034,7 @@ def put(
data_columns=data_columns,
encoding=encoding,
errors=errors,
+ track_times=track_times,
)
def remove(self, key: str, where=None, start=None, stop=None):
@@ -1626,6 +1634,7 @@ def _write_to_group(
data_columns=None,
encoding=None,
errors: str = "strict",
+ track_times: bool = True,
):
group = self.get_node(key)
@@ -1688,6 +1697,7 @@ def _write_to_group(
dropna=dropna,
nan_rep=nan_rep,
data_columns=data_columns,
+ track_times=track_times,
)
if isinstance(s, Table) and index:
@@ -4106,8 +4116,8 @@ def write(
dropna=False,
nan_rep=None,
data_columns=None,
+ track_times=True,
):
-
if not append and self.is_exists:
self._handle.remove_node(self.group, "table")
@@ -4137,6 +4147,8 @@ def write(
# set the table attributes
table.set_attrs()
+ options["track_times"] = track_times
+
# create the table
table._handle.create_table(table.group, **options)
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index c937f9ac42818..fe59b989bab7e 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -1,10 +1,12 @@
import datetime
from datetime import timedelta
from distutils.version import LooseVersion
+import hashlib
from io import BytesIO
import os
from pathlib import Path
import re
+import time
from warnings import catch_warnings, simplefilter
import numpy as np
@@ -296,6 +298,49 @@ def test_keys(self, setup_path):
assert set(store.keys()) == expected
assert set(store) == expected
+ def test_no_track_times(self, setup_path):
+
+ # GH 32682
+ # enables to set track_times (see `pytables` `create_table` documentation)
+
+ def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
+ h = hash_factory()
+ with open(filename, "rb") as f:
+ for chunk in iter(lambda: f.read(chunk_num_blocks * h.block_size), b""):
+ h.update(chunk)
+ return h.digest()
+
+ def create_h5_and_return_checksum(track_times):
+ with ensure_clean_path(setup_path) as path:
+ df = pd.DataFrame({"a": [1]})
+
+ with pd.HDFStore(path, mode="w") as hdf:
+ hdf.put(
+ "table",
+ df,
+ format="table",
+ data_columns=True,
+ index=None,
+ track_times=track_times,
+ )
+
+ return checksum(path)
+
+ checksum_0_tt_false = create_h5_and_return_checksum(track_times=False)
+ checksum_0_tt_true = create_h5_and_return_checksum(track_times=True)
+
+ # sleep is necessary to create h5 with different creation time
+ time.sleep(1)
+
+ checksum_1_tt_false = create_h5_and_return_checksum(track_times=False)
+ checksum_1_tt_true = create_h5_and_return_checksum(track_times=True)
+
+ # checksums are the same if track_time = False
+ assert checksum_0_tt_false == checksum_1_tt_false
+
+ # checksums are NOT same if track_time = True
+ assert checksum_0_tt_true != checksum_1_tt_true
+
def test_keys_ignore_hdf_softlink(self, setup_path):
# GH 20523
| I implement feature request https://github.com/pandas-dev/pandas/issues/32682 but if someone has more experience with pytables consider these changes.
The h5 files generated with track_times=False has the same md5 hashes, that is covered in the unit test as well as the fact that the hashes are not the same with track_times=True
- [x] closes #32682
- [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/32700 | 2020-03-14T14:24:32Z | 2020-05-14T12:38:24Z | 2020-05-14T12:38:24Z | 2020-07-30T14:01:59Z |
DOC: Clarify output of diff (returned type and possible overflow) | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 2d181e826c2a9..483d7746b3e2d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -7019,40 +7019,14 @@ def melt(
# ----------------------------------------------------------------------
# Time series-related
- def diff(self, periods: int = 1, axis: Axis = 0) -> "DataFrame":
- """
- First discrete difference of element.
-
- Calculates the difference of a DataFrame element compared with another
- element in the DataFrame (default is the element in the same column
- of the previous row).
-
- Parameters
- ----------
- periods : int, default 1
- Periods to shift for calculating difference, accepts negative
- values.
- axis : {0 or 'index', 1 or 'columns'}, default 0
- Take difference over rows (0) or columns (1).
-
- Returns
- -------
- DataFrame
-
- See Also
- --------
- Series.diff: First discrete difference for a Series.
- DataFrame.pct_change: Percent change over given number of periods.
- DataFrame.shift: Shift index by desired number of periods with an
- optional time freq.
-
- Notes
- -----
- For boolean dtypes, this uses :meth:`operator.xor` rather than
- :meth:`operator.sub`.
-
- Examples
- --------
+ @doc(
+ Series.diff,
+ klass="Dataframe",
+ extra_params="axis : {0 or 'index', 1 or 'columns'}, default 0\n "
+ "Take difference over rows (0) or columns (1).\n",
+ other_klass="Series",
+ examples=dedent(
+ """
Difference with previous row
>>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],
@@ -7108,7 +7082,18 @@ def diff(self, periods: int = 1, axis: Axis = 0) -> "DataFrame":
3 -1.0 -2.0 -9.0
4 -1.0 -3.0 -11.0
5 NaN NaN NaN
- """
+
+ Overflow in input dtype
+
+ >>> df = pd.DataFrame({'a': [1, 0]}, dtype=np.uint8)
+ >>> df.diff()
+ a
+ 0 NaN
+ 1 255.0"""
+ ),
+ )
+ def diff(self, periods: int = 1, axis: Axis = 0) -> "DataFrame":
+
bm_axis = self._get_block_manager_axis(axis)
self._consolidate_inplace()
diff --git a/pandas/core/series.py b/pandas/core/series.py
index e107b66d33b1c..c9c63b8342657 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2293,38 +2293,12 @@ def cov(self, other, min_periods=None) -> float:
return np.nan
return nanops.nancov(this.values, other.values, min_periods=min_periods)
- def diff(self, periods: int = 1) -> "Series":
- """
- First discrete difference of element.
-
- Calculates the difference of a Series element compared with another
- element in the Series (default is element in previous row).
-
- Parameters
- ----------
- periods : int, default 1
- Periods to shift for calculating difference, accepts negative
- values.
-
- Returns
- -------
- Series
- First differences of the Series.
-
- See Also
- --------
- Series.pct_change: Percent change over given number of periods.
- Series.shift: Shift index by desired number of periods with an
- optional time freq.
- DataFrame.diff: First discrete difference of object.
-
- Notes
- -----
- For boolean dtypes, this uses :meth:`operator.xor` rather than
- :meth:`operator.sub`.
-
- Examples
- --------
+ @doc(
+ klass="Series",
+ extra_params="",
+ other_klass="DataFrame",
+ examples=dedent(
+ """
Difference with previous row
>>> s = pd.Series([1, 1, 2, 3, 5, 8])
@@ -2358,6 +2332,51 @@ def diff(self, periods: int = 1) -> "Series":
4 -3.0
5 NaN
dtype: float64
+
+ Overflow in input dtype
+
+ >>> s = pd.Series([1, 0], dtype=np.uint8)
+ >>> s.diff()
+ 0 NaN
+ 1 255.0
+ dtype: float64"""
+ ),
+ )
+ def diff(self, periods: int = 1) -> "Series":
+ """
+ First discrete difference of element.
+
+ Calculates the difference of a {klass} element compared with another
+ element in the {klass} (default is element in previous row).
+
+ Parameters
+ ----------
+ periods : int, default 1
+ Periods to shift for calculating difference, accepts negative
+ values.
+ {extra_params}
+ Returns
+ -------
+ {klass}
+ First differences of the Series.
+
+ See Also
+ --------
+ {klass}.pct_change: Percent change over given number of periods.
+ {klass}.shift: Shift index by desired number of periods with an
+ optional time freq.
+ {other_klass}.diff: First discrete difference of object.
+
+ Notes
+ -----
+ For boolean dtypes, this uses :meth:`operator.xor` rather than
+ :meth:`operator.sub`.
+ The result is calculated according to current dtype in {klass},
+ however dtype of the result is always float64.
+
+ Examples
+ --------
+ {examples}
"""
result = algorithms.diff(self.array, periods)
return self._constructor(result, index=self.index).__finalize__(
| - [x] closes #28909
- [x] tests passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] note about dtype in `diff` in Dataframa and Series
| https://api.github.com/repos/pandas-dev/pandas/pulls/32699 | 2020-03-14T12:56:25Z | 2020-06-01T10:32:23Z | 2020-06-01T10:32:23Z | 2020-06-01T10:33:00Z |
DOC: Fix EX01 in pandas.DataFrame.idxmin | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index e153fdaac16e2..b0909e23b44c5 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8020,6 +8020,35 @@ def idxmin(self, axis=0, skipna=True) -> Series:
Notes
-----
This method is the DataFrame version of ``ndarray.argmin``.
+
+ Examples
+ --------
+ Consider a dataset containing food consumption in Argentina.
+
+ >>> df = pd.DataFrame({'consumption': [10.51, 103.11, 55.48],
+ ... 'co2_emissions': [37.2, 19.66, 1712]},
+ ... index=['Pork', 'Wheat Products', 'Beef'])
+
+ >>> df
+ consumption co2_emissions
+ Pork 10.51 37.20
+ Wheat Products 103.11 19.66
+ Beef 55.48 1712.00
+
+ By default, it returns the index for the minimum value in each column.
+
+ >>> df.idxmin()
+ consumption Pork
+ co2_emissions Wheat Products
+ dtype: object
+
+ To return the index for the minimum value in each row, use ``axis="columns"``.
+
+ >>> df.idxmin(axis="columns")
+ Pork consumption
+ Wheat Products co2_emissions
+ Beef consumption
+ dtype: object
"""
axis = self._get_axis_number(axis)
indices = nanops.nanargmin(self.values, axis=axis, skipna=skipna)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Related to #27977.
```
################################################################################
################################## Validation ##################################
################################################################################ | https://api.github.com/repos/pandas-dev/pandas/pulls/32697 | 2020-03-14T05:30:19Z | 2020-03-14T16:50:22Z | 2020-03-14T16:50:22Z | 2020-03-14T17:36:07Z |
CLN: remove unused int_block | diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index a569726e9a22a..0bbea671bae19 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -207,7 +207,6 @@ def setup_method(self, method):
self.cblock = create_block("complex", [7])
self.oblock = create_block("object", [1, 3])
self.bool_block = create_block("bool", [5])
- self.int_block = create_block("int", [6])
def test_constructor(self):
int32block = create_block("i4", [0])
| https://api.github.com/repos/pandas-dev/pandas/pulls/32695 | 2020-03-14T01:53:08Z | 2020-03-14T02:55:31Z | 2020-03-14T02:55:31Z | 2020-03-14T03:01:13Z | |
CLN: avoid _ndarray_values in reshape.merge | diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index aeec2a43f39bf..85386923e9912 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -1657,10 +1657,13 @@ def _get_merge_keys(self):
def _get_join_indexers(self):
""" return the join indexers """
- def flip(xs):
+ def flip(xs) -> np.ndarray:
""" unlike np.transpose, this returns an array of tuples """
xs = [
- x if not is_extension_array_dtype(x) else x._ndarray_values for x in xs
+ x
+ if not is_extension_array_dtype(x)
+ else extract_array(x)._values_for_argsort()
+ for x in xs
]
labels = list(string.ascii_lowercase[: len(xs)])
dtypes = [x.dtype for x in xs]
| https://api.github.com/repos/pandas-dev/pandas/pulls/32693 | 2020-03-13T23:33:43Z | 2020-03-14T02:58:00Z | 2020-03-14T02:58:00Z | 2020-03-14T16:47:23Z | |
CLN: remove unused kwargs from BlockManager.downcast | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 6d4ee6222933c..ea1f394aacd5f 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -403,7 +403,9 @@ def _split_op_result(self, result) -> List["Block"]:
return [result]
- def fillna(self, value, limit=None, inplace: bool = False, downcast=None):
+ def fillna(
+ self, value, limit=None, inplace: bool = False, downcast=None
+ ) -> List["Block"]:
"""
fillna on the block with the value. If we fail, then convert to
ObjectBlock and try again
@@ -417,9 +419,9 @@ def fillna(self, value, limit=None, inplace: bool = False, downcast=None):
if not self._can_hold_na:
if inplace:
- return self
+ return [self]
else:
- return self.copy()
+ return [self.copy()]
if self._can_hold_element(value):
# equivalent: _try_coerce_args(value) would not raise
@@ -428,7 +430,7 @@ def fillna(self, value, limit=None, inplace: bool = False, downcast=None):
# we can't process the value, but nothing to do
if not mask.any():
- return self if inplace else self.copy()
+ return [self] if inplace else [self.copy()]
# operate column-by-column
def f(mask, val, idx):
@@ -442,7 +444,7 @@ def f(mask, val, idx):
return self.split_and_operate(None, f, inplace)
- def split_and_operate(self, mask, f, inplace: bool):
+ def split_and_operate(self, mask, f, inplace: bool) -> List["Block"]:
"""
split the block per-column, and apply the callable f
per-column, return a new block for each. Handle
@@ -1191,7 +1193,7 @@ def _interpolate_with_fill(
fill_value=None,
coerce=False,
downcast=None,
- ):
+ ) -> List["Block"]:
""" fillna but using the interpolate machinery """
inplace = validate_bool_kwarg(inplace, "inplace")
@@ -1233,7 +1235,7 @@ def _interpolate(
inplace=False,
downcast=None,
**kwargs,
- ):
+ ) -> List["Block"]:
""" interpolate using scipy wrappers """
inplace = validate_bool_kwarg(inplace, "inplace")
data = self.values if inplace else self.values.copy()
@@ -1241,7 +1243,7 @@ def _interpolate(
# only deal with floats
if not self.is_float:
if not self.is_integer:
- return self
+ return [self]
data = data.astype(np.float64)
if fill_value is None:
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 0bba8de6682ea..2a239746daac7 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -565,8 +565,8 @@ def isna(self, func) -> "BlockManager":
def where(self, **kwargs) -> "BlockManager":
return self.apply("where", **kwargs)
- def setitem(self, **kwargs) -> "BlockManager":
- return self.apply("setitem", **kwargs)
+ def setitem(self, indexer, value) -> "BlockManager":
+ return self.apply("setitem", indexer=indexer, value=value)
def putmask(self, **kwargs):
return self.apply("putmask", **kwargs)
@@ -583,16 +583,30 @@ def shift(self, **kwargs) -> "BlockManager":
def fillna(self, **kwargs) -> "BlockManager":
return self.apply("fillna", **kwargs)
- def downcast(self, **kwargs) -> "BlockManager":
- return self.apply("downcast", **kwargs)
+ def downcast(self) -> "BlockManager":
+ return self.apply("downcast")
def astype(
self, dtype, copy: bool = False, errors: str = "raise"
) -> "BlockManager":
return self.apply("astype", dtype=dtype, copy=copy, errors=errors)
- def convert(self, **kwargs) -> "BlockManager":
- return self.apply("convert", **kwargs)
+ def convert(
+ self,
+ copy: bool = True,
+ datetime: bool = True,
+ numeric: bool = True,
+ timedelta: bool = True,
+ coerce: bool = False,
+ ) -> "BlockManager":
+ return self.apply(
+ "convert",
+ copy=copy,
+ datetime=datetime,
+ numeric=numeric,
+ timedelta=timedelta,
+ coerce=coerce,
+ )
def replace(self, value, **kwargs) -> "BlockManager":
assert np.ndim(value) == 0, value
diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py
index 1b6cb8447c76d..9c759ff1414fe 100644
--- a/pandas/tests/generic/test_generic.py
+++ b/pandas/tests/generic/test_generic.py
@@ -159,27 +159,14 @@ def test_downcast(self):
o = self._construct(shape=4, value=9, dtype=np.int64)
result = o.copy()
- result._data = o._data.downcast(dtypes="infer")
+ result._data = o._data.downcast()
self._compare(result, o)
- o = self._construct(shape=4, value=9.0)
- expected = o.astype(np.int64)
- result = o.copy()
- result._data = o._data.downcast(dtypes="infer")
- self._compare(result, expected)
-
o = self._construct(shape=4, value=9.5)
result = o.copy()
- result._data = o._data.downcast(dtypes="infer")
+ result._data = o._data.downcast()
self._compare(result, o)
- # are close
- o = self._construct(shape=4, value=9.000000000005)
- result = o.copy()
- result._data = o._data.downcast(dtypes="infer")
- expected = o.astype(np.int64)
- self._compare(result, expected)
-
def test_constructor_compound_dtypes(self):
# see gh-5191
# Compound dtypes should raise NotImplementedError.
| add some annotations | https://api.github.com/repos/pandas-dev/pandas/pulls/32691 | 2020-03-13T21:28:42Z | 2020-03-14T03:06:14Z | 2020-03-14T03:06:14Z | 2020-03-14T03:12:53Z |
DOC: filter method example is more clear | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 6f743d7388574..f6853a1bbb748 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -4558,6 +4558,10 @@ def filter(
>>> df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6])),
... index=['mouse', 'rabbit'],
... columns=['one', 'two', 'three'])
+ >>> df
+ one two three
+ mouse 1 2 3
+ rabbit 4 5 6
>>> # select columns by name
>>> df.filter(items=['one', 'three'])
| Added the print of the original example DataFrame. I was struggling to understand the example without looking at the starting point of it. I took the chance to do my first contribution to the project. Hopefully it is only the beginning!
| https://api.github.com/repos/pandas-dev/pandas/pulls/32690 | 2020-03-13T19:59:42Z | 2020-03-13T22:03:30Z | 2020-03-13T22:03:30Z | 2020-03-14T14:28:05Z |
TST: Parametrize in pandas/tests/internals/test_internals.py | diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index 1a7d5839d9a11..deffeb0a1800c 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -333,13 +333,9 @@ def test_pickle(self, mgr):
assert not mgr2._is_consolidated
assert not mgr2._known_consolidated
- def test_non_unique_pickle(self):
-
- mgr = create_mgr("a,a,a:f8")
- mgr2 = tm.round_trip_pickle(mgr)
- tm.assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))
-
- mgr = create_mgr("a: f8; a: i8")
+ @pytest.mark.parametrize("mgr_string", ["a,a,a:f8", "a: f8; a: i8"])
+ def test_non_unique_pickle(self, mgr_string):
+ mgr = create_mgr(mgr_string)
mgr2 = tm.round_trip_pickle(mgr)
tm.assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))
@@ -427,22 +423,25 @@ def test_sparse_mixed(self):
# TODO: what to test here?
- def test_as_array_float(self):
- mgr = create_mgr("c: f4; d: f2; e: f8")
- assert mgr.as_array().dtype == np.float64
-
- mgr = create_mgr("c: f4; d: f2")
- assert mgr.as_array().dtype == np.float32
-
- def test_as_array_int_bool(self):
- mgr = create_mgr("a: bool-1; b: bool-2")
- assert mgr.as_array().dtype == np.bool_
-
- mgr = create_mgr("a: i8-1; b: i8-2; c: i4; d: i2; e: u1")
- assert mgr.as_array().dtype == np.int64
+ @pytest.mark.parametrize(
+ "mgr_string, dtype",
+ [("c: f4; d: f2", np.float32), ("c: f4; d: f2; e: f8", np.float64)],
+ )
+ def test_as_array_float(self, mgr_string, dtype):
+ mgr = create_mgr(mgr_string)
+ assert mgr.as_array().dtype == dtype
- mgr = create_mgr("c: i4; d: i2; e: u1")
- assert mgr.as_array().dtype == np.int32
+ @pytest.mark.parametrize(
+ "mgr_string, dtype",
+ [
+ ("a: bool-1; b: bool-2", np.bool_),
+ ("a: i8-1; b: i8-2; c: i4; d: i2; e: u1", np.int64),
+ ("c: i4; d: i2; e: u1", np.int32),
+ ],
+ )
+ def test_as_array_int_bool(self, mgr_string, dtype):
+ mgr = create_mgr(mgr_string)
+ assert mgr.as_array().dtype == dtype
def test_as_array_datetime(self):
mgr = create_mgr("h: datetime-1; g: datetime-2")
@@ -548,7 +547,6 @@ def test_invalid_ea_block(self):
create_mgr("a: category2; b: category2")
def test_interleave(self):
-
# self
for dtype in ["f8", "i8", "object", "bool", "complex", "M8[ns]", "m8[ns]"]:
mgr = create_mgr(f"a: {dtype}")
@@ -556,6 +554,30 @@ def test_interleave(self):
mgr = create_mgr(f"a: {dtype}; b: {dtype}")
assert mgr.as_array().dtype == dtype
+ @pytest.mark.parametrize(
+ "mgr_string, dtype",
+ [
+ ("a: category", "i8"),
+ ("a: category; b: category", "i8"),
+ ("a: category; b: category2", "object"),
+ ("a: category2", "object"),
+ ("a: category2; b: category2", "object"),
+ ("a: f8", "f8"),
+ ("a: f8; b: i8", "f8"),
+ ("a: f4; b: i8", "f8"),
+ ("a: f4; b: i8; d: object", "object"),
+ ("a: bool; b: i8", "object"),
+ ("a: complex", "complex"),
+ ("a: f8; b: category", "object"),
+ ("a: M8[ns]; b: category", "object"),
+ ("a: M8[ns]; b: bool", "object"),
+ ("a: M8[ns]; b: i8", "object"),
+ ("a: m8[ns]; b: bool", "object"),
+ ("a: m8[ns]; b: i8", "object"),
+ ("a: M8[ns]; b: m8[ns]", "object"),
+ ],
+ )
+ def test_interleave_dtype(self, mgr_string, dtype):
# will be converted according the actual dtype of the underlying
mgr = create_mgr("a: category")
assert mgr.as_array().dtype == "i8"
@@ -689,13 +711,12 @@ def test_get_bool_data(self):
def test_unicode_repr_doesnt_raise(self):
repr(create_mgr("b,\u05d0: object"))
- def test_equals(self):
+ @pytest.mark.parametrize(
+ "mgr_string", ["a,b,c: i8-1; d,e,f: i8-2", "a,a,a: i8-1; b,b,b: i8-2"]
+ )
+ def test_equals(self, mgr_string):
# unique items
- bm1 = create_mgr("a,b,c: i8-1; d,e,f: i8-2")
- bm2 = BlockManager(bm1.blocks[::-1], bm1.axes)
- assert bm1.equals(bm2)
-
- bm1 = create_mgr("a,a,a: i8-1; b,b,b: i8-2")
+ bm1 = create_mgr(mgr_string)
bm2 = BlockManager(bm1.blocks[::-1], bm1.axes)
assert bm1.equals(bm2)
@@ -905,97 +926,111 @@ def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value):
class TestBlockPlacement:
- def test_slice_len(self):
- assert len(BlockPlacement(slice(0, 4))) == 4
- assert len(BlockPlacement(slice(0, 4, 2))) == 2
- assert len(BlockPlacement(slice(0, 3, 2))) == 2
-
- assert len(BlockPlacement(slice(0, 1, 2))) == 1
- assert len(BlockPlacement(slice(1, 0, -1))) == 1
+ @pytest.mark.parametrize(
+ "slc, expected",
+ [
+ (slice(0, 4), 4),
+ (slice(0, 4, 2), 2),
+ (slice(0, 3, 2), 2),
+ (slice(0, 1, 2), 1),
+ (slice(1, 0, -1), 1),
+ ],
+ )
+ def test_slice_len(self, slc, expected):
+ assert len(BlockPlacement(slc)) == expected
- def test_zero_step_raises(self):
+ @pytest.mark.parametrize("slc", [slice(1, 1, 0), slice(1, 2, 0)])
+ def test_zero_step_raises(self, slc):
msg = "slice step cannot be zero"
-
with pytest.raises(ValueError, match=msg):
- BlockPlacement(slice(1, 1, 0))
+ BlockPlacement(slc)
+
+ @pytest.mark.parametrize(
+ "slc",
+ [
+ slice(None, None),
+ slice(10, None),
+ slice(None, None, -1),
+ slice(None, 10, -1),
+ # These are "unbounded" because negative index will
+ # change depending on container shape.
+ slice(-1, None),
+ slice(None, -1),
+ slice(-1, -1),
+ slice(-1, None, -1),
+ slice(None, -1, -1),
+ slice(-1, -1, -1),
+ ],
+ )
+ def test_unbounded_slice_raises(self, slc):
+ msg = "unbounded slice"
with pytest.raises(ValueError, match=msg):
- BlockPlacement(slice(1, 2, 0))
-
- def test_unbounded_slice_raises(self):
- def assert_unbounded_slice_error(slc):
- with pytest.raises(ValueError, match="unbounded slice"):
- BlockPlacement(slc)
-
- assert_unbounded_slice_error(slice(None, None))
- assert_unbounded_slice_error(slice(10, None))
- assert_unbounded_slice_error(slice(None, None, -1))
- assert_unbounded_slice_error(slice(None, 10, -1))
-
- # These are "unbounded" because negative index will change depending on
- # container shape.
- assert_unbounded_slice_error(slice(-1, None))
- assert_unbounded_slice_error(slice(None, -1))
- assert_unbounded_slice_error(slice(-1, -1))
- assert_unbounded_slice_error(slice(-1, None, -1))
- assert_unbounded_slice_error(slice(None, -1, -1))
- assert_unbounded_slice_error(slice(-1, -1, -1))
-
- def test_not_slice_like_slices(self):
- def assert_not_slice_like(slc):
- assert not BlockPlacement(slc).is_slice_like
-
- assert_not_slice_like(slice(0, 0))
- assert_not_slice_like(slice(100, 0))
-
- assert_not_slice_like(slice(100, 100, -1))
- assert_not_slice_like(slice(0, 100, -1))
-
- assert not BlockPlacement(slice(0, 0)).is_slice_like
- assert not BlockPlacement(slice(100, 100)).is_slice_like
-
- def test_array_to_slice_conversion(self):
- def assert_as_slice_equals(arr, slc):
- assert BlockPlacement(arr).as_slice == slc
-
- assert_as_slice_equals([0], slice(0, 1, 1))
- assert_as_slice_equals([100], slice(100, 101, 1))
-
- assert_as_slice_equals([0, 1, 2], slice(0, 3, 1))
- assert_as_slice_equals([0, 5, 10], slice(0, 15, 5))
- assert_as_slice_equals([0, 100], slice(0, 200, 100))
-
- assert_as_slice_equals([2, 1], slice(2, 0, -1))
-
- def test_not_slice_like_arrays(self):
- def assert_not_slice_like(arr):
- assert not BlockPlacement(arr).is_slice_like
-
- assert_not_slice_like([])
- assert_not_slice_like([-1])
- assert_not_slice_like([-1, -2, -3])
- assert_not_slice_like([-10])
- assert_not_slice_like([-1])
- assert_not_slice_like([-1, 0, 1, 2])
- assert_not_slice_like([-2, 0, 2, 4])
- assert_not_slice_like([1, 0, -1])
- assert_not_slice_like([1, 1, 1])
-
- def test_slice_iter(self):
- assert list(BlockPlacement(slice(0, 3))) == [0, 1, 2]
- assert list(BlockPlacement(slice(0, 0))) == []
- assert list(BlockPlacement(slice(3, 0))) == []
-
- def test_slice_to_array_conversion(self):
- def assert_as_array_equals(slc, asarray):
- tm.assert_numpy_array_equal(
- BlockPlacement(slc).as_array, np.asarray(asarray, dtype=np.int64)
- )
+ BlockPlacement(slc)
- assert_as_array_equals(slice(0, 3), [0, 1, 2])
- assert_as_array_equals(slice(0, 0), [])
- assert_as_array_equals(slice(3, 0), [])
+ @pytest.mark.parametrize(
+ "slc",
+ [
+ slice(0, 0),
+ slice(100, 0),
+ slice(100, 100),
+ slice(100, 100, -1),
+ slice(0, 100, -1),
+ ],
+ )
+ def test_not_slice_like_slices(self, slc):
+ assert not BlockPlacement(slc).is_slice_like
+
+ @pytest.mark.parametrize(
+ "arr, slc",
+ [
+ ([0], slice(0, 1, 1)),
+ ([100], slice(100, 101, 1)),
+ ([0, 1, 2], slice(0, 3, 1)),
+ ([0, 5, 10], slice(0, 15, 5)),
+ ([0, 100], slice(0, 200, 100)),
+ ([2, 1], slice(2, 0, -1)),
+ ],
+ )
+ def test_array_to_slice_conversion(self, arr, slc):
+ assert BlockPlacement(arr).as_slice == slc
- assert_as_array_equals(slice(3, 0, -1), [3, 2, 1])
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ [],
+ [-1],
+ [-1, -2, -3],
+ [-10],
+ [-1],
+ [-1, 0, 1, 2],
+ [-2, 0, 2, 4],
+ [1, 0, -1],
+ [1, 1, 1],
+ ],
+ )
+ def test_not_slice_like_arrays(self, arr):
+ assert not BlockPlacement(arr).is_slice_like
+
+ @pytest.mark.parametrize(
+ "slc, expected",
+ [(slice(0, 3), [0, 1, 2]), (slice(0, 0), []), (slice(3, 0), [])],
+ )
+ def test_slice_iter(self, slc, expected):
+ assert list(BlockPlacement(slc)) == expected
+
+ @pytest.mark.parametrize(
+ "slc, arr",
+ [
+ (slice(0, 3), [0, 1, 2]),
+ (slice(0, 0), []),
+ (slice(3, 0), []),
+ (slice(3, 0, -1), [3, 2, 1]),
+ ],
+ )
+ def test_slice_to_array_conversion(self, slc, arr):
+ tm.assert_numpy_array_equal(
+ BlockPlacement(slc).as_array, np.asarray(arr, dtype=np.int64)
+ )
def test_blockplacement_add(self):
bpl = BlockPlacement(slice(0, 5))
@@ -1003,30 +1038,30 @@ def test_blockplacement_add(self):
assert bpl.add(np.arange(5)).as_slice == slice(0, 10, 2)
assert list(bpl.add(np.arange(5, 0, -1))) == [5, 5, 5, 5, 5]
- def test_blockplacement_add_int(self):
- def assert_add_equals(val, inc, result):
- assert list(BlockPlacement(val).add(inc)) == result
-
- assert_add_equals(slice(0, 0), 0, [])
- assert_add_equals(slice(1, 4), 0, [1, 2, 3])
- assert_add_equals(slice(3, 0, -1), 0, [3, 2, 1])
- assert_add_equals([1, 2, 4], 0, [1, 2, 4])
-
- assert_add_equals(slice(0, 0), 10, [])
- assert_add_equals(slice(1, 4), 10, [11, 12, 13])
- assert_add_equals(slice(3, 0, -1), 10, [13, 12, 11])
- assert_add_equals([1, 2, 4], 10, [11, 12, 14])
-
- assert_add_equals(slice(0, 0), -1, [])
- assert_add_equals(slice(1, 4), -1, [0, 1, 2])
- assert_add_equals([1, 2, 4], -1, [0, 1, 3])
+ @pytest.mark.parametrize(
+ "val, inc, expected",
+ [
+ (slice(0, 0), 0, []),
+ (slice(1, 4), 0, [1, 2, 3]),
+ (slice(3, 0, -1), 0, [3, 2, 1]),
+ ([1, 2, 4], 0, [1, 2, 4]),
+ (slice(0, 0), 10, []),
+ (slice(1, 4), 10, [11, 12, 13]),
+ (slice(3, 0, -1), 10, [13, 12, 11]),
+ ([1, 2, 4], 10, [11, 12, 14]),
+ (slice(0, 0), -1, []),
+ (slice(1, 4), -1, [0, 1, 2]),
+ ([1, 2, 4], -1, [0, 1, 3]),
+ ],
+ )
+ def test_blockplacement_add_int(self, val, inc, expected):
+ assert list(BlockPlacement(val).add(inc)) == expected
+ @pytest.mark.parametrize("val", [slice(1, 4), [1, 2, 4]])
+ def test_blockplacement_add_int_raises(self, val):
msg = "iadd causes length change"
-
- with pytest.raises(ValueError, match=msg):
- BlockPlacement(slice(1, 4)).add(-10)
with pytest.raises(ValueError, match=msg):
- BlockPlacement([1, 2, 4]).add(-10)
+ BlockPlacement(val).add(-10)
class DummyElement:
| - [ ] 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/32687 | 2020-03-13T19:27:07Z | 2020-03-19T17:40:37Z | 2020-03-19T17:40:37Z | 2020-03-19T17:54:09Z |
BUG: Series.__getitem__ with downstream scalars | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 0d3a9a8f969a4..441c6cee32b2a 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -303,6 +303,7 @@ Indexing
- Bug in :meth:`Series.loc` and :meth:`DataFrame.loc` when indexing with an integer key on a object-dtype :class:`Index` that is not all-integers (:issue:`31905`)
- Bug in :meth:`DataFrame.iloc.__setitem__` on a :class:`DataFrame` with duplicate columns incorrectly setting values for all matching columns (:issue:`15686`, :issue:`22036`)
- Bug in :meth:`DataFrame.loc:` and :meth:`Series.loc` with a :class:`DatetimeIndex`, :class:`TimedeltaIndex`, or :class:`PeriodIndex` incorrectly allowing lookups of non-matching datetime-like dtypes (:issue:`32650`)
+- Bug in :meth:`Series.__getitem__` indexing with non-standard scalars, e.g. ``np.dtype`` (:issue:`32684`)
Missing
^^^^^^^
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 8a6839b4fb181..21477cce48e63 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -926,6 +926,10 @@ def _get_with(self, key):
elif isinstance(key, tuple):
return self._get_values_tuple(key)
+ elif not is_list_like(key):
+ # e.g. scalars that aren't recognized by lib.is_scalar, GH#32684
+ return self.loc[key]
+
if not isinstance(key, (list, np.ndarray, ExtensionArray, Series, Index)):
key = list(key)
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index e0fef833d4ced..ab9916eea8e5a 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -1437,6 +1437,7 @@ def test_is_scalar_pandas_scalars(self):
assert is_scalar(Period("2014-01-01"))
assert is_scalar(Interval(left=0, right=1))
assert is_scalar(DateOffset(days=1))
+ assert is_scalar(pd.offsets.Minute(3))
def test_is_scalar_pandas_containers(self):
assert not is_scalar(Series(dtype=object))
@@ -1445,6 +1446,11 @@ def test_is_scalar_pandas_containers(self):
assert not is_scalar(DataFrame([[1]]))
assert not is_scalar(Index([]))
assert not is_scalar(Index([1]))
+ assert not is_scalar(Categorical([]))
+ assert not is_scalar(DatetimeIndex([])._data)
+ assert not is_scalar(TimedeltaIndex([])._data)
+ assert not is_scalar(DatetimeIndex([])._data.to_period("D"))
+ assert not is_scalar(pd.array([1, 2, 3]))
def test_is_scalar_number(self):
# Number() is not recognied by PyNumber_Check, so by extension
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index 18fcbea683dd3..5b3786e1a0d3c 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -923,3 +923,15 @@ def test_getitem_2d_no_warning():
series = pd.Series([1, 2, 3], index=[1, 2, 3])
with tm.assert_produces_warning(None):
series[:, None]
+
+
+def test_getitem_unrecognized_scalar():
+ # GH#32684 a scalar key that is not recognized by lib.is_scalar
+
+ # a series that might be produced via `frame.dtypes`
+ ser = pd.Series([1, 2], index=[np.dtype("O"), np.dtype("i8")])
+
+ key = ser.index[1]
+
+ result = ser[key]
+ assert result == 2
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
cc @spencerclark I think this fixes a subset of the issues reported in https://github.com/pydata/xarray/issues/3751, can you confirm?
@jorisvandenbossche IIRC geopandas scalars not being recognized by lib.is_scalar has caused some issues there; does this address any of those? | https://api.github.com/repos/pandas-dev/pandas/pulls/32684 | 2020-03-13T17:02:56Z | 2020-03-19T00:02:07Z | 2020-03-19T00:02:07Z | 2020-03-19T01:38:15Z |
PERF: Using Numpy C-API arange | diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx
index 437406cbbd819..7f861e587e637 100644
--- a/pandas/_libs/internals.pyx
+++ b/pandas/_libs/internals.pyx
@@ -7,7 +7,9 @@ cdef extern from "Python.h":
Py_ssize_t PY_SSIZE_T_MAX
import numpy as np
-from numpy cimport int64_t
+cimport numpy as cnp
+from numpy cimport NPY_INT64, int64_t
+cnp.import_array()
from pandas._libs.algos import ensure_int64
@@ -105,7 +107,9 @@ cdef class BlockPlacement:
Py_ssize_t start, stop, end, _
if not self._has_array:
start, stop, step, _ = slice_get_indices_ex(self._as_slice)
- self._as_array = np.arange(start, stop, step, dtype=np.int64)
+ # NOTE: this is the C-optimized equivalent of
+ # np.arange(start, stop, step, dtype=np.int64)
+ self._as_array = cnp.PyArray_Arange(start, stop, step, NPY_INT64)
self._has_array = True
return self._as_array
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
---
This PR was opened as @jbrockmendel suggested (ref https://github.com/pandas-dev/pandas/pull/32177#discussion_r382923663)
---
### Benchmarks:
#### Master:
```
In [1]: import pandas._libs.internals as internals
In [2]: %timeit internals.BlockPlacement(slice(1_000_000)).as_array
1.55 ms ± 143 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
```
---
#### PR:
```
In [1]: import pandas._libs.internals as internals
In [2]: %timeit internals.BlockPlacement(slice(1_000_000)).as_array
1.46 ms ± 3.55 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/32681 | 2020-03-13T14:39:29Z | 2020-03-14T15:54:56Z | 2020-03-14T15:54:56Z | 2020-03-18T12:47:08Z |
Fix wrong docstring in qcut | diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py
index 86417faf6cd11..b9eb89b4d14c6 100644
--- a/pandas/core/reshape/tile.py
+++ b/pandas/core/reshape/tile.py
@@ -286,7 +286,7 @@ def qcut(
Parameters
----------
x : 1d ndarray or Series
- q : int or list-like of int
+ q : int or list-like of float
Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately
array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles.
labels : array or False, default None
| - [ ] 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/32679 | 2020-03-13T13:38:18Z | 2020-03-13T22:20:27Z | 2020-03-13T22:20:27Z | 2020-03-13T22:20:32Z |
CLN: Remove PY2 compat code | diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index 359e5b956f8a5..145cf43112be3 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -985,12 +985,7 @@ def get_empty_frame(data) -> DataFrame:
if prefix is None:
dummy_cols = levels
else:
-
- # PY2 embedded unicode, gh-22084
- def _make_col_name(prefix, prefix_sep, level) -> str:
- return f"{prefix}{prefix_sep}{level}"
-
- dummy_cols = [_make_col_name(prefix, prefix_sep, level) for level in levels]
+ dummy_cols = [f"{prefix}{prefix_sep}{level}" for level in levels]
index: Optional[Index]
if isinstance(data, Series):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
---
Benchmarks:
#### Master:
```
In [1]: import pandas as pd
In [2]: s = pd.Series(list("ABCA"))
In [3]: %timeit pd.get_dummies(s)
482 µs ± 752 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
```
---
#### PR:
```
In [1]: import pandas as pd
In [2]: s = pd.Series(list("ABCA"))
In [3]: %timeit pd.get_dummies(s)
479 µs ± 2.43 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/32677 | 2020-03-13T11:00:16Z | 2020-03-13T12:14:14Z | 2020-03-13T12:14:14Z | 2020-03-14T14:07:29Z |
Avoid bare pytest.raises in dtypes/test_dtypes.py | diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index 181f0c8906853..d29102cbd4604 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -558,7 +558,7 @@ def validate_categories(categories, fastpath: bool = False):
if not fastpath:
if categories.hasnans:
- raise ValueError("Categorial categories cannot be null")
+ raise ValueError("Categorical categories cannot be null")
if not categories.is_unique:
raise ValueError("Categorical categories must be unique")
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py
index c6b4c4904735c..3e31c1acbe09d 100644
--- a/pandas/tests/arrays/categorical/test_constructors.py
+++ b/pandas/tests/arrays/categorical/test_constructors.py
@@ -252,7 +252,7 @@ def test_constructor_not_sequence(self):
def test_constructor_with_null(self):
# Cannot have NaN in categories
- msg = "Categorial categories cannot be null"
+ msg = "Categorical categories cannot be null"
with pytest.raises(ValueError, match=msg):
Categorical([np.nan, "a", "b", "c"], categories=[np.nan, "a", "b", "c"])
@@ -500,7 +500,7 @@ def test_from_codes_non_unique_categories(self):
Categorical.from_codes([0, 1, 2], categories=["a", "a", "b"])
def test_from_codes_nan_cat_included(self):
- with pytest.raises(ValueError, match="Categorial categories cannot be null"):
+ with pytest.raises(ValueError, match="Categorical categories cannot be null"):
Categorical.from_codes([0, 1, 2], categories=["a", "b", np.nan])
def test_from_codes_too_negative(self):
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index 55b1ac819049d..16ee7c27780ca 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -361,7 +361,7 @@ def test_hash_vs_equality(self, dtype):
assert hash(dtype) == hash(dtype3)
def test_construction(self):
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="Invalid frequency: xx"):
PeriodDtype("xx")
for s in ["period[D]", "Period[D]", "D"]:
@@ -414,21 +414,25 @@ def test_construction_from_string(self, dtype):
assert is_dtype_equal(dtype, result)
result = PeriodDtype.construct_from_string("period[D]")
assert is_dtype_equal(dtype, result)
- with pytest.raises(TypeError):
- PeriodDtype.construct_from_string("foo")
- with pytest.raises(TypeError):
- PeriodDtype.construct_from_string("period[foo]")
- with pytest.raises(TypeError):
- PeriodDtype.construct_from_string("foo[D]")
-
- with pytest.raises(TypeError):
- PeriodDtype.construct_from_string("datetime64[ns]")
- with pytest.raises(TypeError):
- PeriodDtype.construct_from_string("datetime64[ns, US/Eastern]")
with pytest.raises(TypeError, match="list"):
PeriodDtype.construct_from_string([1, 2, 3])
+ @pytest.mark.parametrize(
+ "string",
+ [
+ "foo",
+ "period[foo]",
+ "foo[D]",
+ "datetime64[ns]",
+ "datetime64[ns, US/Eastern]",
+ ],
+ )
+ def test_construct_dtype_from_string_invalid_raises(self, string):
+ msg = f"Cannot construct a 'PeriodDtype' from '{string}'"
+ with pytest.raises(TypeError, match=re.escape(msg)):
+ PeriodDtype.construct_from_string(string)
+
def test_is_dtype(self, dtype):
assert PeriodDtype.is_dtype(dtype)
assert PeriodDtype.is_dtype("period[D]")
@@ -475,7 +479,9 @@ def test_basic(self, dtype):
def test_empty(self):
dt = PeriodDtype()
- with pytest.raises(AttributeError):
+ # https://github.com/pandas-dev/pandas/issues/27388
+ msg = "object has no attribute 'freqstr'"
+ with pytest.raises(AttributeError, match=msg):
str(dt)
def test_not_string(self):
@@ -764,11 +770,13 @@ def test_order_hashes_different(self, v1, v2):
assert c1 is not c3
def test_nan_invalid(self):
- with pytest.raises(ValueError):
+ msg = "Categorical categories cannot be null"
+ with pytest.raises(ValueError, match=msg):
CategoricalDtype([1, 2, np.nan])
def test_non_unique_invalid(self):
- with pytest.raises(ValueError):
+ msg = "Categorical categories must be unique"
+ with pytest.raises(ValueError, match=msg):
CategoricalDtype([1, 2, 1])
def test_same_categories_different_order(self):
| * [x] ref #30999
* [x] tests added / passed
* [x] passes `black pandas`
* [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` | https://api.github.com/repos/pandas-dev/pandas/pulls/32672 | 2020-03-13T02:10:55Z | 2020-03-18T09:12:01Z | 2020-03-18T09:12:01Z | 2020-03-21T00:41:31Z |
REF: put all post-processing at end of DataFrame._reduce | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 5e8db3acc7ff3..e153fdaac16e2 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -7808,6 +7808,8 @@ def _reduce(
self, op, name, axis=0, skipna=True, numeric_only=None, filter_type=None, **kwds
):
+ assert filter_type is None or filter_type == "bool", filter_type
+
dtype_is_dt = self.dtypes.apply(
lambda x: is_datetime64_any_dtype(x) or is_period_dtype(x)
)
@@ -7835,7 +7837,7 @@ def f(x):
return op(x, axis=axis, skipna=skipna, **kwds)
def _get_data(axis_matters):
- if filter_type is None or filter_type == "numeric":
+ if filter_type is None:
data = self._get_numeric_data()
elif filter_type == "bool":
if axis_matters:
@@ -7882,15 +7884,11 @@ def blk_func(values):
return out
if numeric_only is None:
- values = self.values
+ data = self
+ values = data.values
try:
result = f(values)
- if filter_type == "bool" and is_object_dtype(values) and axis is None:
- # work around https://github.com/numpy/numpy/issues/10489
- # TODO: combine with hasattr(result, 'dtype') further down
- # hard since we don't have `values` down there.
- result = np.bool_(result)
except TypeError:
# e.g. in nanops trying to convert strs to float
@@ -7916,30 +7914,36 @@ def blk_func(values):
# TODO: why doesnt axis matter here?
data = _get_data(axis_matters=False)
- with np.errstate(all="ignore"):
- result = f(data.values)
labels = data._get_agg_axis(axis)
+
+ values = data.values
+ with np.errstate(all="ignore"):
+ result = f(values)
else:
if numeric_only:
data = _get_data(axis_matters=True)
+ labels = data._get_agg_axis(axis)
values = data.values
- labels = data._get_agg_axis(axis)
else:
- values = self.values
+ data = self
+ values = data.values
result = f(values)
- if hasattr(result, "dtype") and is_object_dtype(result.dtype):
+ if filter_type == "bool" and is_object_dtype(values) and axis is None:
+ # work around https://github.com/numpy/numpy/issues/10489
+ # TODO: can we de-duplicate parts of this with the next blocK?
+ result = np.bool_(result)
+ elif hasattr(result, "dtype") and is_object_dtype(result.dtype):
try:
- if filter_type is None or filter_type == "numeric":
+ if filter_type is None:
result = result.astype(np.float64)
elif filter_type == "bool" and notna(result).all():
result = result.astype(np.bool_)
except (ValueError, TypeError):
-
# try to coerce to the original dtypes item by item if we can
if axis == 0:
- result = coerce_to_dtypes(result, self.dtypes)
+ result = coerce_to_dtypes(result, data.dtypes)
if constructor is not None:
result = self._constructor_sliced(result, index=labels)
| there's some nasty try/except logic in DataFrame._reduce. This is simplifying the code _around_ that. | https://api.github.com/repos/pandas-dev/pandas/pulls/32671 | 2020-03-13T02:00:15Z | 2020-03-14T03:03:17Z | 2020-03-14T03:03:17Z | 2020-03-14T03:04:51Z |
TST: reintroduce check_series_type in assert_series_equal | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 11757e1bf14e0..0630823f0de35 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -396,6 +396,7 @@ Other
- Set operations on an object-dtype :class:`Index` now always return object-dtype results (:issue:`31401`)
- Bug in :meth:`AbstractHolidayCalendar.holidays` when no rules were defined (:issue:`31415`)
- Bug in :meth:`DataFrame.to_records` incorrectly losing timezone information in timezone-aware ``datetime64`` columns (:issue:`32535`)
+- Fixed :func:`pandas.testing.assert_series_equal` to correctly raise if left object is a different subclass with ``check_series_type=True`` (:issue:`32670`).
- :meth:`IntegerArray.astype` now supports ``datetime64`` dtype (:issue:32538`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/_testing.py b/pandas/_testing.py
index dff15c66750ac..d473b453d77d2 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -1050,6 +1050,7 @@ def assert_series_equal(
right,
check_dtype=True,
check_index_type="equiv",
+ check_series_type=True,
check_less_precise=False,
check_names=True,
check_exact=False,
@@ -1070,6 +1071,8 @@ def assert_series_equal(
check_index_type : bool or {'equiv'}, default 'equiv'
Whether to check the Index class, dtype and inferred_type
are identical.
+ check_series_type : bool, default True
+ Whether to check the Series class is identical.
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
@@ -1101,10 +1104,8 @@ def assert_series_equal(
# instance validation
_check_isinstance(left, right, Series)
- # TODO: There are some tests using rhs is sparse
- # lhs is dense. Should use assert_class_equal in future
- assert isinstance(left, type(right))
- # assert_class_equal(left, right, obj=obj)
+ if check_series_type:
+ assert_class_equal(left, right, obj=obj)
# length comparison
if len(left) != len(right):
diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py
index a2e7dc527c4b8..16bf651829a04 100644
--- a/pandas/tests/frame/test_subclass.py
+++ b/pandas/tests/frame/test_subclass.py
@@ -163,12 +163,14 @@ def test_subclass_align_combinations(self):
# frame + series
res1, res2 = df.align(s, axis=0)
- exp1 = pd.DataFrame(
+ exp1 = tm.SubclassedDataFrame(
{"a": [1, np.nan, 3, np.nan, 5], "b": [1, np.nan, 3, np.nan, 5]},
index=list("ABCDE"),
)
# name is lost when
- exp2 = pd.Series([1, 2, np.nan, 4, np.nan], index=list("ABCDE"), name="x")
+ exp2 = tm.SubclassedSeries(
+ [1, 2, np.nan, 4, np.nan], index=list("ABCDE"), name="x"
+ )
assert isinstance(res1, tm.SubclassedDataFrame)
tm.assert_frame_equal(res1, exp1)
diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py
index eaf0824f52927..2550b32446055 100644
--- a/pandas/tests/util/test_assert_series_equal.py
+++ b/pandas/tests/util/test_assert_series_equal.py
@@ -194,3 +194,24 @@ def test_series_equal_categorical_mismatch(check_categorical):
tm.assert_series_equal(s1, s2, check_categorical=check_categorical)
else:
_assert_series_equal_both(s1, s2, check_categorical=check_categorical)
+
+
+def test_series_equal_series_type():
+ class MySeries(Series):
+ pass
+
+ s1 = Series([1, 2])
+ s2 = Series([1, 2])
+ s3 = MySeries([1, 2])
+
+ tm.assert_series_equal(s1, s2, check_series_type=False)
+ tm.assert_series_equal(s1, s2, check_series_type=True)
+
+ tm.assert_series_equal(s1, s3, check_series_type=False)
+ tm.assert_series_equal(s3, s1, check_series_type=False)
+
+ with pytest.raises(AssertionError, match="Series classes are different"):
+ tm.assert_series_equal(s1, s3, check_series_type=True)
+
+ with pytest.raises(AssertionError, match="Series classes are different"):
+ tm.assert_series_equal(s3, s1, check_series_type=True)
| - [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Re-introduced `check_series_type` in `assert_series_equal` which was recently removed in #32513. It was a part of public API which is not used internally, but it is used elsewhere (like geopandas). Discussion in #32513 suggests that it should be put back where it was. | https://api.github.com/repos/pandas-dev/pandas/pulls/32670 | 2020-03-12T22:52:49Z | 2020-03-16T22:43:07Z | 2020-03-16T22:43:07Z | 2020-03-16T22:43:08Z |
PERF: MultiIndex._shallow_copy | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 5b6f70be478c2..48eff0543ad4d 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -190,7 +190,7 @@ Performance improvements
- Performance improvement in flex arithmetic ops between :class:`DataFrame` and :class:`Series` with ``axis=0`` (:issue:`31296`)
- The internal index method :meth:`~Index._shallow_copy` now copies cached attributes over to the new index,
avoiding creating these again on the new index. This can speed up many operations that depend on creating copies of
- existing indexes (:issue:`28584`, :issue:`32640`)
+ existing indexes (:issue:`28584`, :issue:`32640`, :issue:`32669`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 0bb88145646ed..122097f4478d7 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -276,6 +276,7 @@ def __new__(
raise ValueError("Must pass non-zero number of levels/codes")
result = object.__new__(MultiIndex)
+ result._cache = {}
# we've already validated levels and codes, so shortcut here
result._set_levels(levels, copy=copy, validate=False)
@@ -991,7 +992,13 @@ def _shallow_copy(self, values=None, **kwargs):
# discards freq
kwargs.pop("freq", None)
return MultiIndex.from_tuples(values, names=names, **kwargs)
- return self.copy(**kwargs)
+
+ result = self.copy(**kwargs)
+ result._cache = self._cache.copy()
+ # GH32669
+ if "levels" in result._cache:
+ del result._cache["levels"]
+ return result
def _shallow_copy_with_infer(self, values, **kwargs):
# On equal MultiIndexes the difference is empty.
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 8ae792d3f63b5..f83234f1aac0b 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -251,11 +251,13 @@ def _has_complex_internals(self):
def _shallow_copy(self, values=None, name: Label = no_default):
name = name if name is not no_default else self.name
-
+ cache = self._cache.copy() if values is None else {}
if values is None:
values = self._data
- return self._simple_new(values, name=name)
+ result = self._simple_new(values, name=name)
+ result._cache = cache
+ return result
def _maybe_convert_timedelta(self, other):
"""
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index c21d8df2476b3..2c038564f4e6f 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -141,7 +141,7 @@ def _simple_new(cls, values: range, name: Label = None) -> "RangeIndex":
result._range = values
result.name = name
-
+ result._cache = {}
result._reset_identity()
return result
@@ -391,7 +391,9 @@ def _shallow_copy(self, values=None, name: Label = no_default):
name = self.name if name is no_default else name
if values is None:
- return self._simple_new(self._range, name=name)
+ result = self._simple_new(self._range, name=name)
+ result._cache = self._cache.copy()
+ return result
else:
return Int64Index._simple_new(values, name=name)
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index e5af0d9c03979..c13385c135e9f 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -919,3 +919,16 @@ def test_contains_requires_hashable_raises(self):
with pytest.raises(TypeError):
{} in idx._engine
+
+ def test_shallow_copy_copies_cache(self):
+ # GH32669
+ idx = self.create_index()
+ idx.get_loc(idx[0]) # populates the _cache.
+ shallow_copy = idx._shallow_copy()
+
+ # check that the shallow_copied cache is a copy of the original
+ assert idx._cache == shallow_copy._cache
+ assert idx._cache is not shallow_copy._cache
+ # cache values should reference the same object
+ for key, val in idx._cache.items():
+ assert shallow_copy._cache[key] is val, key
| - [x] xref #28584, #32568, #32640
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Improves performance of ``MultiIndex._shallow_copy``. Example:
```python
>>> n = 100_000
>>> df = pd.DataFrame({'a': range(n), 'b': range(1, n+1)})
>>> mi = pd.MultiIndex.from_frame(df)
>>> mi.is_lexsorted()
True
>>> mi.get_loc(mi[0]) # also sets up the cache
>>> %timeit mi._shallow_copy().get_loc(mi[0])
8.56 ms ± 127 µs per loop # master
75.1 µs ± 2.3 µs per loop # this PR, first commit
46.9 µs ± 792 ns per loop # this PR, second commit
```
Also adds tests for ``_shallow_copy`` for all index types. This ensures that this issue has been resolved for all index types. | https://api.github.com/repos/pandas-dev/pandas/pulls/32669 | 2020-03-12T22:48:47Z | 2020-03-14T16:29:24Z | 2020-03-14T16:29:24Z | 2020-03-29T17:48:22Z |
BUG: DatetimeArray._from_sequence accepting bool dtype | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 48eff0543ad4d..d2038f7dc7468 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -216,6 +216,7 @@ Datetimelike
- Bug in :class:`Timestamp` where constructing :class:`Timestamp` with dateutil timezone less than 128 nanoseconds before daylight saving time switch from winter to summer would result in nonexistent time (:issue:`31043`)
- Bug in :meth:`Period.to_timestamp`, :meth:`Period.start_time` with microsecond frequency returning a timestamp one nanosecond earlier than the correct time (:issue:`31475`)
- :class:`Timestamp` raising confusing error message when year, month or day is missing (:issue:`31200`)
+- Bug in :class:`DatetimeIndex` constructor incorrectly accepting ``bool``-dtyped inputs (:issue:`32668`)
Timedelta
^^^^^^^^^
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 7223eda22b3d9..2110f782330fb 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -23,6 +23,7 @@
from pandas.core.dtypes.common import (
_INT64_DTYPE,
_NS_DTYPE,
+ is_bool_dtype,
is_categorical_dtype,
is_datetime64_any_dtype,
is_datetime64_dtype,
@@ -1903,7 +1904,11 @@ def maybe_convert_dtype(data, copy):
------
TypeError : PeriodDType data is passed
"""
- if is_float_dtype(data):
+ if not hasattr(data, "dtype"):
+ # e.g. collections.deque
+ return data, copy
+
+ if is_float_dtype(data.dtype):
# Note: we must cast to datetime64[ns] here in order to treat these
# as wall-times instead of UTC timestamps.
data = data.astype(_NS_DTYPE)
@@ -1911,24 +1916,24 @@ def maybe_convert_dtype(data, copy):
# TODO: deprecate this behavior to instead treat symmetrically
# with integer dtypes. See discussion in GH#23675
- elif is_timedelta64_dtype(data):
+ elif is_timedelta64_dtype(data.dtype) or is_bool_dtype(data.dtype):
# GH#29794 enforcing deprecation introduced in GH#23539
raise TypeError(f"dtype {data.dtype} cannot be converted to datetime64[ns]")
- elif is_period_dtype(data):
+ elif is_period_dtype(data.dtype):
# Note: without explicitly raising here, PeriodIndex
# test_setops.test_join_does_not_recur fails
raise TypeError(
"Passing PeriodDtype data is invalid. Use `data.to_timestamp()` instead"
)
- elif is_categorical_dtype(data):
+ elif is_categorical_dtype(data.dtype):
# GH#18664 preserve tz in going DTI->Categorical->DTI
# TODO: cases where we need to do another pass through this func,
# e.g. the categories are timedelta64s
data = data.categories.take(data.codes, fill_value=NaT)._values
copy = False
- elif is_extension_array_dtype(data) and not is_datetime64tz_dtype(data):
+ elif is_extension_array_dtype(data.dtype) and not is_datetime64tz_dtype(data.dtype):
# Includes categorical
# TODO: We have no tests for these
data = np.array(data, dtype=np.object_)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 2d8eb9b29498a..e120695cc83e8 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2666,9 +2666,9 @@ def combine(self, other, func, fill_value=None) -> "Series":
new_values = [func(lv, other) for lv in self._values]
new_name = self.name
- if is_categorical_dtype(self.values):
+ if is_categorical_dtype(self.dtype):
pass
- elif is_extension_array_dtype(self.values):
+ elif is_extension_array_dtype(self.dtype):
# The function can return something of any type, so check
# if the type is compatible with the calling EA.
new_values = try_cast_to_ea(self._values, new_values)
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index c32b4d81c0988..8e38332e67439 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -359,7 +359,18 @@ def _convert_listlike_datetimes(
# warn if passing timedelta64, raise for PeriodDtype
# NB: this must come after unit transformation
orig_arg = arg
- arg, _ = maybe_convert_dtype(arg, copy=False)
+ try:
+ arg, _ = maybe_convert_dtype(arg, copy=False)
+ except TypeError:
+ if errors == "coerce":
+ result = np.array(["NaT"], dtype="datetime64[ns]").repeat(len(arg))
+ return DatetimeIndex(result, name=name)
+ elif errors == "ignore":
+ from pandas import Index
+
+ result = Index(arg, name=name)
+ return result
+ raise
arg = ensure_object(arg)
require_iso8601 = False
diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py
index 2c26e72a245f7..7d80ad3d8c6be 100644
--- a/pandas/tests/arrays/test_datetimes.py
+++ b/pandas/tests/arrays/test_datetimes.py
@@ -89,11 +89,26 @@ def test_non_array_raises(self):
with pytest.raises(ValueError, match="list"):
DatetimeArray([1, 2, 3])
- def test_other_type_raises(self):
+ def test_bool_dtype_raises(self):
+ arr = np.array([1, 2, 3], dtype="bool")
+
with pytest.raises(
ValueError, match="The dtype of 'values' is incorrect.*bool"
):
- DatetimeArray(np.array([1, 2, 3], dtype="bool"))
+ DatetimeArray(arr)
+
+ msg = r"dtype bool cannot be converted to datetime64\[ns\]"
+ with pytest.raises(TypeError, match=msg):
+ DatetimeArray._from_sequence(arr)
+
+ with pytest.raises(TypeError, match=msg):
+ sequence_to_dt64ns(arr)
+
+ with pytest.raises(TypeError, match=msg):
+ pd.DatetimeIndex(arr)
+
+ with pytest.raises(TypeError, match=msg):
+ pd.to_datetime(arr)
def test_incorrect_dtype_raises(self):
with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Identified when making the change this makes in Series. | https://api.github.com/repos/pandas-dev/pandas/pulls/32668 | 2020-03-12T21:04:08Z | 2020-03-15T00:34:01Z | 2020-03-15T00:34:01Z | 2020-03-15T21:00:00Z |
REF: values-> _values | diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 6388f2007cb12..52423c4008399 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -396,7 +396,7 @@ def _engine(self):
def unique(self, level=None):
if level is not None:
self._validate_index_level(level)
- result = self.values.unique()
+ result = self._values.unique()
# Use _simple_new instead of _shallow_copy to ensure we keep dtype
# of result, not self.
return type(self)._simple_new(result, name=self.name)
@@ -423,7 +423,7 @@ def where(self, cond, other=None):
# 3. Rebuild CategoricalIndex.
if other is None:
other = self._na_value
- values = np.where(cond, self.values, other)
+ values = np.where(cond, self._values, other)
cat = Categorical(values, dtype=self.dtype)
return type(self)._simple_new(cat, name=self.name)
@@ -532,13 +532,13 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None):
"method='nearest' not implemented yet for CategoricalIndex"
)
- if isinstance(target, CategoricalIndex) and self.values.is_dtype_equal(target):
- if self.values.equals(target.values):
+ if isinstance(target, CategoricalIndex) and self._values.is_dtype_equal(target):
+ if self._values.equals(target._values):
# we have the same codes
codes = target.codes
else:
codes = _recode_for_categories(
- target.codes, target.categories, self.values.categories
+ target.codes, target.categories, self._values.categories
)
else:
if isinstance(target, CategoricalIndex):
@@ -560,7 +560,7 @@ def get_indexer_non_unique(self, target):
target = target.codes
indexer, missing = self._engine.get_indexer_non_unique(target)
return ensure_platform_int(indexer), missing
- target = target.values
+ target = target._values
codes = self.categories.get_indexer(target)
indexer, missing = self._engine.get_indexer_non_unique(codes)
@@ -679,7 +679,7 @@ def map(self, mapper):
>>> idx.map({'a': 'first', 'b': 'second'})
Index(['first', 'second', nan], dtype='object')
"""
- return self._shallow_copy_with_infer(self.values.map(mapper))
+ return self._shallow_copy_with_infer(self._values.map(mapper))
def delete(self, loc):
"""
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 80d58de6f1437..3d31e7f8054ec 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -409,7 +409,7 @@ def __reduce__(self):
@Appender(Index.astype.__doc__)
def astype(self, dtype, copy=True):
with rewrite_exception("IntervalArray", type(self).__name__):
- new_values = self.values.astype(dtype, copy=copy)
+ new_values = self._values.astype(dtype, copy=copy)
if is_interval_dtype(new_values):
return self._shallow_copy(new_values)
return Index.astype(self, dtype, copy=copy)
@@ -887,7 +887,7 @@ def _convert_slice_indexer(self, key: slice, kind: str):
def where(self, cond, other=None):
if other is None:
other = self._na_value
- values = np.where(cond, self.values, other)
+ values = np.where(cond, self._values, other)
result = IntervalArray(values)
return self._shallow_copy(result)
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py
index 2d1d69772c100..3a6f3630c19e7 100644
--- a/pandas/core/indexes/numeric.py
+++ b/pandas/core/indexes/numeric.py
@@ -248,7 +248,7 @@ def inferred_type(self) -> str:
@property
def asi8(self) -> np.ndarray:
# do not cache or you'll create a memory leak
- return self.values.view(self._default_dtype)
+ return self._values.view(self._default_dtype)
class Int64Index(IntegerIndex):
@@ -368,7 +368,7 @@ def astype(self, dtype, copy=True):
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)
+ arr = astype_nansafe(self._values, dtype=dtype)
return Int64Index(arr)
return super().astype(dtype, copy=copy)
@@ -395,7 +395,7 @@ def _format_native_types(
from pandas.io.formats.format import FloatArrayFormatter
formatter = FloatArrayFormatter(
- self.values,
+ self._values,
na_rep=na_rep,
float_format=float_format,
decimal=decimal,
| For the affected Index subclasses .values and ._values are the same | https://api.github.com/repos/pandas-dev/pandas/pulls/32662 | 2020-03-12T14:55:52Z | 2020-03-14T03:12:13Z | 2020-03-14T03:12:13Z | 2020-03-14T03:14:32Z |
Backport PR #32658 on branch 1.0.x (DOC: Organize regressions) | diff --git a/doc/source/whatsnew/v1.0.2.rst b/doc/source/whatsnew/v1.0.2.rst
index 6eac25c661689..d3921271264c2 100644
--- a/doc/source/whatsnew/v1.0.2.rst
+++ b/doc/source/whatsnew/v1.0.2.rst
@@ -1,6 +1,6 @@
.. _whatsnew_102:
-What's new in 1.0.2 (March 11, 2020)
+What's new in 1.0.2 (March 12, 2020)
------------------------------------
These are the changes in pandas 1.0.2. See :ref:`release` for a full changelog
@@ -15,23 +15,34 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
-- Fixed regression in :meth:`DataFrame.to_excel` when ``columns`` kwarg is passed (:issue:`31677`)
-- Fixed regression in :meth:`Series.align` when ``other`` is a DataFrame and ``method`` is not None (:issue:`31785`)
+**Groupby**
+
- Fixed regression in :meth:`groupby(..).agg() <pandas.core.groupby.GroupBy.agg>` which was failing on frames with MultiIndex columns and a custom function (:issue:`31777`)
- Fixed regression in ``groupby(..).rolling(..).apply()`` (``RollingGroupby``) where the ``raw`` parameter was ignored (:issue:`31754`)
- Fixed regression in :meth:`rolling(..).corr() <pandas.core.window.rolling.Rolling.corr>` when using a time offset (:issue:`31789`)
- Fixed regression in :meth:`groupby(..).nunique() <pandas.core.groupby.DataFrameGroupBy.nunique>` which was modifying the original values if ``NaN`` values were present (:issue:`31950`)
- Fixed regression in ``DataFrame.groupby`` raising a ``ValueError`` from an internal operation (:issue:`31802`)
-- Fixed regression where :func:`read_pickle` raised a ``UnicodeDecodeError`` when reading a py27 pickle with :class:`MultiIndex` column (:issue:`31988`).
-- Fixed regression in :class:`DataFrame` arithmetic operations with mis-matched columns (:issue:`31623`)
- Fixed regression in :meth:`groupby(..).agg() <pandas.core.groupby.GroupBy.agg>` calling a user-provided function an extra time on an empty input (:issue:`31760`)
-- Fixed regression in joining on :class:`DatetimeIndex` or :class:`TimedeltaIndex` to preserve ``freq`` in simple cases (:issue:`32166`)
-- Fixed regression in the repr of an object-dtype :class:`Index` with bools and missing values (:issue:`32146`)
+
+**I/O**
+
- Fixed regression in :meth:`read_csv` in which the ``encoding`` option was not recognized with certain file-like objects (:issue:`31819`)
-- Fixed regression in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with (tz-aware) index and ``method=nearest`` (:issue:`26683`)
+- Fixed regression in :meth:`DataFrame.to_excel` when the ``columns`` keyword argument is passed (:issue:`31677`)
- Fixed regression in :class:`ExcelFile` where the stream passed into the function was closed by the destructor. (:issue:`31467`)
+- Fixed regression where :func:`read_pickle` raised a ``UnicodeDecodeError`` when reading a py27 pickle with :class:`MultiIndex` column (:issue:`31988`).
+
+**Reindexing/alignment**
+
+- Fixed regression in :meth:`Series.align` when ``other`` is a DataFrame and ``method`` is not None (:issue:`31785`)
+- Fixed regression in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with (tz-aware) index and ``method=nearest`` (:issue:`26683`)
- Fixed regression in :meth:`DataFrame.reindex_like` on a :class:`DataFrame` subclass raised an ``AssertionError`` (:issue:`31925`)
+- Fixed regression in :class:`DataFrame` arithmetic operations with mis-matched columns (:issue:`31623`)
+
+**Other**
+
+- Fixed regression in joining on :class:`DatetimeIndex` or :class:`TimedeltaIndex` to preserve ``freq`` in simple cases (:issue:`32166`)
- Fixed regression in :meth:`Series.shift` with ``datetime64`` dtype when passing an integer ``fill_value`` (:issue:`32591`)
+- Fixed regression in the repr of an object-dtype :class:`Index` with bools and missing values (:issue:`32146`)
.. ---------------------------------------------------------------------------
| Backport PR #32658: DOC: Organize regressions | https://api.github.com/repos/pandas-dev/pandas/pulls/32661 | 2020-03-12T14:11:16Z | 2020-03-12T14:39:01Z | 2020-03-12T14:39:01Z | 2020-03-12T14:39:01Z |
Backport PR #32490: BUG: Fix bug, where BooleanDtype columns are conv… | diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index e42402b307f28..b19bd2240ca9e 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -589,6 +589,8 @@ def astype(self, dtype, copy=True):
if getattr(self.dtype, "tz", None) is None:
return self.tz_localize(new_tz)
result = self.tz_convert(new_tz)
+ if copy:
+ result = result.copy()
if new_tz is None:
# Do we want .astype('datetime64[ns]') to be an ndarray.
# The astype in Block._astype expects this to return an
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 4d99a13ccd0b5..eecb1e567bd8f 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1045,8 +1045,8 @@ def convert_dtypes(
dtype
new dtype
"""
-
- if convert_string or convert_integer or convert_boolean:
+ is_extension = is_extension_array_dtype(input_array.dtype)
+ if (convert_string or convert_integer or convert_boolean) and not is_extension:
try:
inferred_dtype = lib.infer_dtype(input_array)
except ValueError:
@@ -1059,9 +1059,7 @@ def convert_dtypes(
if convert_integer:
target_int_dtype = "Int64"
- if is_integer_dtype(input_array.dtype) and not is_extension_array_dtype(
- input_array.dtype
- ):
+ if is_integer_dtype(input_array.dtype):
from pandas.core.arrays.integer import _dtypes
inferred_dtype = _dtypes.get(input_array.dtype.name, target_int_dtype)
@@ -1075,9 +1073,7 @@ def convert_dtypes(
inferred_dtype = input_array.dtype
if convert_boolean:
- if is_bool_dtype(input_array.dtype) and not is_extension_array_dtype(
- input_array.dtype
- ):
+ if is_bool_dtype(input_array.dtype):
inferred_dtype = "boolean"
else:
if isinstance(inferred_dtype, str) and inferred_dtype == "boolean":
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index db98ec5ad388e..33a5d6443aa7c 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -2209,6 +2209,9 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
# 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()
if getattr(values, "tz", None) is None:
values = DatetimeArray(values).tz_localize("UTC")
values = values.tz_convert(dtype.tz)
diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py
index 5608ab5fbd9db..925781b6c4851 100644
--- a/pandas/tests/arrays/test_datetimes.py
+++ b/pandas/tests/arrays/test_datetimes.py
@@ -151,6 +151,18 @@ def test_astype_to_same(self):
result = arr.astype(DatetimeTZDtype(tz="US/Central"), copy=False)
assert result is arr
+ @pytest.mark.parametrize("dtype", ["datetime64[ns]", "datetime64[ns, UTC]"])
+ @pytest.mark.parametrize(
+ "other", ["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, CET]"]
+ )
+ def test_astype_copies(self, dtype, other):
+ # https://github.com/pandas-dev/pandas/pull/32490
+ s = pd.Series([1, 2], dtype=dtype)
+ orig = s.copy()
+ t = s.astype(other)
+ t[:] = pd.NaT
+ tm.assert_series_equal(s, orig)
+
@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")])
diff --git a/pandas/tests/series/test_convert_dtypes.py b/pandas/tests/series/test_convert_dtypes.py
index 17527a09f07a1..a41f893e3753f 100644
--- a/pandas/tests/series/test_convert_dtypes.py
+++ b/pandas/tests/series/test_convert_dtypes.py
@@ -279,3 +279,8 @@ def test_convert_string_dtype(self):
)
result = df.convert_dtypes()
tm.assert_frame_equal(df, result)
+
+ def test_convert_bool_dtype(self):
+ # GH32287
+ df = pd.DataFrame({"A": pd.array([True])})
+ tm.assert_frame_equal(df, df.convert_dtypes())
| …erted to Int64
https://github.com/pandas-dev/pandas/pull/32490 | https://api.github.com/repos/pandas-dev/pandas/pulls/32660 | 2020-03-12T13:30:27Z | 2020-03-12T14:11:32Z | 2020-03-12T14:11:31Z | 2020-03-12T14:11:36Z |
Backport PR #32656 on branch 1.0.x (DOC: fix announce formtting) | diff --git a/doc/sphinxext/announce.py b/doc/sphinxext/announce.py
index 9bc353b115852..839970febda2c 100755
--- a/doc/sphinxext/announce.py
+++ b/doc/sphinxext/announce.py
@@ -122,14 +122,15 @@ def build_string(revision_range, heading="Contributors"):
components["uline"] = "=" * len(components["heading"])
components["authors"] = "* " + "\n* ".join(components["authors"])
+ # Don't change this to an fstring. It breaks the formatting.
tpl = textwrap.dedent(
- f"""\
- {components['heading']}
- {components['uline']}
+ """\
+ {heading}
+ {uline}
- {components['author_message']}
- {components['authors']}"""
- )
+ {author_message}
+ {authors}"""
+ ).format(**components)
return tpl
| Backport PR #32656: DOC: fix announce formtting | https://api.github.com/repos/pandas-dev/pandas/pulls/32659 | 2020-03-12T13:16:12Z | 2020-03-12T14:07:37Z | 2020-03-12T14:07:37Z | 2020-03-12T14:07:37Z |
DOC: Organize regressions | diff --git a/doc/source/whatsnew/v1.0.2.rst b/doc/source/whatsnew/v1.0.2.rst
index 0bfcb95b25ffd..97260ec5e9f0e 100644
--- a/doc/source/whatsnew/v1.0.2.rst
+++ b/doc/source/whatsnew/v1.0.2.rst
@@ -1,6 +1,6 @@
.. _whatsnew_102:
-What's new in 1.0.2 (March 11, 2020)
+What's new in 1.0.2 (March 12, 2020)
------------------------------------
These are the changes in pandas 1.0.2. See :ref:`release` for a full changelog
@@ -15,23 +15,34 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
-- Fixed regression in :meth:`DataFrame.to_excel` when ``columns`` kwarg is passed (:issue:`31677`)
-- Fixed regression in :meth:`Series.align` when ``other`` is a DataFrame and ``method`` is not None (:issue:`31785`)
+**Groupby**
+
- Fixed regression in :meth:`groupby(..).agg() <pandas.core.groupby.GroupBy.agg>` which was failing on frames with MultiIndex columns and a custom function (:issue:`31777`)
- Fixed regression in ``groupby(..).rolling(..).apply()`` (``RollingGroupby``) where the ``raw`` parameter was ignored (:issue:`31754`)
- Fixed regression in :meth:`rolling(..).corr() <pandas.core.window.rolling.Rolling.corr>` when using a time offset (:issue:`31789`)
- Fixed regression in :meth:`groupby(..).nunique() <pandas.core.groupby.DataFrameGroupBy.nunique>` which was modifying the original values if ``NaN`` values were present (:issue:`31950`)
- Fixed regression in ``DataFrame.groupby`` raising a ``ValueError`` from an internal operation (:issue:`31802`)
-- Fixed regression where :func:`read_pickle` raised a ``UnicodeDecodeError`` when reading a py27 pickle with :class:`MultiIndex` column (:issue:`31988`).
-- Fixed regression in :class:`DataFrame` arithmetic operations with mis-matched columns (:issue:`31623`)
- Fixed regression in :meth:`groupby(..).agg() <pandas.core.groupby.GroupBy.agg>` calling a user-provided function an extra time on an empty input (:issue:`31760`)
-- Fixed regression in joining on :class:`DatetimeIndex` or :class:`TimedeltaIndex` to preserve ``freq`` in simple cases (:issue:`32166`)
-- Fixed regression in the repr of an object-dtype :class:`Index` with bools and missing values (:issue:`32146`)
+
+**I/O**
+
- Fixed regression in :meth:`read_csv` in which the ``encoding`` option was not recognized with certain file-like objects (:issue:`31819`)
-- Fixed regression in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with (tz-aware) index and ``method=nearest`` (:issue:`26683`)
+- Fixed regression in :meth:`DataFrame.to_excel` when the ``columns`` keyword argument is passed (:issue:`31677`)
- Fixed regression in :class:`ExcelFile` where the stream passed into the function was closed by the destructor. (:issue:`31467`)
+- Fixed regression where :func:`read_pickle` raised a ``UnicodeDecodeError`` when reading a py27 pickle with :class:`MultiIndex` column (:issue:`31988`).
+
+**Reindexing/alignment**
+
+- Fixed regression in :meth:`Series.align` when ``other`` is a DataFrame and ``method`` is not None (:issue:`31785`)
+- Fixed regression in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with (tz-aware) index and ``method=nearest`` (:issue:`26683`)
- Fixed regression in :meth:`DataFrame.reindex_like` on a :class:`DataFrame` subclass raised an ``AssertionError`` (:issue:`31925`)
+- Fixed regression in :class:`DataFrame` arithmetic operations with mis-matched columns (:issue:`31623`)
+
+**Other**
+
+- Fixed regression in joining on :class:`DatetimeIndex` or :class:`TimedeltaIndex` to preserve ``freq`` in simple cases (:issue:`32166`)
- Fixed regression in :meth:`Series.shift` with ``datetime64`` dtype when passing an integer ``fill_value`` (:issue:`32591`)
+- Fixed regression in the repr of an object-dtype :class:`Index` with bools and missing values (:issue:`32146`)
.. ---------------------------------------------------------------------------
| https://api.github.com/repos/pandas-dev/pandas/pulls/32658 | 2020-03-12T12:23:09Z | 2020-03-12T14:11:02Z | 2020-03-12T14:11:02Z | 2020-03-12T14:11:05Z | |
Backport PR #32544 on branch 1.0.x (BUG: pd.ExcelFile closes stream on destruction) | diff --git a/doc/source/whatsnew/v1.0.2.rst b/doc/source/whatsnew/v1.0.2.rst
index 211d0ec95f7ee..6eac25c661689 100644
--- a/doc/source/whatsnew/v1.0.2.rst
+++ b/doc/source/whatsnew/v1.0.2.rst
@@ -29,6 +29,7 @@ Fixed regressions
- Fixed regression in the repr of an object-dtype :class:`Index` with bools and missing values (:issue:`32146`)
- Fixed regression in :meth:`read_csv` in which the ``encoding`` option was not recognized with certain file-like objects (:issue:`31819`)
- Fixed regression in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with (tz-aware) index and ``method=nearest`` (:issue:`26683`)
+- Fixed regression in :class:`ExcelFile` where the stream passed into the function was closed by the destructor. (:issue:`31467`)
- Fixed regression in :meth:`DataFrame.reindex_like` on a :class:`DataFrame` subclass raised an ``AssertionError`` (:issue:`31925`)
- Fixed regression in :meth:`Series.shift` with ``datetime64`` dtype when passing an integer ``fill_value`` (:issue:`32591`)
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 2a91381b7fbeb..a8ae359509de2 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -367,6 +367,9 @@ def _workbook_class(self):
def load_workbook(self, filepath_or_buffer):
pass
+ def close(self):
+ pass
+
@property
@abc.abstractmethod
def sheet_names(self):
@@ -895,14 +898,7 @@ def sheet_names(self):
def close(self):
"""close io if necessary"""
- if self.engine == "openpyxl":
- # https://stackoverflow.com/questions/31416842/
- # openpyxl-does-not-close-excel-workbook-in-read-only-mode
- wb = self.book
- wb._archive.close()
-
- if hasattr(self.io, "close"):
- self.io.close()
+ self._reader.close()
def __enter__(self):
return self
diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py
index be52523e486af..c4327316d4784 100644
--- a/pandas/io/excel/_openpyxl.py
+++ b/pandas/io/excel/_openpyxl.py
@@ -497,6 +497,11 @@ def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
filepath_or_buffer, read_only=True, data_only=True, keep_links=False
)
+ def close(self):
+ # https://stackoverflow.com/questions/31416842/
+ # openpyxl-does-not-close-excel-workbook-in-read-only-mode
+ self.book.close()
+
@property
def sheet_names(self) -> List[str]:
return self.book.sheetnames
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 8d00ef1b7fe3e..140cb80dbf7f8 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -628,6 +628,17 @@ def test_read_from_py_localpath(self, read_ext):
tm.assert_frame_equal(expected, actual)
+ @td.check_file_leaks
+ def test_close_from_py_localpath(self, read_ext):
+
+ # GH31467
+ str_path = os.path.join("test1" + read_ext)
+ with open(str_path, "rb") as f:
+ x = pd.read_excel(f, "Sheet1", index_col=0)
+ del x
+ # should not throw an exception because the passed file was closed
+ f.read()
+
def test_reader_seconds(self, read_ext):
if pd.read_excel.keywords["engine"] == "pyxlsb":
pytest.xfail("Sheets containing datetimes not supported by pyxlsb")
@@ -1019,10 +1030,10 @@ def test_excel_read_buffer(self, engine, read_ext):
tm.assert_frame_equal(expected, actual)
def test_reader_closes_file(self, engine, read_ext):
- f = open("test1" + read_ext, "rb")
- with pd.ExcelFile(f) as xlsx:
- # parses okay
- pd.read_excel(xlsx, "Sheet1", index_col=0, engine=engine)
+ with open("test1" + read_ext, "rb") as f:
+ with pd.ExcelFile(f) as xlsx:
+ # parses okay
+ pd.read_excel(xlsx, "Sheet1", index_col=0, engine=engine)
assert f.closed
| Backport PR #32544: BUG: pd.ExcelFile closes stream on destruction | https://api.github.com/repos/pandas-dev/pandas/pulls/32657 | 2020-03-12T12:18:53Z | 2020-03-12T13:15:43Z | 2020-03-12T13:15:43Z | 2020-03-12T13:15:43Z |
DOC: fix announce formtting | diff --git a/doc/sphinxext/announce.py b/doc/sphinxext/announce.py
index e4859157f73de..0084036f1e75c 100755
--- a/doc/sphinxext/announce.py
+++ b/doc/sphinxext/announce.py
@@ -122,14 +122,15 @@ def build_string(revision_range, heading="Contributors"):
components["uline"] = "=" * len(components["heading"])
components["authors"] = "* " + "\n* ".join(components["authors"])
+ # Don't change this to an fstring. It breaks the formatting.
tpl = textwrap.dedent(
- f"""\
- {components['heading']}
- {components['uline']}
+ """\
+ {heading}
+ {uline}
- {components['author_message']}
- {components['authors']}"""
- )
+ {author_message}
+ {authors}"""
+ ).format(**components)
return tpl
| Master:
```
Contributors
============
A total of 143 people contributed patches to this release. People with a
"+" by their names contributed a patch for the first time.
* 3vts +
* A Brooks +
* Abbie Popa +
* Achmad Syarif Hidayatullah +
```
PR
```
Contributors
============
A total of 143 people contributed patches to this release. People with a
"+" by their names contributed a patch for the first time.
* 3vts +
* A Brooks +
* Abbie Popa +
```
I think the offset computed by textwrap.dedent changed. With fstrings it's calculated after the values are interpolated. We want it to be computed on the templated version. | https://api.github.com/repos/pandas-dev/pandas/pulls/32656 | 2020-03-12T12:04:27Z | 2020-03-12T13:16:00Z | 2020-03-12T13:16:00Z | 2020-03-12T13:16:04Z |
BUG: DTI/TDI/PI get_indexer_non_unique with incompatible dtype | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 1663d4c44c362..cdef6c65863fa 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -301,6 +301,7 @@ Indexing
- Bug in :meth:`DataFrame.iat` incorrectly returning ``Timestamp`` instead of ``datetime`` in some object-dtype cases (:issue:`32809`)
- Bug in :meth:`Series.loc` and :meth:`DataFrame.loc` when indexing with an integer key on a object-dtype :class:`Index` that is not all-integers (:issue:`31905`)
- Bug in :meth:`DataFrame.iloc.__setitem__` on a :class:`DataFrame` with duplicate columns incorrectly setting values for all matching columns (:issue:`15686`, :issue:`22036`)
+- Bug in :meth:`DataFrame.loc:` and :meth:`Series.loc` with a :class:`DatetimeIndex`, :class:`TimedeltaIndex`, or :class:`PeriodIndex` incorrectly allowing lookups of non-matching datetime-like dtypes (:issue:`32650`)
Missing
^^^^^^^
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 31966489403f4..51c9cd881de4e 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -29,7 +29,6 @@
ensure_platform_int,
is_bool,
is_bool_dtype,
- is_categorical,
is_categorical_dtype,
is_datetime64_any_dtype,
is_dtype_equal,
@@ -532,6 +531,9 @@ def _shallow_copy_with_infer(self, values, **kwargs):
return self._constructor(values, **attributes)
except (TypeError, ValueError):
pass
+
+ # Remove tz so Index will try non-DatetimeIndex inference
+ attributes.pop("tz", None)
return Index(values, **attributes)
def _update_inplace(self, result, **kwargs):
@@ -4657,10 +4659,8 @@ def get_indexer_non_unique(self, target):
if pself is not self or ptarget is not target:
return pself.get_indexer_non_unique(ptarget)
- if is_categorical(target):
+ if is_categorical_dtype(target.dtype):
tgt_values = np.asarray(target)
- elif self.is_all_dates and target.is_all_dates: # GH 30399
- tgt_values = target.asi8
else:
tgt_values = target._get_engine_target()
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 054a64bf3f990..878c588c6e51a 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -8,13 +8,14 @@
from pandas._libs import NaT, iNaT, join as libjoin, lib
from pandas._libs.tslibs import timezones
-from pandas._typing import Label
+from pandas._typing import DtypeObj, Label
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender, cache_readonly
from pandas.core.dtypes.common import (
ensure_int64,
+ ensure_platform_int,
is_bool_dtype,
is_categorical_dtype,
is_dtype_equal,
@@ -32,7 +33,7 @@
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
from pandas.core.base import _shared_docs
import pandas.core.indexes.base as ibase
-from pandas.core.indexes.base import Index, _index_shared_docs
+from pandas.core.indexes.base import Index, _index_shared_docs, ensure_index
from pandas.core.indexes.extension import (
ExtensionIndex,
inherit_names,
@@ -101,6 +102,12 @@ class DatetimeIndexOpsMixin(ExtensionIndex):
def is_all_dates(self) -> bool:
return True
+ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
+ """
+ Can we compare values of the given dtype to our own?
+ """
+ raise AbstractMethodError(self)
+
# ------------------------------------------------------------------------
# Abstract data attributes
@@ -426,6 +433,21 @@ def _partial_date_slice(
# try to find the dates
return (lhs_mask & rhs_mask).nonzero()[0]
+ @Appender(Index.get_indexer_non_unique.__doc__)
+ def get_indexer_non_unique(self, target):
+ target = ensure_index(target)
+ pself, ptarget = self._maybe_promote(target)
+ if pself is not self or ptarget is not target:
+ return pself.get_indexer_non_unique(ptarget)
+
+ if not self._is_comparable_dtype(target.dtype):
+ no_matches = -1 * np.ones(self.shape, dtype=np.intp)
+ return no_matches, no_matches
+
+ tgt_values = target.asi8
+ indexer, missing = self._engine.get_indexer_non_unique(tgt_values)
+ return ensure_platform_int(indexer), missing
+
# --------------------------------------------------------------------
__add__ = make_wrapped_arith_op("__add__")
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index e791133220dbf..ca1995adc1ea9 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -7,10 +7,18 @@
from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib as libts
from pandas._libs.tslibs import fields, parsing, timezones
-from pandas._typing import Label
+from pandas._typing import DtypeObj, Label
from pandas.util._decorators import cache_readonly
-from pandas.core.dtypes.common import _NS_DTYPE, is_float, is_integer, is_scalar
+from pandas.core.dtypes.common import (
+ _NS_DTYPE,
+ is_datetime64_any_dtype,
+ is_datetime64_dtype,
+ is_datetime64tz_dtype,
+ is_float,
+ is_integer,
+ is_scalar,
+)
from pandas.core.dtypes.missing import is_valid_nat_for_dtype
from pandas.core.arrays.datetimes import DatetimeArray, tz_to_dtype
@@ -298,6 +306,18 @@ def _convert_for_op(self, value):
return Timestamp(value).asm8
raise ValueError("Passed item and index have different timezone")
+ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
+ """
+ Can we compare values of the given dtype to our own?
+ """
+ if not is_datetime64_any_dtype(dtype):
+ return False
+ if self.tz is not None:
+ # If we have tz, we can compare to tzaware
+ return is_datetime64tz_dtype(dtype)
+ # if we dont have tz, we can only compare to tznaive
+ return is_datetime64_dtype(dtype)
+
# --------------------------------------------------------------------
# Rendering Methods
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index f83234f1aac0b..f6bf02b6df676 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -9,7 +9,7 @@
from pandas._libs.tslibs import frequencies as libfrequencies, resolution
from pandas._libs.tslibs.parsing import parse_time_string
from pandas._libs.tslibs.period import Period
-from pandas._typing import Label
+from pandas._typing import DtypeObj, Label
from pandas.util._decorators import Appender, cache_readonly
from pandas.core.dtypes.common import (
@@ -23,6 +23,7 @@
is_scalar,
pandas_dtype,
)
+from pandas.core.dtypes.dtypes import PeriodDtype
from pandas.core.arrays.period import (
PeriodArray,
@@ -298,6 +299,14 @@ def _maybe_convert_timedelta(self, other):
# raise when input doesn't have freq
raise raise_on_incompatible(self, None)
+ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
+ """
+ Can we compare values of the given dtype to our own?
+ """
+ if not isinstance(dtype, PeriodDtype):
+ return False
+ return dtype.freq == self.freq
+
# ------------------------------------------------------------------------
# Rendering Methods
@@ -454,12 +463,11 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None):
def get_indexer_non_unique(self, target):
target = ensure_index(target)
- if isinstance(target, PeriodIndex):
- if target.freq != self.freq:
- no_matches = -1 * np.ones(self.shape, dtype=np.intp)
- return no_matches, no_matches
+ if not self._is_comparable_dtype(target.dtype):
+ no_matches = -1 * np.ones(self.shape, dtype=np.intp)
+ return no_matches, no_matches
- target = target.asi8
+ target = target.asi8
indexer, missing = self._int64index.get_indexer_non_unique(target)
return ensure_platform_int(indexer), missing
diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index 7a7670b0e7965..588cb3e37bced 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -1,7 +1,7 @@
""" implement the TimedeltaIndex """
from pandas._libs import NaT, Timedelta, index as libindex
-from pandas._typing import Label
+from pandas._typing import DtypeObj, Label
from pandas.util._decorators import Appender
from pandas.core.dtypes.common import (
@@ -213,6 +213,12 @@ def _maybe_promote(self, other):
other = TimedeltaIndex(other)
return self, other
+ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
+ """
+ Can we compare values of the given dtype to our own?
+ """
+ return is_timedelta64_dtype(dtype)
+
def get_loc(self, key, method=None, tolerance=None):
"""
Get integer location for requested label
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 2981f56e58ecc..5bdbc18769ce5 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -2616,3 +2616,40 @@ def test_convert_almost_null_slice(indices):
msg = "'>=' not supported between instances of 'str' and 'int'"
with pytest.raises(TypeError, match=msg):
idx._convert_slice_indexer(key, "loc")
+
+
+dtlike_dtypes = [
+ np.dtype("timedelta64[ns]"),
+ np.dtype("datetime64[ns]"),
+ pd.DatetimeTZDtype("ns", "Asia/Tokyo"),
+ pd.PeriodDtype("ns"),
+]
+
+
+@pytest.mark.parametrize("ldtype", dtlike_dtypes)
+@pytest.mark.parametrize("rdtype", dtlike_dtypes)
+def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype):
+
+ vals = np.tile(3600 * 10 ** 9 * np.arange(3), 2)
+
+ def construct(dtype):
+ if dtype is dtlike_dtypes[-1]:
+ # PeriodArray will try to cast ints to strings
+ return pd.DatetimeIndex(vals).astype(dtype)
+ return pd.Index(vals, dtype=dtype)
+
+ left = construct(ldtype)
+ right = construct(rdtype)
+
+ result = left.get_indexer_non_unique(right)
+
+ if ldtype is rdtype:
+ ex1 = np.array([0, 3, 1, 4, 2, 5] * 2, dtype=np.intp)
+ ex2 = np.array([], dtype=np.intp)
+ tm.assert_numpy_array_equal(result[0], ex1)
+ tm.assert_numpy_array_equal(result[1], ex2.astype(np.int64))
+
+ else:
+ no_matches = np.array([-1] * 6, dtype=np.intp)
+ tm.assert_numpy_array_equal(result[0], no_matches)
+ tm.assert_numpy_array_equal(result[1], no_matches)
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index a0edf78f79a53..ee92e5a69204d 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -1073,3 +1073,25 @@ def test_loc_slice_disallows_positional():
with tm.assert_produces_warning(FutureWarning):
# GH#31840 deprecated incorrect behavior
df.loc[1:3, 1] = 2
+
+
+def test_loc_datetimelike_mismatched_dtypes():
+ # GH#32650 dont mix and match datetime/timedelta/period dtypes
+
+ df = pd.DataFrame(
+ np.random.randn(5, 3),
+ columns=["a", "b", "c"],
+ index=pd.date_range("2012", freq="H", periods=5),
+ )
+ # create dataframe with non-unique DatetimeIndex
+ df = df.iloc[[0, 2, 2, 3]].copy()
+
+ dti = df.index
+ tdi = pd.TimedeltaIndex(dti.asi8) # matching i8 values
+
+ msg = r"None of \[TimedeltaIndex.* are in the \[index\]"
+ with pytest.raises(KeyError, match=msg):
+ df.loc[tdi]
+
+ with pytest.raises(KeyError, match=msg):
+ df["a"].loc[tdi]
| I'm pretty sure we can share more code here, but PeriodEngine needs some work first. | https://api.github.com/repos/pandas-dev/pandas/pulls/32650 | 2020-03-12T03:17:52Z | 2020-03-17T01:41:27Z | 2020-03-17T01:41:27Z | 2020-03-23T16:12:20Z |
Backport PR #32223: BUG: Fix DateFrameGroupBy.mean error for Int64 dtype | diff --git a/doc/source/whatsnew/v1.0.2.rst b/doc/source/whatsnew/v1.0.2.rst
index d00a418af3ddb..c9521cd7fb75c 100644
--- a/doc/source/whatsnew/v1.0.2.rst
+++ b/doc/source/whatsnew/v1.0.2.rst
@@ -92,6 +92,7 @@ Bug fixes
- Fixed bug in setting values using a slice indexer with string dtype (:issue:`31772`)
- Fixed bug where :meth:`pandas.core.groupby.GroupBy.first` and :meth:`pandas.core.groupby.GroupBy.last` would raise a ``TypeError`` when groups contained ``pd.NA`` in a column of object dtype (:issue:`32123`)
- Fix bug in :meth:`Series.convert_dtypes` for series with mix of integers and strings (:issue:`32117`)
+- Fixed bug where :meth:`DataFrameGroupBy.mean`, :meth:`DataFrameGroupBy.median`, :meth:`DataFrameGroupBy.var`, and :meth:`DataFrameGroupBy.std` would raise a ``TypeError`` on ``Int64`` dtype columns (:issue:`32219`)
**Strings**
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index d346a0ccbcd3f..97f73966dda8a 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1080,7 +1080,7 @@ def _cython_agg_blocks(
result = type(block.values)._from_sequence(
result.ravel(), dtype=block.values.dtype
)
- except ValueError:
+ except (ValueError, TypeError):
# reshape to be valid for non-Extension Block
result = result.reshape(1, -1)
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index 1ecff003b545b..3f7b0d46faf5d 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -1563,3 +1563,34 @@ def test_groupby_mean_no_overflow():
}
)
assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840
+
+
+@pytest.mark.parametrize(
+ "values",
+ [
+ {
+ "a": [1, 1, 1, 2, 2, 2, 3, 3, 3],
+ "b": [1, pd.NA, 2, 1, pd.NA, 2, 1, pd.NA, 2],
+ },
+ {"a": [1, 1, 2, 2, 3, 3], "b": [1, 2, 1, 2, 1, 2]},
+ ],
+)
+@pytest.mark.parametrize("function", ["mean", "median", "var"])
+def test_apply_to_nullable_integer_returns_float(values, function):
+ # https://github.com/pandas-dev/pandas/issues/32219
+ output = 0.5 if function == "var" else 1.5
+ arr = np.array([output] * 3, dtype=float)
+ idx = pd.Index([1, 2, 3], dtype=object, name="a")
+ expected = pd.DataFrame({"b": arr}, index=idx)
+
+ groups = pd.DataFrame(values, dtype="Int64").groupby("a")
+
+ result = getattr(groups, function)()
+ tm.assert_frame_equal(result, expected)
+
+ result = groups.agg(function)
+ tm.assert_frame_equal(result, expected)
+
+ result = groups.agg([function])
+ expected.columns = MultiIndex.from_tuples([("b", function)])
+ tm.assert_frame_equal(result, expected)
| cc @jreback | https://api.github.com/repos/pandas-dev/pandas/pulls/32649 | 2020-03-12T02:46:56Z | 2020-03-12T04:28:27Z | 2020-03-12T04:28:26Z | 2020-03-12T15:04:33Z |
Backport PR #32040 on branch 1.0.x (BUG: GroupBy aggregation of DataFrame with MultiIndex columns breaks with custom function) | diff --git a/doc/source/whatsnew/v1.0.2.rst b/doc/source/whatsnew/v1.0.2.rst
index d00a418af3ddb..5ffde693da9c2 100644
--- a/doc/source/whatsnew/v1.0.2.rst
+++ b/doc/source/whatsnew/v1.0.2.rst
@@ -17,6 +17,7 @@ Fixed regressions
- Fixed regression in :meth:`DataFrame.to_excel` when ``columns`` kwarg is passed (:issue:`31677`)
- Fixed regression in :meth:`Series.align` when ``other`` is a DataFrame and ``method`` is not None (:issue:`31785`)
+- Fixed regression in :meth:`groupby(..).agg() <pandas.core.groupby.GroupBy.agg>` which was failing on frames with MultiIndex columns and a custom function (:issue:`31777`)
- Fixed regression in ``groupby(..).rolling(..).apply()`` (``RollingGroupby``) where the ``raw`` parameter was ignored (:issue:`31754`)
- Fixed regression in :meth:`rolling(..).corr() <pandas.core.window.rolling.Rolling.corr>` when using a time offset (:issue:`31789`)
- Fixed regression in :meth:`groupby(..).nunique() <pandas.core.groupby.DataFrameGroupBy.nunique>` which was modifying the original values if ``NaN`` values were present (:issue:`31950`)
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index d346a0ccbcd3f..ceacafc852e27 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -952,9 +952,11 @@ def aggregate(self, func=None, *args, **kwargs):
raise
result = self._aggregate_frame(func)
else:
- result.columns = Index(
- result.columns.levels[0], name=self._selected_obj.columns.name
- )
+ # select everything except for the last level, which is the one
+ # containing the name of the function(s), see GH 32040
+ result.columns = result.columns.rename(
+ [self._selected_obj.columns.name] * result.columns.nlevels
+ ).droplevel(-1)
if not self.as_index:
self._insert_inaxis_grouper_inplace(result)
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index cd1ea2415b0d2..94c5563e575cc 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -692,6 +692,19 @@ def test_agg_relabel_multiindex_duplicates():
tm.assert_frame_equal(result, expected)
+@pytest.mark.parametrize(
+ "func", [lambda s: s.mean(), lambda s: np.mean(s), lambda s: np.nanmean(s)]
+)
+def test_multiindex_custom_func(func):
+ # GH 31777
+ data = [[1, 4, 2], [5, 7, 1]]
+ df = pd.DataFrame(data, columns=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 3]]))
+ result = df.groupby(np.array([0, 1])).agg(func)
+ expected_dict = {(1, 3): {0: 1, 1: 5}, (1, 4): {0: 4, 1: 7}, (2, 3): {0: 2, 1: 1}}
+ expected = pd.DataFrame(expected_dict)
+ tm.assert_frame_equal(result, expected)
+
+
def myfunc(s):
return np.percentile(s, q=0.90)
| Backport PR #32040: BUG: GroupBy aggregation of DataFrame with MultiIndex columns breaks with custom function | https://api.github.com/repos/pandas-dev/pandas/pulls/32648 | 2020-03-12T02:33:39Z | 2020-03-12T04:26:39Z | 2020-03-12T04:26:39Z | 2020-03-12T04:26:40Z |
Backport PR #32591 on branch 1.0.x (REG: dt64 shift with integer fill_value) | diff --git a/doc/source/whatsnew/v1.0.2.rst b/doc/source/whatsnew/v1.0.2.rst
index d00a418af3ddb..69eca8d8c175d 100644
--- a/doc/source/whatsnew/v1.0.2.rst
+++ b/doc/source/whatsnew/v1.0.2.rst
@@ -29,6 +29,7 @@ Fixed regressions
- Fixed regression in :meth:`read_csv` in which the ``encoding`` option was not recognized with certain file-like objects (:issue:`31819`)
- Fixed regression in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with (tz-aware) index and ``method=nearest`` (:issue:`26683`)
- Fixed regression in :meth:`DataFrame.reindex_like` on a :class:`DataFrame` subclass raised an ``AssertionError`` (:issue:`31925`)
+- Fixed regression in :meth:`Series.shift` with ``datetime64`` dtype when passing an integer ``fill_value`` (:issue:`32591`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index ec954e5721f1d..3d39d85158ffb 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -725,6 +725,57 @@ def _from_factorized(cls, values, original):
def _values_for_argsort(self):
return self._data
+ @Appender(ExtensionArray.shift.__doc__)
+ def shift(self, periods=1, fill_value=None, axis=0):
+ if not self.size or periods == 0:
+ return self.copy()
+
+ if is_valid_nat_for_dtype(fill_value, self.dtype):
+ fill_value = NaT
+ elif not isinstance(fill_value, self._recognized_scalars):
+ # only warn if we're not going to raise
+ if self._scalar_type is Period and lib.is_integer(fill_value):
+ # kludge for #31971 since Period(integer) tries to cast to str
+ new_fill = Period._from_ordinal(fill_value, freq=self.freq)
+ else:
+ new_fill = self._scalar_type(fill_value)
+
+ # stacklevel here is chosen to be correct when called from
+ # DataFrame.shift or Series.shift
+ warnings.warn(
+ f"Passing {type(fill_value)} to shift is deprecated and "
+ "will raise in a future version, pass "
+ f"{self._scalar_type.__name__} instead.",
+ FutureWarning,
+ stacklevel=7,
+ )
+ fill_value = new_fill
+
+ fill_value = self._unbox_scalar(fill_value)
+
+ new_values = self._data
+
+ # make sure array sent to np.roll is c_contiguous
+ f_ordered = new_values.flags.f_contiguous
+ if f_ordered:
+ new_values = new_values.T
+ axis = new_values.ndim - axis - 1
+
+ new_values = np.roll(new_values, periods, axis=axis)
+
+ axis_indexer = [slice(None)] * self.ndim
+ if periods > 0:
+ axis_indexer[axis] = slice(None, periods)
+ else:
+ axis_indexer[axis] = slice(periods, None)
+ new_values[tuple(axis_indexer)] = fill_value
+
+ # restore original order
+ if f_ordered:
+ new_values = new_values.T
+
+ return type(self)._simple_new(new_values, dtype=self.dtype)
+
# ------------------------------------------------------------------
# Additional array methods
# These are not part of the EA API, but we implement them because
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 1229f2ad061b8..db98ec5ad388e 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1897,10 +1897,7 @@ def diff(self, n: int, axis: int = 1) -> List["Block"]:
return super().diff(n, axis)
def shift(
- self,
- periods: int,
- axis: libinternals.BlockPlacement = 0,
- fill_value: Any = None,
+ self, periods: int, axis: int = 0, fill_value: Any = None,
) -> List["ExtensionBlock"]:
"""
Shift the block by `periods`.
@@ -2150,7 +2147,7 @@ def get_values(self, dtype=None):
def iget(self, key):
# GH#31649 we need to wrap scalars in Timestamp/Timedelta
- # TODO: this can be removed if we ever have 2D EA
+ # TODO(EA2D): this can be removed if we ever have 2D EA
result = super().iget(key)
if isinstance(result, np.datetime64):
result = Timestamp(result)
@@ -2158,6 +2155,12 @@ def iget(self, key):
result = Timedelta(result)
return result
+ def shift(self, periods, axis=0, fill_value=None):
+ # TODO(EA2D) this is unnecessary if these blocks are backed by 2D EAs
+ values = self.array_values()
+ new_values = values.shift(periods, fill_value=fill_value, axis=axis)
+ return self.make_block_same_class(new_values)
+
class DatetimeBlock(DatetimeLikeBlockMixin, Block):
__slots__ = ()
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py
index fa45db93c6102..3732818c0efc9 100644
--- a/pandas/tests/arrays/test_datetimelike.py
+++ b/pandas/tests/arrays/test_datetimelike.py
@@ -239,6 +239,23 @@ def test_inplace_arithmetic(self):
arr -= pd.Timedelta(days=1)
tm.assert_equal(arr, expected)
+ def test_shift_fill_int_deprecated(self):
+ # GH#31971
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ arr = self.array_cls(data, freq="D")
+
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ result = arr.shift(1, fill_value=1)
+
+ expected = arr.copy()
+ if self.array_cls is PeriodArray:
+ fill_val = PeriodArray._scalar_type._from_ordinal(1, freq=arr.freq)
+ else:
+ fill_val = arr._scalar_type(1)
+ expected[0] = fill_val
+ expected[1:] = arr[:-1]
+ tm.assert_equal(result, expected)
+
class TestDatetimeArray(SharedTests):
index_cls = pd.DatetimeIndex
diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py
index cfb17de892b1c..f6c89172bbf86 100644
--- a/pandas/tests/frame/methods/test_shift.py
+++ b/pandas/tests/frame/methods/test_shift.py
@@ -185,3 +185,26 @@ def test_tshift(self, datetime_frame):
msg = "Freq was not given and was not set in the index"
with pytest.raises(ValueError, match=msg):
no_freq.tshift()
+
+ def test_shift_dt64values_int_fill_deprecated(self):
+ # GH#31971
+ ser = pd.Series([pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")])
+ df = ser.to_frame()
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = df.shift(1, fill_value=0)
+
+ expected = pd.Series([pd.Timestamp(0), ser[0]]).to_frame()
+ tm.assert_frame_equal(result, expected)
+
+ # axis = 1
+ df2 = pd.DataFrame({"A": ser, "B": ser})
+ df2._consolidate_inplace()
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = df2.shift(1, axis=1, fill_value=0)
+
+ expected = pd.DataFrame(
+ {"A": [pd.Timestamp(0), pd.Timestamp(0)], "B": df2["A"]}
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_shift.py b/pandas/tests/series/methods/test_shift.py
index 8256e2f33b936..e8d7f5958d0a1 100644
--- a/pandas/tests/series/methods/test_shift.py
+++ b/pandas/tests/series/methods/test_shift.py
@@ -263,3 +263,13 @@ def test_shift_categorical(self):
tm.assert_index_equal(s.values.categories, sp1.values.categories)
tm.assert_index_equal(s.values.categories, sn2.values.categories)
+
+ def test_shift_dt64values_int_fill_deprecated(self):
+ # GH#31971
+ ser = pd.Series([pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")])
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = ser.shift(1, fill_value=0)
+
+ expected = pd.Series([pd.Timestamp(0), ser[0]])
+ tm.assert_series_equal(result, expected)
| Backport PR #32591: REG: dt64 shift with integer fill_value | https://api.github.com/repos/pandas-dev/pandas/pulls/32647 | 2020-03-12T02:26:57Z | 2020-03-12T04:26:18Z | 2020-03-12T04:26:18Z | 2020-03-12T04:26:18Z |
MultiIndex union/intersection with non-object other | diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 5bffc4ec552af..d30765217390f 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3243,9 +3243,13 @@ def union(self, other, sort=None):
# TODO: Index.union returns other when `len(self)` is 0.
- uniq_tuples = lib.fast_unique_multiple(
- [self._values, other._ndarray_values], sort=sort
- )
+ if not is_object_dtype(other.dtype):
+ raise NotImplementedError(
+ "Can only union MultiIndex with MultiIndex or Index of tuples, "
+ "try mi.to_flat_index().union(other) instead."
+ )
+
+ uniq_tuples = lib.fast_unique_multiple([self._values, other._values], sort=sort)
return MultiIndex.from_arrays(
zip(*uniq_tuples), sortorder=0, names=result_names
@@ -3279,8 +3283,18 @@ def intersection(self, other, sort=False):
if self.equals(other):
return self
+ if not is_object_dtype(other.dtype):
+ # The intersection is empty
+ # TODO: we have no tests that get here
+ return MultiIndex(
+ levels=self.levels,
+ codes=[[]] * self.nlevels,
+ names=result_names,
+ verify_integrity=False,
+ )
+
lvals = self._values
- rvals = other._ndarray_values
+ rvals = other._values
uniq_tuples = None # flag whether _inner_indexer was succesful
if self.is_monotonic and other.is_monotonic:
diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py
index d7d0ff4c411aa..b24f56afee376 100644
--- a/pandas/tests/indexes/multi/test_setops.py
+++ b/pandas/tests/indexes/multi/test_setops.py
@@ -246,6 +246,7 @@ def test_union(idx, sort):
the_union = idx.union(idx[:0], sort=sort)
assert the_union is idx
+ # FIXME: dont leave commented-out
# won't work in python 3
# tuples = _index.values
# result = _index[:4] | tuples[4:]
@@ -282,6 +283,7 @@ def test_intersection(idx, sort):
expected = idx[:0]
assert empty.equals(expected)
+ # FIXME: dont leave commented-out
# can't do in python 3
# tuples = _index.values
# result = _index & tuples
@@ -351,6 +353,17 @@ def test_union_sort_other_incomparable_sort():
idx.union(idx[:1], sort=True)
+def test_union_non_object_dtype_raises():
+ # GH#32646 raise NotImplementedError instead of less-informative error
+ mi = pd.MultiIndex.from_product([["a", "b"], [1, 2]])
+
+ idx = mi.levels[1]
+
+ msg = "Can only union MultiIndex with MultiIndex or Index of tuples"
+ with pytest.raises(NotImplementedError, match=msg):
+ mi.union(idx)
+
+
@pytest.mark.parametrize(
"method", ["union", "intersection", "difference", "symmetric_difference"]
)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
ATM if we call MultiIndex.union with e.g. a Float64Index, we get `ValueError: Buffer dtype mismatch, expected 'Python object' but got 'double'` from `lib.fast_unique_multiple`. This PR changes that to raise NotImplementedError with a reasonable message, but we could alternatively return `self.to_flat_index().union(other)`
I prefer making the user do to_flat_index on their own because this seems like something that would often be reached by accident. | https://api.github.com/repos/pandas-dev/pandas/pulls/32646 | 2020-03-12T01:38:42Z | 2020-03-17T01:37:11Z | 2020-03-17T01:37:11Z | 2020-03-17T01:39:37Z |
Simplified get_blkno_indexers | diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx
index 7f861e587e637..5545302fcbfc4 100644
--- a/pandas/_libs/internals.pyx
+++ b/pandas/_libs/internals.pyx
@@ -1,4 +1,5 @@
import cython
+from collections import defaultdict
from cython import Py_ssize_t
from cpython.slice cimport PySlice_GetIndicesEx
@@ -373,8 +374,7 @@ def get_blkno_indexers(int64_t[:] blknos, bint group=True):
Py_ssize_t i, start, stop, n, diff
object blkno
- list group_order
- dict group_dict
+ object group_dict = defaultdict(list)
int64_t[:] res_view
n = blknos.shape[0]
@@ -395,28 +395,16 @@ def get_blkno_indexers(int64_t[:] blknos, bint group=True):
yield cur_blkno, slice(start, n)
else:
- group_order = []
- group_dict = {}
-
for i in range(1, n):
if blknos[i] != cur_blkno:
- if cur_blkno not in group_dict:
- group_order.append(cur_blkno)
- group_dict[cur_blkno] = [(start, i)]
- else:
- group_dict[cur_blkno].append((start, i))
+ group_dict[cur_blkno].append((start, i))
start = i
cur_blkno = blknos[i]
- if cur_blkno not in group_dict:
- group_order.append(cur_blkno)
- group_dict[cur_blkno] = [(start, n)]
- else:
- group_dict[cur_blkno].append((start, n))
+ group_dict[cur_blkno].append((start, n))
- for blkno in group_order:
- slices = group_dict[blkno]
+ for blkno, slices in group_dict.items():
if len(slices) == 1:
yield blkno, slice(slices[0][0], slices[0][1])
else:
| This function is the last that appears to be throwing warnings in #32163
This PR doesn't solve that, but simplifies the logic to make it easier to grok | https://api.github.com/repos/pandas-dev/pandas/pulls/32645 | 2020-03-12T00:26:31Z | 2020-03-15T00:35:24Z | 2020-03-15T00:35:24Z | 2023-04-12T20:15:53Z |
CLN: Deduplicate show_versions | diff --git a/doc/source/install.rst b/doc/source/install.rst
index 1c1f0c1d4cf8e..ee4b36f898e31 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -286,6 +286,7 @@ psycopg2 PostgreSQL engine for sqlalchemy
pyarrow 0.9.0 Parquet and feather reading / writing
pymysql MySQL engine for sqlalchemy
pyreadstat SPSS files (.sav) reading
+pytables 3.4.2 HDF5 reading / writing
qtpy Clipboard I/O
s3fs 0.0.8 Amazon S3 access
xarray 0.8.2 pandas-like API for N-dimensional data
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index 4a7b8c4e88649..875edb3d3f1dd 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -19,6 +19,7 @@
"s3fs": "0.0.8",
"scipy": "0.19.0",
"sqlalchemy": "1.1.4",
+ "tables": "3.4.2",
"xarray": "0.8.2",
"xlrd": "1.1.0",
"xlwt": "1.2.0",
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 983b1286eec91..79d6d8563a162 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -19,6 +19,7 @@
from pandas._libs import lib, writers as libwriters
from pandas._libs.tslibs import timezones
+from pandas.compat._optional import import_optional_dependency
from pandas.errors import PerformanceWarning
from pandas.core.dtypes.common import (
@@ -448,11 +449,7 @@ def __init__(self, path, mode=None, complevel=None, complib=None,
if 'format' in kwargs:
raise ValueError('format is not a defined argument for HDFStore')
- try:
- import tables # noqa
- except ImportError as ex: # pragma: no cover
- raise ImportError('HDFStore requires PyTables, "{ex!s}" problem '
- 'importing'.format(ex=ex))
+ tables = import_optional_dependency("tables")
if complib is not None and complib not in tables.filters.all_complibs:
raise ValueError(
diff --git a/pandas/tests/io/test_pytables_missing.py b/pandas/tests/io/test_pytables_missing.py
new file mode 100644
index 0000000000000..4ceb80889c989
--- /dev/null
+++ b/pandas/tests/io/test_pytables_missing.py
@@ -0,0 +1,14 @@
+import pytest
+
+import pandas.util._test_decorators as td
+
+import pandas as pd
+import pandas.util.testing as tm
+
+
+@td.skip_if_installed("tables")
+def test_pytables_raises():
+ df = pd.DataFrame({"A": [1, 2]})
+ with pytest.raises(ImportError, match="tables"):
+ with tm.ensure_clean("foo.h5") as path:
+ df.to_hdf(path, "df")
diff --git a/pandas/util/_print_versions.py b/pandas/util/_print_versions.py
index a5c86c2cc80b3..5e2e013c4afcc 100644
--- a/pandas/util/_print_versions.py
+++ b/pandas/util/_print_versions.py
@@ -1,5 +1,4 @@
import codecs
-import importlib
import locale
import os
import platform
@@ -7,6 +6,9 @@
import subprocess
import sys
+from pandas.compat._optional import (
+ VERSIONS, _get_version, import_optional_dependency)
+
def get_sys_info():
"Returns system information as a dict"
@@ -58,60 +60,49 @@ def get_sys_info():
def show_versions(as_json=False):
sys_info = get_sys_info()
-
deps = [
- # (MODULE_NAME, f(mod) -> mod version)
- ("pandas", lambda mod: mod.__version__),
- ("pytest", lambda mod: mod.__version__),
- ("pip", lambda mod: mod.__version__),
- ("setuptools", lambda mod: mod.__version__),
- ("Cython", lambda mod: mod.__version__),
- ("numpy", lambda mod: mod.version.version),
- ("scipy", lambda mod: mod.version.version),
- ("pyarrow", lambda mod: mod.__version__),
- ("xarray", lambda mod: mod.__version__),
- ("IPython", lambda mod: mod.__version__),
- ("sphinx", lambda mod: mod.__version__),
- ("patsy", lambda mod: mod.__version__),
- ("dateutil", lambda mod: mod.__version__),
- ("pytz", lambda mod: mod.VERSION),
- ("blosc", lambda mod: mod.__version__),
- ("bottleneck", lambda mod: mod.__version__),
- ("tables", lambda mod: mod.__version__),
- ("numexpr", lambda mod: mod.__version__),
- ("feather", lambda mod: mod.__version__),
- ("matplotlib", lambda mod: mod.__version__),
- ("openpyxl", lambda mod: mod.__version__),
- ("xlrd", lambda mod: mod.__VERSION__),
- ("xlwt", lambda mod: mod.__VERSION__),
- ("xlsxwriter", lambda mod: mod.__version__),
- ("lxml.etree", lambda mod: mod.__version__),
- ("bs4", lambda mod: mod.__version__),
- ("html5lib", lambda mod: mod.__version__),
- ("sqlalchemy", lambda mod: mod.__version__),
- ("pymysql", lambda mod: mod.__version__),
- ("psycopg2", lambda mod: mod.__version__),
- ("jinja2", lambda mod: mod.__version__),
- ("s3fs", lambda mod: mod.__version__),
- ("fastparquet", lambda mod: mod.__version__),
- ("pandas_gbq", lambda mod: mod.__version__),
- ("pandas_datareader", lambda mod: mod.__version__),
- ("gcsfs", lambda mod: mod.__version__),
+ 'pandas',
+ # required
+ 'numpy',
+ 'pytz',
+ 'dateutil',
+ # install / build,
+ 'pip',
+ 'setuptools',
+ 'Cython',
+ # test
+ 'pytest',
+ 'hypothesis',
+ # docs
+ "sphinx",
+ # Other, need a min version
+ "blosc",
+ "feather",
+ "xlsxwriter",
+ "lxml.etree",
+ "html5lib",
+ "pymysql",
+ "psycopg2",
+ "jinja2",
+ # Other, not imported.
+ "IPython",
+ "pandas_datareader",
]
- deps_blob = list()
- for (modname, ver_f) in deps:
- try:
- if modname in sys.modules:
- mod = sys.modules[modname]
- else:
- mod = importlib.import_module(modname)
- ver = ver_f(mod)
- deps_blob.append((modname, ver))
- except ImportError:
- deps_blob.append((modname, None))
+ deps.extend(list(VERSIONS))
+ deps_blob = []
- if (as_json):
+ for modname in deps:
+ mod = import_optional_dependency(modname,
+ raise_on_missing=False,
+ on_version="ignore")
+ if mod:
+ ver = _get_version(mod)
+ else:
+ ver = None
+ deps_blob.append((modname, ver))
+
+ if as_json:
try:
import json
except ImportError:
@@ -126,16 +117,15 @@ def show_versions(as_json=False):
json.dump(j, f, indent=2)
else:
-
+ maxlen = max(len(x) for x in deps)
+ tpl = '{{k:<{maxlen}}}: {{stat}}'.format(maxlen=maxlen)
print("\nINSTALLED VERSIONS")
print("------------------")
-
for k, stat in sys_info:
- print("{k}: {stat}".format(k=k, stat=stat))
-
+ print(tpl.format(k=k, stat=stat))
print("")
for k, stat in deps_blob:
- print("{k}: {stat}".format(k=k, stat=stat))
+ print(tpl.format(k=k, stat=stat))
def main():
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index 0cb82c0028c90..fd9c9d07a974e 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -100,6 +100,23 @@ def _skip_if_no_scipy():
safe_import('scipy.signal'))
+def skip_if_installed(
+ package: str,
+) -> MarkDecorator:
+ """
+ Skip a test if a package is installed.
+
+ Parameters
+ ----------
+ package : str
+ The name of the package.
+ """
+ return pytest.mark.skipif(
+ safe_import(package),
+ reason="Skipping because {} is installed.".format(package)
+ )
+
+
def skip_if_no(
package: str,
min_version: Optional[str] = None
| Closes #26814
The old version had special cases for numpy, scipy, and pytz. All those now provide a standard `__version__`. xlrd and xlwt are the only special ones now (`__version__`)
I messed up the minimum xlwt version in the last PR. I copied openpyxl's rather than xlwt's. That's now fixed.
I prettied up the output format a bit, to align the version numbers. Hope that 's OK.
```
INSTALLED VERSIONS
------------------
commit : cbc6edf8bfad33c8bc698a3d035b593d921b0112
python : 3.7.3.final.0
python-bits : 64
OS : Darwin
OS-release : 18.6.0
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8
pandas : 0.25.0.dev0+729.gcbc6edf8b
pytest : 4.6.2
pip : 19.1.1
setuptools : 41.0.1
Cython : 0.29.10
numpy : 1.17.0.dev0+5b06588
scipy : 1.3.0
pyarrow : 0.13.0
xarray : 0.12.1
IPython : 7.5.0
sphinx : 1.8.5
patsy : 0.5.1
dateutil : 2.7.3
pytz : 2018.5
blosc : 1.5.1
bottleneck : 1.2.1
tables : 3.5.1
numexpr : 2.6.8
feather : 0.4.0
matplotlib : 3.1.0
openpyxl : 2.5.11
xlrd : 1.1.0
xlwt : 1.3.0
xlsxwriter : 1.1.2
lxml.etree : 4.2.5
bs4 : 4.7.1
html5lib : 1.0.1
sqlalchemy : 1.2.14
pymysql : 0.9.2
psycopg2 : 2.7.6.1 (dt dec pq3 ext lo64)
jinja2 : 2.10.1
s3fs : 0.1.6
fastparquet : None
pandas_gbq : 0.10.0
pandas_datareader: None
gcsfs : 0.1.2
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/26816 | 2019-06-12T19:00:35Z | 2019-06-21T01:48:37Z | 2019-06-21T01:48:37Z | 2019-06-21T01:48:48Z |
CLN: compat.to_str -> core.dtypes.common.ensure_str | diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py
index 7036d0e1428fe..4459e66540dac 100644
--- a/pandas/compat/__init__.py
+++ b/pandas/compat/__init__.py
@@ -24,17 +24,6 @@
# found at https://bitbucket.org/gutworth/six
-def to_str(s):
- """
- Convert bytes and non-string into Python 3 str
- """
- if isinstance(s, bytes):
- s = s.decode('utf-8')
- elif not isinstance(s, str):
- s = str(s)
- return s
-
-
def set_function_name(f, name, cls):
"""
Bind the name/qualname attributes of the function
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index d0f392df70c85..2f66e9ed46aa0 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -6,12 +6,11 @@
from pandas._libs import lib, tslib, tslibs
from pandas._libs.tslibs import NaT, OutOfBoundsDatetime, Period, iNaT
-from pandas.compat import to_str
from .common import (
_INT64_DTYPE, _NS_DTYPE, _POSSIBLY_CAST_DTYPES, _TD_DTYPE, ensure_int8,
- ensure_int16, ensure_int32, ensure_int64, ensure_object, is_bool,
- is_bool_dtype, is_categorical_dtype, is_complex, is_complex_dtype,
+ ensure_int16, ensure_int32, ensure_int64, ensure_object, ensure_str,
+ is_bool, is_bool_dtype, is_categorical_dtype, is_complex, is_complex_dtype,
is_datetime64_dtype, is_datetime64_ns_dtype, is_datetime64tz_dtype,
is_datetime_or_timedelta_dtype, is_datetimelike, is_dtype_equal,
is_extension_array_dtype, is_extension_type, is_float, is_float_dtype,
@@ -1189,7 +1188,7 @@ def construct_1d_arraylike_from_scalar(value, length, dtype):
# to allow numpy to take our string as a scalar value
dtype = object
if not isna(value):
- value = to_str(value)
+ value = ensure_str(value)
subarr = np.empty(length, dtype=dtype)
subarr.fill(value)
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 52011d53d22cd..ce99d150880c6 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -1,5 +1,5 @@
""" common type operations """
-from typing import Union
+from typing import Any, Union
import warnings
import numpy as np
@@ -69,6 +69,17 @@ def ensure_float(arr):
ensure_object = algos.ensure_object
+def ensure_str(value: Union[bytes, Any]) -> str:
+ """
+ Ensure that bytes and non-strings get converted into ``str`` objects.
+ """
+ if isinstance(value, bytes):
+ value = value.decode('utf-8')
+ elif not isinstance(value, str):
+ value = str(value)
+ return value
+
+
def ensure_categorical(arr):
"""
Ensure that an array-like object is a Categorical (if not already).
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index d85a3a1ddeff0..865eab9d71eff 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -15,7 +15,7 @@
from pandas._config import config
from pandas._libs import Timestamp, iNaT, properties
-from pandas.compat import set_function_name, to_str
+from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
from pandas.util._decorators import (
@@ -24,7 +24,7 @@
from pandas.core.dtypes.cast import maybe_promote, maybe_upcast_putmask
from pandas.core.dtypes.common import (
- ensure_int64, ensure_object, is_bool, is_bool_dtype,
+ ensure_int64, ensure_object, ensure_str, is_bool, is_bool_dtype,
is_datetime64_any_dtype, is_datetime64_dtype, is_datetime64tz_dtype,
is_dict_like, is_extension_array_dtype, is_integer, is_list_like,
is_number, is_numeric_dtype, is_object_dtype, is_period_arraylike,
@@ -4564,12 +4564,12 @@ def filter(self, items=None, like=None, regex=None, axis=None):
**{name: [r for r in items if r in labels]})
elif like:
def f(x):
- return like in to_str(x)
+ return like in ensure_str(x)
values = labels.map(f)
return self.loc(axis=axis)[values]
elif regex:
def f(x):
- return matcher.search(to_str(x)) is not None
+ return matcher.search(ensure_str(x)) is not None
matcher = re.compile(regex)
values = labels.map(f)
return self.loc(axis=axis)[values]
diff --git a/pandas/io/json/json.py b/pandas/io/json/json.py
index 20bed9bff7383..7bafa15bb1979 100644
--- a/pandas/io/json/json.py
+++ b/pandas/io/json/json.py
@@ -6,10 +6,9 @@
import pandas._libs.json as json
from pandas._libs.tslibs import iNaT
-from pandas.compat import to_str
from pandas.errors import AbstractMethodError
-from pandas.core.dtypes.common import is_period_dtype
+from pandas.core.dtypes.common import ensure_str, is_period_dtype
from pandas import DataFrame, MultiIndex, Series, isna, to_datetime
from pandas.core.reshape.concat import concat
@@ -545,8 +544,7 @@ def read(self):
if self.lines and self.chunksize:
obj = concat(self)
elif self.lines:
-
- data = to_str(self.data)
+ data = ensure_str(self.data)
obj = self._get_object_parser(
self._combine_lines(data.split('\n'))
)
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index bcbdd80865360..2daed630f1c69 100755
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -17,16 +17,16 @@
import pandas._libs.ops as libops
import pandas._libs.parsers as parsers
from pandas._libs.tslibs import parsing
-import pandas.compat as compat
from pandas.errors import (
AbstractMethodError, EmptyDataError, ParserError, ParserWarning)
from pandas.util._decorators import Appender
from pandas.core.dtypes.cast import astype_nansafe
from pandas.core.dtypes.common import (
- ensure_object, is_bool_dtype, is_categorical_dtype, is_dtype_equal,
- is_extension_array_dtype, is_float, is_integer, is_integer_dtype,
- is_list_like, is_object_dtype, is_scalar, is_string_dtype, pandas_dtype)
+ ensure_object, ensure_str, is_bool_dtype, is_categorical_dtype,
+ is_dtype_equal, is_extension_array_dtype, is_float, is_integer,
+ is_integer_dtype, is_list_like, is_object_dtype, is_scalar,
+ is_string_dtype, pandas_dtype)
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.missing import isna
@@ -1494,7 +1494,7 @@ def extract(r):
# If we find unnamed columns all in a single
# level, then our header was too long.
for n in range(len(columns[0])):
- if all(compat.to_str(c[n]) in self.unnamed_cols for c in columns):
+ if all(ensure_str(col[n]) in self.unnamed_cols for col in columns):
raise ParserError(
"Passed header=[{header}] are too many rows for this "
"multi_index of columns"
| ``compat.to_str`` is useful to have in cases where an object might be a ``bytes`` object, so it's moved to ``core.dtypes.common`` and renamed to ``ensure_str``.
| https://api.github.com/repos/pandas-dev/pandas/pulls/26811 | 2019-06-12T13:50:30Z | 2019-06-12T14:56:56Z | 2019-06-12T14:56:56Z | 2019-06-12T14:57:01Z |
DOC: Fixing some more warnings | diff --git a/doc/source/user_guide/advanced.rst b/doc/source/user_guide/advanced.rst
index 0e68cddde8bc7..3235e3c2a8b2e 100644
--- a/doc/source/user_guide/advanced.rst
+++ b/doc/source/user_guide/advanced.rst
@@ -703,6 +703,8 @@ faster than fancy indexing.
%timeit arr[indexer]
%timeit arr.take(indexer, axis=0)
+.. ipython:: python
+
ser = pd.Series(arr[:, 0])
%timeit ser.iloc[indexer]
%timeit ser.take(indexer)
diff --git a/doc/source/user_guide/cookbook.rst b/doc/source/user_guide/cookbook.rst
index 538acbd7d01fa..772362cab396c 100644
--- a/doc/source/user_guide/cookbook.rst
+++ b/doc/source/user_guide/cookbook.rst
@@ -1260,24 +1260,19 @@ The `method` argument within `DataFrame.corr` can accept a callable in addition
n = len(x)
a = np.zeros(shape=(n, n))
b = np.zeros(shape=(n, n))
-
for i in range(n):
for j in range(i + 1, n):
a[i, j] = abs(x[i] - x[j])
b[i, j] = abs(y[i] - y[j])
-
a += a.T
b += b.T
-
a_bar = np.vstack([np.nanmean(a, axis=0)] * n)
b_bar = np.vstack([np.nanmean(b, axis=0)] * n)
-
A = a - a_bar - a_bar.T + np.full(shape=(n, n), fill_value=a_bar.mean())
B = b - b_bar - b_bar.T + np.full(shape=(n, n), fill_value=b_bar.mean())
cov_ab = np.sqrt(np.nansum(A * B)) / n
std_a = np.sqrt(np.sqrt(np.nansum(A**2)) / n)
std_b = np.sqrt(np.sqrt(np.nansum(B**2)) / n)
-
return cov_ab / std_a / std_b
df = pd.DataFrame(np.random.normal(size=(100, 3)))
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index 4aacb6fa1e278..725af8ef8769b 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -4703,6 +4703,7 @@ See the documentation for `pyarrow <https://arrow.apache.org/docs/python/>`__ an
Write to a parquet file.
.. ipython:: python
+ :okwarning:
df.to_parquet('example_pa.parquet', engine='pyarrow')
df.to_parquet('example_fp.parquet', engine='fastparquet')
@@ -4720,6 +4721,7 @@ Read from a parquet file.
Read only certain columns of a parquet file.
.. ipython:: python
+ :okwarning:
result = pd.read_parquet('example_fp.parquet',
engine='fastparquet', columns=['a', 'b'])
@@ -4742,6 +4744,7 @@ Serializing a ``DataFrame`` to parquet may include the implicit index as one or
more columns in the output file. Thus, this code:
.. ipython:: python
+ :okwarning:
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
df.to_parquet('test.parquet', engine='pyarrow')
@@ -4758,6 +4761,7 @@ If you want to omit a dataframe's indexes when writing, pass ``index=False`` to
:func:`~pandas.DataFrame.to_parquet`:
.. ipython:: python
+ :okwarning:
df.to_parquet('test.parquet', index=False)
diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst
index e8fb2b135fd61..417eead3a2b33 100644
--- a/doc/source/user_guide/missing_data.rst
+++ b/doc/source/user_guide/missing_data.rst
@@ -348,7 +348,8 @@ that, by default, performs linear interpolation at missing data points.
np.random.seed(123456)
idx = pd.date_range('1/1/2000', periods=100, freq='BM')
ts = pd.Series(np.random.randn(100), index=idx)
- ts[1:20] = np.nan
+ ts[1:5] = np.nan
+ ts[20:30] = np.nan
ts[60:80] = np.nan
ts = ts.cumsum()
@@ -356,6 +357,12 @@ that, by default, performs linear interpolation at missing data points.
ts
ts.count()
+ @savefig series_before_interpolate.png
+ ts.plot()
+
+.. ipython:: python
+
+ ts.interpolate()
ts.interpolate().count()
@savefig series_interpolate.png
@@ -435,9 +442,9 @@ Compare several methods:
np.random.seed(2)
- ser = pd.Series(np.arange(1, 10.1, .25)**2 + np.random.randn(37))
- bad = np.array([4, 13, 14, 15, 16, 17, 18, 20, 29])
- ser[bad] = np.nan
+ ser = pd.Series(np.arange(1, 10.1, .25) ** 2 + np.random.randn(37))
+ missing = np.array([4, 13, 14, 15, 16, 17, 18, 20, 29])
+ ser[missing] = np.nan
methods = ['linear', 'quadratic', 'cubic']
df = pd.DataFrame({m: ser.interpolate(method=m) for m in methods})
@@ -451,6 +458,7 @@ You can mix pandas' ``reindex`` and ``interpolate`` methods to interpolate
at the new values.
.. ipython:: python
+ :okexcept:
ser = pd.Series(np.sort(np.random.uniform(size=100)))
@@ -476,6 +484,7 @@ filled since the last valid observation:
ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan,
np.nan, 13, np.nan, np.nan])
+ ser
# fill all consecutive values in a forward direction
ser.interpolate()
diff --git a/doc/source/whatsnew/v0.17.0.rst b/doc/source/whatsnew/v0.17.0.rst
index c53fee42548e9..8a3f87e8488ca 100644
--- a/doc/source/whatsnew/v0.17.0.rst
+++ b/doc/source/whatsnew/v0.17.0.rst
@@ -5,10 +5,6 @@ v0.17.0 (October 9, 2015)
{{ header }}
-.. ipython:: python
- :suppress:
-
-
This is a major release from 0.16.2 and includes a small number of API changes, several new features,
enhancements, and performance improvements along with a large number of bug fixes. We recommend that all
diff --git a/doc/source/whatsnew/v0.17.1.rst b/doc/source/whatsnew/v0.17.1.rst
index 233414dae957d..c4dc442bd7354 100644
--- a/doc/source/whatsnew/v0.17.1.rst
+++ b/doc/source/whatsnew/v0.17.1.rst
@@ -5,10 +5,6 @@ v0.17.1 (November 21, 2015)
{{ header }}
-.. ipython:: python
- :suppress:
-
-
.. note::
| - [X] closes #26788, xref #24173
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Fixing some more warnings in the doc build, and small improvements to the interpolation doc.
CC: @jorisvandenbossche | https://api.github.com/repos/pandas-dev/pandas/pulls/26810 | 2019-06-12T13:13:20Z | 2019-06-14T06:45:13Z | 2019-06-14T06:45:13Z | 2019-06-14T06:48:32Z |
REF: Consistent optional dependency handling | diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst
index ba0558cff07eb..135fb55cfce50 100644
--- a/doc/source/development/contributing.rst
+++ b/doc/source/development/contributing.rst
@@ -499,6 +499,21 @@ as possible to avoid mass breakages.
Additional standards are outlined on the `code style wiki
page <https://github.com/pandas-dev/pandas/wiki/Code-Style-and-Conventions>`_.
+Optional dependencies
+---------------------
+
+Optional dependencies (e.g. matplotlib) should be imported with the private helper
+``pandas.compat._optional.import_optional_dependency``. This ensures a
+consistent error message when the dependency is not met.
+
+All methods using an optional dependency should include a test asserting that an
+``ImportError`` is raised when the optional dependency is not found. This test
+should be skipped if the library is present.
+
+All optional dependencies should be documented in
+:ref:`install.optional_dependencies` and the minimum required version should be
+set in the ``pandas.compat._optional.VERSIONS`` dict.
+
C (cpplint)
~~~~~~~~~~~
diff --git a/doc/source/install.rst b/doc/source/install.rst
index 98443ede2e965..2b8352ff9a1a5 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -252,87 +252,69 @@ Recommended Dependencies
Optional Dependencies
~~~~~~~~~~~~~~~~~~~~~
-* `Cython <http://www.cython.org>`__: Only necessary to build development
- version. Version 0.28.2 or higher.
-* `SciPy <http://www.scipy.org>`__: miscellaneous statistical functions, Version 0.19.0 or higher
-* `xarray <http://xarray.pydata.org>`__: pandas like handling for > 2 dims. Version 0.8.2 or higher is recommended.
-* `PyTables <http://www.pytables.org>`__: necessary for HDF5-based storage, Version 3.4.2 or higher
-* `pyarrow <http://arrow.apache.org/docs/python/>`__ (>= 0.9.0): necessary for feather-based storage.
-* `Apache Parquet <https://parquet.apache.org/>`__, either `pyarrow <http://arrow.apache.org/docs/python/>`__ (>= 0.9.0) or `fastparquet <https://fastparquet.readthedocs.io/en/latest>`__ (>= 0.2.1) for parquet-based storage. The `snappy <https://pypi.org/project/python-snappy>`__ and `brotli <https://pypi.org/project/brotlipy>`__ are available for compression support.
-* `SQLAlchemy <http://www.sqlalchemy.org>`__: for SQL database support. Version 1.1.4 or higher recommended. Besides SQLAlchemy, you also need a database specific driver. You can find an overview of supported drivers for each SQL dialect in the `SQLAlchemy docs <http://docs.sqlalchemy.org/en/latest/dialects/index.html>`__. Some common drivers are:
-
- * `psycopg2 <http://initd.org/psycopg/>`__: for PostgreSQL
- * `pymysql <https://github.com/PyMySQL/PyMySQL>`__: for MySQL.
- * `SQLite <https://docs.python.org/3/library/sqlite3.html>`__: for SQLite, this is included in Python's standard library by default.
-
-* `matplotlib <http://matplotlib.org/>`__: for plotting, Version 2.2.2 or higher.
-* For Excel I/O:
-
- * `xlrd/xlwt <http://www.python-excel.org/>`__: Excel reading (xlrd), version 1.0.0 or higher required, and writing (xlwt)
- * `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`__: openpyxl version 2.4.0
- for writing .xlsx files (xlrd >= 1.0.0)
- * `XlsxWriter <https://pypi.org/project/XlsxWriter>`__: Alternative Excel writer
-
-* `Jinja2 <http://jinja.pocoo.org/>`__: Template engine for conditional HTML formatting.
-* `s3fs <http://s3fs.readthedocs.io/>`__: necessary for Amazon S3 access (s3fs >= 0.0.8).
-* `blosc <https://pypi.org/project/blosc>`__: for msgpack compression using ``blosc``
-* `gcsfs <http://gcsfs.readthedocs.io/>`__: necessary for Google Cloud Storage access (gcsfs >= 0.1.0).
-* One of
- `qtpy <https://github.com/spyder-ide/qtpy>`__ (requires PyQt or PySide),
- `PyQt5 <https://www.riverbankcomputing.com/software/pyqt/download5>`__,
- `PyQt4 <http://www.riverbankcomputing.com/software/pyqt/download>`__,
- `xsel <http://www.vergenet.net/~conrad/software/xsel/>`__, or
- `xclip <https://github.com/astrand/xclip/>`__: necessary to use
- :func:`~pandas.read_clipboard`. Most package managers on Linux distributions will have ``xclip`` and/or ``xsel`` immediately available for installation.
-* `pandas-gbq
- <https://pandas-gbq.readthedocs.io/en/latest/install.html#dependencies>`__:
- for Google BigQuery I/O. (pandas-gbq >= 0.8.0)
-
-* One of the following combinations of libraries is needed to use the
- top-level :func:`~pandas.read_html` function:
-
- .. versionchanged:: 0.23.0
-
- .. note::
-
- If using BeautifulSoup4 a minimum version of 4.4.1 is required
-
- * `BeautifulSoup4`_ and `html5lib`_ (Any recent version of `html5lib`_ is
- okay.)
- * `BeautifulSoup4`_ and `lxml`_
- * `BeautifulSoup4`_ and `html5lib`_ and `lxml`_
- * Only `lxml`_, although see :ref:`HTML Table Parsing <io.html.gotchas>`
- for reasons as to why you should probably **not** take this approach.
-
- .. warning::
-
- * if you install `BeautifulSoup4`_ you must install either
- `lxml`_ or `html5lib`_ or both.
- :func:`~pandas.read_html` will **not** work with *only*
- `BeautifulSoup4`_ installed.
- * You are highly encouraged to read :ref:`HTML Table Parsing gotchas <io.html.gotchas>`.
- It explains issues surrounding the installation and
- usage of the above three libraries.
-
- .. note::
-
- * if you're on a system with ``apt-get`` you can do
-
- .. code-block:: sh
-
- sudo apt-get build-dep python-lxml
-
- to get the necessary dependencies for installation of `lxml`_. This
- will prevent further headaches down the line.
-
+Pandas has many optional dependencies that are only used for specific methods.
+For example, :func:`pandas.read_hdf` requires the ``pytables`` package. If the
+optional dependency is not installed, pandas will raise an ``ImportError`` when
+the method requiring that dependency is called.
+
+========================= ================== =============================================================
+Dependency Minimum Version Notes
+========================= ================== =============================================================
+BeautifulSoup4 4.4.1 HTML parser for read_html (see :ref:`note <optional_html>`)
+Jinja2 Conditional formatting with DataFrame.style
+PyQt4 Clipboard I/O
+PyQt5 Clipboard I/O
+PyTables 3.4.2 HDF5-based reading / writing
+SQLAlchemy 1.1.4 SQL support for databases other than sqlite
+SciPy 0.19.0 Miscellaneous statistical functions
+XLsxWriter Excel writing
+blosc Compression for msgpack
+fastparquet 0.2.1 Parquet reading / writing
+gcsfs 0.1.0 Google Cloud Storage access
+html5lib HTML parser for read_html (see :ref:`note <optional_html>`)
+lxml HTML parser for read_html (see :ref:`note <optional_html>`)
+matplotlib 2.2.2 Visualization
+openpyxl 2.4.0 Reading / writing for xlsx files
+pandas-gbq 0.8.0 Google Big Query access
+psycopg2 PostgreSQL engine for sqlalchemy
+pyarrow 0.9.0 Parquet and feather reading / writing
+pymysql MySQL engine for sqlalchemy
+qtpy Clipboard I/O
+s3fs 0.0.8 Amazon S3 access
+xarray 0.8.2 pandas-like API for N-dimensional data
+xclip Clipboard I/O on linux
+xlrd 1.0.0 Excel reading
+xlwt 2.4.0 Excel writing
+xsel Clipboard I/O on linux
+zlib Compression for msgpack
+========================= ================== =============================================================
+
+.. _optional_html:
+
+Optional Dependencies for Parsing HTML
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+One of the following combinations of libraries is needed to use the
+top-level :func:`~pandas.read_html` function:
+
+.. versionchanged:: 0.23.0
+
+* `BeautifulSoup4`_ and `html5lib`_
+* `BeautifulSoup4`_ and `lxml`_
+* `BeautifulSoup4`_ and `html5lib`_ and `lxml`_
+* Only `lxml`_, although see :ref:`HTML Table Parsing <io.html.gotchas>`
+ for reasons as to why you should probably **not** take this approach.
+
+.. warning::
+
+ * if you install `BeautifulSoup4`_ you must install either
+ `lxml`_ or `html5lib`_ or both.
+ :func:`~pandas.read_html` will **not** work with *only*
+ `BeautifulSoup4`_ installed.
+ * You are highly encouraged to read :ref:`HTML Table Parsing gotchas <io.html.gotchas>`.
+ It explains issues surrounding the installation and
+ usage of the above three libraries.
.. _html5lib: https://github.com/html5lib/html5lib-python
.. _BeautifulSoup4: http://www.crummy.com/software/BeautifulSoup
.. _lxml: http://lxml.de
-
-.. note::
-
- Without the optional dependencies, many useful features will not
- work. Hence, it is highly recommended that you install these. A packaged
- distribution like `Anaconda <http://docs.continuum.io/anaconda/>`__, `ActivePython <https://www.activestate.com/activepython/downloads>`__ (version 2.7 or 3.5), or `Enthought Canopy
- <http://enthought.com/products/canopy>`__ may be worth considering.
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
new file mode 100644
index 0000000000000..a3c0e6691dd22
--- /dev/null
+++ b/pandas/compat/_optional.py
@@ -0,0 +1,115 @@
+import distutils.version
+import importlib
+import types
+from typing import Optional
+import warnings
+
+# Update install.rst when updating versions!
+
+VERSIONS = {
+ "bs4": "4.4.1",
+ "bottleneck": "1.2.1",
+ "fastparquet": "0.2.1",
+ "gcsfs": "0.1.0",
+ "matplotlib": "2.2.2",
+ "numexpr": "2.6.2",
+ "openpyxl": "2.4.0",
+ "pandas_gbq": "0.8.0",
+ "pyarrow": "0.9.0",
+ "pytables": "3.4.2",
+ "s3fs": "0.0.8",
+ "scipy": "0.19.0",
+ "sqlalchemy": "1.1.4",
+ "xarray": "0.8.2",
+ "xlrd": "1.0.0",
+ "xlwt": "2.4.0",
+}
+
+message = (
+ "Missing optional dependency '{name}'. {extra} "
+ "Use pip or conda to install {name}."
+)
+version_message = (
+ "Pandas requires version '{minimum_version}' or newer of '{name}' "
+ "(version '{actual_version}' currently installed)."
+)
+
+
+def _get_version(module: types.ModuleType) -> str:
+ version = getattr(module, '__version__', None)
+ if version is None:
+ # xlrd uses a capitalized attribute name
+ version = getattr(module, '__VERSION__', None)
+
+ if version is None:
+ raise ImportError(
+ "Can't determine version for {}".format(module.__name__)
+ )
+ return version
+
+
+def import_optional_dependency(
+ name: str,
+ extra: str = "",
+ raise_on_missing: bool = True,
+ on_version: str = "raise",
+) -> Optional[types.ModuleType]:
+ """
+ Import an optional dependency.
+
+ By default, if a dependency is missing an ImportError with a nice
+ message will be raised. If a dependency is present, but too old,
+ we raise.
+
+ Parameters
+ ----------
+ name : str
+ The module name. This should be top-level only, so that the
+ version may be checked.
+ extra : str
+ Additional text to include in the ImportError message.
+ raise_on_missing : bool, default True
+ Whether to raise if the optional dependency is not found.
+ When False and the module is not present, None is returned.
+ on_version : str {'raise', 'warn'}
+ What to do when a dependency's version is too old.
+
+ * raise : Raise an ImportError
+ * warn : Warn that the version is too old. Returns None
+ * ignore: Return the module, even if the version is too old.
+ It's expected that users validate the version locally when
+ using ``on_version="ignore"`` (see. ``io/html.py``)
+
+ Returns
+ -------
+ maybe_module : Optional[ModuleType]
+ The imported module, when found and the version is correct.
+ None is returned when the package is not found and `raise_on_missing`
+ is False, or when the package's version is too old and `on_version`
+ is ``'warn'``.
+ """
+ try:
+ module = importlib.import_module(name)
+ except ImportError:
+ if raise_on_missing:
+ raise ImportError(message.format(name=name, extra=extra)) from None
+ else:
+ return None
+
+ minimum_version = VERSIONS.get(name)
+ if minimum_version:
+ version = _get_version(module)
+ if distutils.version.LooseVersion(version) < minimum_version:
+ assert on_version in {"warn", "raise", "ignore"}
+ msg = version_message.format(
+ minimum_version=minimum_version,
+ name=name,
+ actual_version=version,
+ )
+ if on_version == "warn":
+ warnings.warn(msg, UserWarning)
+ return None
+ elif on_version == "raise":
+ raise ImportError(msg)
+
+ return module
diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py
index 926ed6a829a6d..ca6e2c04f5a69 100644
--- a/pandas/core/arrays/sparse.py
+++ b/pandas/core/arrays/sparse.py
@@ -15,6 +15,7 @@
from pandas._libs.sparse import BlockIndex, IntIndex, SparseIndex
from pandas._libs.tslibs import NaT
import pandas.compat as compat
+from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
from pandas.errors import PerformanceWarning
@@ -2205,10 +2206,8 @@ def to_coo(self):
float32. By numpy.find_common_type convention, mixing int64 and
and uint64 will result in a float64 dtype.
"""
- try:
- from scipy.sparse import coo_matrix
- except ImportError:
- raise ImportError('Scipy is not installed')
+ import_optional_dependency("scipy")
+ from scipy.sparse import coo_matrix
dtype = find_common_type(self._parent.dtypes)
if isinstance(dtype, SparseDtype):
diff --git a/pandas/core/computation/check.py b/pandas/core/computation/check.py
index c9b68661fd596..fc6b9a2522824 100644
--- a/pandas/core/computation/check.py
+++ b/pandas/core/computation/check.py
@@ -1,24 +1,11 @@
-from distutils.version import LooseVersion
-import warnings
-
-_NUMEXPR_INSTALLED = False
-_MIN_NUMEXPR_VERSION = "2.6.2"
-_NUMEXPR_VERSION = None
-
-try:
- import numexpr as ne
- ver = LooseVersion(ne.__version__)
- _NUMEXPR_INSTALLED = ver >= LooseVersion(_MIN_NUMEXPR_VERSION)
- _NUMEXPR_VERSION = ver
-
- if not _NUMEXPR_INSTALLED:
- warnings.warn(
- "The installed version of numexpr {ver} is not supported "
- "in pandas and will be not be used\nThe minimum supported "
- "version is {min_ver}\n".format(
- ver=ver, min_ver=_MIN_NUMEXPR_VERSION), UserWarning)
-
-except ImportError: # pragma: no cover
- pass
+from pandas.compat._optional import import_optional_dependency
+
+ne = import_optional_dependency("numexpr", raise_on_missing=False,
+ on_version="warn")
+_NUMEXPR_INSTALLED = ne is not None
+if _NUMEXPR_INSTALLED:
+ _NUMEXPR_VERSION = ne.__version__
+else:
+ _NUMEXPR_VERSION = None
__all__ = ['_NUMEXPR_INSTALLED', '_NUMEXPR_VERSION']
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 865eab9d71eff..903fd7ffe706a 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -16,6 +16,7 @@
from pandas._libs import Timestamp, iNaT, properties
from pandas.compat import set_function_name
+from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
from pandas.util._decorators import (
@@ -2750,15 +2751,7 @@ class (index) object 'bird' 'bird' 'mammal' 'mammal'
Data variables:
speed (date, animal) int64 350 18 361 15
"""
- try:
- import xarray
- except ImportError:
- # Give a nice error message
- raise ImportError("the xarray library is not installed\n"
- "you can install via conda\n"
- "conda install xarray\n"
- "or via pip\n"
- "pip install xarray\n")
+ xarray = import_optional_dependency("xarray")
if self.ndim == 1:
return xarray.DataArray.from_series(self)
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index b54418e9d58c3..cdb3b77567829 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -6,6 +6,7 @@
import numpy as np
from pandas._libs import algos, lib
+from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.cast import infer_dtype_from_array
from pandas.core.dtypes.common import (
@@ -246,13 +247,9 @@ def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None,
Returns an array interpolated at new_x. Add any new methods to
the list in _clean_interp_method.
"""
- try:
- from scipy import interpolate
- # TODO: Why is DatetimeIndex being imported here?
- from pandas import DatetimeIndex # noqa
- except ImportError:
- raise ImportError('{method} interpolation requires SciPy'
- .format(method=method))
+ extra = '{method} interpolation requires SciPy.'.format(method=method)
+ import_optional_dependency('scipy', extra=extra)
+ from scipy import interpolate
new_x = np.asarray(new_x)
@@ -275,12 +272,7 @@ def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None,
raise ImportError("Your version of Scipy does not support "
"PCHIP interpolation.")
elif method == 'akima':
- try:
- from scipy.interpolate import Akima1DInterpolator # noqa
- alt_methods['akima'] = _akima_interpolate
- except ImportError:
- raise ImportError("Your version of Scipy does not support "
- "Akima interpolation.")
+ alt_methods['akima'] = _akima_interpolate
interp1d_methods = ['nearest', 'zero', 'slinear', 'quadratic', 'cubic',
'polynomial']
@@ -392,11 +384,8 @@ def _akima_interpolate(xi, yi, x, der=0, axis=0):
"""
from scipy import interpolate
- try:
- P = interpolate.Akima1DInterpolator(xi, yi, axis=axis)
- except TypeError:
- # Scipy earlier than 0.17.0 missing axis
- P = interpolate.Akima1DInterpolator(xi, yi)
+ P = interpolate.Akima1DInterpolator(xi, yi, axis=axis)
+
if der == 0:
return P(x)
elif interpolate._isscalar(der):
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 56698ff3d9c35..7923e463c7719 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -1,15 +1,14 @@
-from distutils.version import LooseVersion
import functools
import itertools
import operator
from typing import Any, Optional, Tuple, Union
-import warnings
import numpy as np
from pandas._config import get_option
from pandas._libs import iNaT, lib, tslibs
+from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.cast import _int64_max, maybe_upcast_putmask
from pandas.core.dtypes.common import (
@@ -22,26 +21,10 @@
import pandas.core.common as com
-_BOTTLENECK_INSTALLED = False
-_MIN_BOTTLENECK_VERSION = '1.2.1'
-
-try:
- import bottleneck as bn
- ver = bn.__version__
- _BOTTLENECK_INSTALLED = (LooseVersion(ver) >=
- LooseVersion(_MIN_BOTTLENECK_VERSION))
-
- if not _BOTTLENECK_INSTALLED:
- warnings.warn(
- "The installed version of bottleneck {ver} is not supported "
- "in pandas and will be not be used\nThe minimum supported "
- "version is {min_ver}\n".format(
- ver=ver, min_ver=_MIN_BOTTLENECK_VERSION), UserWarning)
-
-except ImportError: # pragma: no cover
- pass
-
-
+bn = import_optional_dependency("bottleneck",
+ raise_on_missing=False,
+ on_version="warn")
+_BOTTLENECK_INSTALLED = bn is not None
_USE_BOTTLENECK = False
diff --git a/pandas/core/window.py b/pandas/core/window.py
index ab1f49aec2ad1..2b3cc4f0bf00a 100644
--- a/pandas/core/window.py
+++ b/pandas/core/window.py
@@ -11,6 +11,7 @@
import numpy as np
import pandas._libs.window as libwindow
+from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender, Substitution, cache_readonly
@@ -595,11 +596,11 @@ def validate(self):
elif is_integer(window):
if window <= 0:
raise ValueError("window must be > 0 ")
- try:
- import scipy.signal as sig
- except ImportError:
- raise ImportError('Please install scipy to generate window '
- 'weight')
+ import_optional_dependency(
+ "scipy",
+ extra="Scipy is required to generate window weight."
+ )
+ import scipy.signal as sig
if not isinstance(self.win_type, str):
raise ValueError('Invalid win_type {0}'.format(self.win_type))
diff --git a/pandas/io/excel/_util.py b/pandas/io/excel/_util.py
index ccf9a4e91e961..286efea9f120e 100644
--- a/pandas/io/excel/_util.py
+++ b/pandas/io/excel/_util.py
@@ -1,5 +1,7 @@
import warnings
+from pandas.compat._optional import import_optional_dependency
+
from pandas.core.dtypes.common import is_integer, is_list_like
_writers = {}
@@ -36,11 +38,11 @@ def _get_default_writer(ext):
The default engine for the extension.
"""
_default_writers = {'xlsx': 'openpyxl', 'xlsm': 'openpyxl', 'xls': 'xlwt'}
- try:
- import xlsxwriter # noqa
+ xlsxwriter = import_optional_dependency("xlsxwriter",
+ raise_on_missing=False,
+ on_version="warn")
+ if xlsxwriter:
_default_writers['xlsx'] = 'xlsxwriter'
- except ImportError:
- pass
return _default_writers[ext]
diff --git a/pandas/io/excel/_xlrd.py b/pandas/io/excel/_xlrd.py
index 18e751274dab9..fcc432dc7a5ad 100644
--- a/pandas/io/excel/_xlrd.py
+++ b/pandas/io/excel/_xlrd.py
@@ -1,8 +1,9 @@
from datetime import time
-from distutils.version import LooseVersion
import numpy as np
+from pandas.compat._optional import import_optional_dependency
+
from pandas.io.excel._base import _BaseExcelReader
@@ -17,16 +18,7 @@ def __init__(self, filepath_or_buffer):
Object to be parsed.
"""
err_msg = "Install xlrd >= 1.0.0 for Excel support"
-
- try:
- import xlrd
- except ImportError:
- raise ImportError(err_msg)
- else:
- if xlrd.__VERSION__ < LooseVersion("1.0.0"):
- raise ImportError(err_msg +
- ". Current version " + xlrd.__VERSION__)
-
+ import_optional_dependency("xlrd", extra=err_msg)
super().__init__(filepath_or_buffer)
@property
diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py
index 9d60349faaffe..93252f3a09ceb 100644
--- a/pandas/io/feather_format.py
+++ b/pandas/io/feather_format.py
@@ -2,6 +2,7 @@
from distutils.version import LooseVersion
+from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import deprecate_kwarg
from pandas import DataFrame, Int64Index, RangeIndex
@@ -9,30 +10,6 @@
from pandas.io.common import _stringify_path
-def _try_import():
- # since pandas is a dependency of pyarrow
- # we need to import on first use
- try:
- import pyarrow
- from pyarrow import feather
- except ImportError:
- # give a nice error message
- raise ImportError("pyarrow is not installed\n\n"
- "you can install via conda\n"
- "conda install pyarrow -c conda-forge\n"
- "or via pip\n"
- "pip install -U pyarrow\n")
-
- if LooseVersion(pyarrow.__version__) < LooseVersion('0.9.0'):
- raise ImportError("pyarrow >= 0.9.0 required for feather support\n\n"
- "you can install via conda\n"
- "conda install pyarrow -c conda-forge"
- "or via pip\n"
- "pip install -U pyarrow\n")
-
- return feather, pyarrow
-
-
def to_feather(df, path):
"""
Write a DataFrame to the feather-format
@@ -43,11 +20,14 @@ def to_feather(df, path):
path : string file path, or file-like object
"""
+ import_optional_dependency("pyarrow")
+ from pyarrow import feather
+
path = _stringify_path(path)
+
if not isinstance(df, DataFrame):
raise ValueError("feather only support IO with DataFrames")
- feather = _try_import()[0]
valid_types = {'string', 'unicode'}
# validate index
@@ -110,8 +90,9 @@ def read_feather(path, columns=None, use_threads=True):
-------
type of object stored in file
"""
+ pyarrow = import_optional_dependency("pyarrow")
+ from pyarrow import feather
- feather, pyarrow = _try_import()
path = _stringify_path(path)
if LooseVersion(pyarrow.__version__) < LooseVersion('0.11.0'):
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 1e80677e1a597..0d9b5fe4314a3 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -14,6 +14,7 @@
from pandas._config import get_option
+from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import Appender
from pandas.core.dtypes.common import is_float, is_string_like
@@ -25,14 +26,9 @@
from pandas.core.generic import _shared_docs
from pandas.core.indexing import _maybe_numeric_slice, _non_reducing_slice
-try:
- from jinja2 import (
- PackageLoader, Environment, ChoiceLoader, FileSystemLoader
- )
-except ImportError:
- raise ImportError("pandas.Styler requires jinja2. "
- "Please install with `conda install Jinja2`\n"
- "or `pip install Jinja2`")
+jinja2 = import_optional_dependency(
+ "jinja2", extra="DataFrame.style requires jinja2."
+)
try:
@@ -75,7 +71,7 @@ class Styler:
Attributes
----------
- env : Jinja2 Environment
+ env : Jinja2 jinja2.Environment
template : Jinja2 Template
loader : Jinja2 Loader
@@ -112,8 +108,8 @@ class Styler:
* Blank cells include ``blank``
* Data cells include ``data``
"""
- loader = PackageLoader("pandas", "io/formats/templates")
- env = Environment(
+ loader = jinja2.PackageLoader("pandas", "io/formats/templates")
+ env = jinja2.Environment(
loader=loader,
trim_blocks=True,
)
@@ -1231,13 +1227,13 @@ def from_custom_template(cls, searchpath, name):
MyStyler : subclass of Styler
Has the correct ``env`` and ``template`` class attributes set.
"""
- loader = ChoiceLoader([
- FileSystemLoader(searchpath),
+ loader = jinja2.ChoiceLoader([
+ jinja2.FileSystemLoader(searchpath),
cls.loader,
])
class MyStyler(cls):
- env = Environment(loader=loader)
+ env = jinja2.Environment(loader=loader)
template = env.get_template(name)
return MyStyler
diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 3a6d538b5e616..a9eff003f2249 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -1,23 +1,18 @@
""" Google BigQuery support """
+from pandas.compat._optional import import_optional_dependency
def _try_import():
# since pandas is a dependency of pandas-gbq
# we need to import on first use
- try:
- import pandas_gbq
- except ImportError:
-
- # give a nice error message
- raise ImportError("Load data from Google BigQuery\n"
- "\n"
- "the pandas-gbq package is not installed\n"
- "see the docs: https://pandas-gbq.readthedocs.io\n"
- "\n"
- "you can install via pip or conda:\n"
- "pip install pandas-gbq\n"
- "conda install pandas-gbq -c conda-forge\n")
-
+ msg = (
+ "pandas-gbq is required to load data from Google BigQuery. "
+ "See the docs: https://pandas-gbq.readthedocs.io."
+ )
+ pandas_gbq = import_optional_dependency(
+ "pandas_gbq",
+ extra=msg,
+ )
return pandas_gbq
diff --git a/pandas/io/gcs.py b/pandas/io/gcs.py
index 89dade27ad543..310a1f9f398e9 100644
--- a/pandas/io/gcs.py
+++ b/pandas/io/gcs.py
@@ -1,8 +1,10 @@
""" GCS support for remote file interactivity """
-try:
- import gcsfs
-except ImportError:
- raise ImportError("The gcsfs library is required to handle GCS files")
+from pandas.compat._optional import import_optional_dependency
+
+gcsfs = import_optional_dependency(
+ "gcsfs",
+ extra="The gcsfs library is required to handle GCS files"
+)
def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
diff --git a/pandas/io/html.py b/pandas/io/html.py
index cbdc513cfbbe3..2e2327a35f2c7 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -10,6 +10,7 @@
import re
from pandas.compat import raise_with_traceback
+from pandas.compat._optional import import_optional_dependency
from pandas.errors import AbstractMethodError, EmptyDataError
from pandas.core.dtypes.common import is_list_like
@@ -35,24 +36,17 @@ def _importers():
return
global _HAS_BS4, _HAS_LXML, _HAS_HTML5LIB
+ bs4 = import_optional_dependency("bs4", raise_on_missing=False,
+ on_version="ignore")
+ _HAS_BS4 = bs4 is not None
- try:
- import bs4 # noqa
- _HAS_BS4 = True
- except ImportError:
- pass
-
- try:
- import lxml # noqa
- _HAS_LXML = True
- except ImportError:
- pass
-
- try:
- import html5lib # noqa
- _HAS_HTML5LIB = True
- except ImportError:
- pass
+ lxml = import_optional_dependency("lxml", raise_on_missing=False,
+ on_version="ignore")
+ _HAS_LXML = lxml is not None
+
+ html5lib = import_optional_dependency("html5lib", raise_on_missing=False,
+ on_version="ignore")
+ _HAS_HTML5LIB = html5lib is not None
_IMPORTS = True
diff --git a/pandas/io/packers.py b/pandas/io/packers.py
index ead0fbd263ebf..e3d45548e4978 100644
--- a/pandas/io/packers.py
+++ b/pandas/io/packers.py
@@ -41,12 +41,12 @@
from datetime import date, datetime, timedelta
from io import BytesIO
import os
-from textwrap import dedent
import warnings
from dateutil.parser import parse
import numpy as np
+from pandas.compat._optional import import_optional_dependency
from pandas.errors import PerformanceWarning
from pandas.util._move import (
BadMove as _BadMove, move_into_mutable_buffer as _move_into_mutable_buffer)
@@ -69,47 +69,6 @@
from pandas.io.common import _stringify_path, get_filepath_or_buffer
from pandas.io.msgpack import ExtType, Packer as _Packer, Unpacker as _Unpacker
-# check which compression libs we have installed
-try:
- import zlib
-
- def _check_zlib():
- pass
-except ImportError:
- def _check_zlib():
- raise ImportError('zlib is not installed')
-
-_check_zlib.__doc__ = dedent(
- """\
- Check if zlib is installed.
-
- Raises
- ------
- ImportError
- Raised when zlib is not installed.
- """,
-)
-
-try:
- import blosc
-
- def _check_blosc():
- pass
-except ImportError:
- def _check_blosc():
- raise ImportError('blosc is not installed')
-
-_check_blosc.__doc__ = dedent(
- """\
- Check if blosc is installed.
-
- Raises
- ------
- ImportError
- Raised when blosc is not installed.
- """,
-)
-
# until we can pass this into our conversion functions,
# this is pretty hacky
compressor = None
@@ -274,7 +233,10 @@ def convert(values):
v = values.ravel()
if compressor == 'zlib':
- _check_zlib()
+ zlib = import_optional_dependency(
+ "zlib",
+ extra="zlib is required when `compress='zlib'`."
+ )
# return string arrays like they are
if dtype == np.object_:
@@ -285,7 +247,10 @@ def convert(values):
return ExtType(0, zlib.compress(v))
elif compressor == 'blosc':
- _check_blosc()
+ blosc = import_optional_dependency(
+ "blosc",
+ extra="zlib is required when `compress='blosc'`."
+ )
# return string arrays like they are
if dtype == np.object_:
@@ -319,10 +284,16 @@ def unconvert(values, dtype, compress=None):
if compress:
if compress == 'zlib':
- _check_zlib()
+ zlib = import_optional_dependency(
+ "zlib",
+ extra="zlib is required when `compress='zlib'`."
+ )
decompress = zlib.decompress
elif compress == 'blosc':
- _check_blosc()
+ blosc = import_optional_dependency(
+ "blosc",
+ extra="zlib is required when `compress='blosc'`."
+ )
decompress = blosc.decompress
else:
raise ValueError("compress must be one of 'zlib' or 'blosc'")
diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py
index 6f3d70836af47..9a846d1c7845c 100644
--- a/pandas/io/parquet.py
+++ b/pandas/io/parquet.py
@@ -1,8 +1,8 @@
""" parquet compat """
-from distutils.version import LooseVersion
from warnings import catch_warnings
+from pandas.compat._optional import import_optional_dependency
from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
@@ -75,28 +75,11 @@ def read(self, path, columns=None, **kwargs):
class PyArrowImpl(BaseImpl):
def __init__(self):
- # since pandas is a dependency of pyarrow
- # we need to import on first use
- try:
- import pyarrow
- import pyarrow.parquet
- except ImportError:
- raise ImportError(
- "pyarrow is required for parquet support\n\n"
- "you can install via conda\n"
- "conda install pyarrow -c conda-forge\n"
- "\nor via pip\n"
- "pip install -U pyarrow\n"
- )
- if LooseVersion(pyarrow.__version__) < '0.9.0':
- raise ImportError(
- "pyarrow >= 0.9.0 is required for parquet support\n\n"
- "you can install via conda\n"
- "conda install pyarrow -c conda-forge\n"
- "\nor via pip\n"
- "pip install -U pyarrow\n"
- )
-
+ pyarrow = import_optional_dependency(
+ "pyarrow",
+ extra="pyarrow is required for parquet support."
+ )
+ import pyarrow.parquet
self.api = pyarrow
def write(self, df, path, compression='snappy',
@@ -140,25 +123,10 @@ class FastParquetImpl(BaseImpl):
def __init__(self):
# since pandas is a dependency of fastparquet
# we need to import on first use
- try:
- import fastparquet
- except ImportError:
- raise ImportError(
- "fastparquet is required for parquet support\n\n"
- "you can install via conda\n"
- "conda install fastparquet -c conda-forge\n"
- "\nor via pip\n"
- "pip install -U fastparquet"
- )
- if LooseVersion(fastparquet.__version__) < '0.2.1':
- raise ImportError(
- "fastparquet >= 0.2.1 is required for parquet "
- "support\n\n"
- "you can install via conda\n"
- "conda install fastparquet -c conda-forge\n"
- "\nor via pip\n"
- "pip install -U fastparquet"
- )
+ fastparquet = import_optional_dependency(
+ "fastparquet",
+ extra="fastparquet is required for parquet support."
+ )
self.api = fastparquet
def write(self, df, path, compression='snappy', index=None,
diff --git a/pandas/io/s3.py b/pandas/io/s3.py
index 607eae27021c3..61fd984789f78 100644
--- a/pandas/io/s3.py
+++ b/pandas/io/s3.py
@@ -1,12 +1,13 @@
""" s3 support for remote file interactivity """
-try:
- import s3fs
- from botocore.exceptions import NoCredentialsError
-except ImportError:
- raise ImportError("The s3fs library is required to handle s3 files")
-
from urllib.parse import urlparse as parse_url
+from pandas.compat._optional import import_optional_dependency
+
+s3fs = import_optional_dependency(
+ "s3fs",
+ extra="The s3fs package is required to handle s3 files."
+)
+
def _strip_schema(url):
"""Returns the url without the s3:// part"""
@@ -16,6 +17,7 @@ def _strip_schema(url):
def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
compression=None, mode=None):
+ from botocore.exceptions import NoCredentialsError
if mode is None:
mode = 'rb'
diff --git a/pandas/tests/computation/test_compat.py b/pandas/tests/computation/test_compat.py
index 7cc373d06cfe1..3b01851bd39ca 100644
--- a/pandas/tests/computation/test_compat.py
+++ b/pandas/tests/computation/test_compat.py
@@ -2,8 +2,9 @@
import pytest
+from pandas.compat._optional import VERSIONS
+
import pandas as pd
-from pandas.core.computation.check import _MIN_NUMEXPR_VERSION
from pandas.core.computation.engines import _engines
import pandas.core.computation.expr as expr
@@ -15,7 +16,7 @@ def test_compat():
try:
import numexpr as ne
ver = ne.__version__
- if LooseVersion(ver) < LooseVersion(_MIN_NUMEXPR_VERSION):
+ if LooseVersion(ver) < LooseVersion(VERSIONS['numexpr']):
assert not _NUMEXPR_INSTALLED
else:
assert _NUMEXPR_INSTALLED
@@ -38,7 +39,7 @@ def testit():
pytest.skip("no numexpr")
else:
if (LooseVersion(ne.__version__) <
- LooseVersion(_MIN_NUMEXPR_VERSION)):
+ LooseVersion(VERSIONS['numexpr'])):
with pytest.raises(ImportError):
testit()
else:
diff --git a/pandas/tests/test_optional_dependency.py b/pandas/tests/test_optional_dependency.py
new file mode 100644
index 0000000000000..3916bedb8e44b
--- /dev/null
+++ b/pandas/tests/test_optional_dependency.py
@@ -0,0 +1,52 @@
+import sys
+import types
+
+import pytest
+
+from pandas.compat._optional import VERSIONS, import_optional_dependency
+
+import pandas.util.testing as tm
+
+
+def test_import_optional():
+ match = "Missing .*notapackage.* pip .* conda .* notapackage"
+ with pytest.raises(ImportError, match=match):
+ import_optional_dependency("notapackage")
+
+ result = import_optional_dependency("notapackage", raise_on_missing=False)
+ assert result is None
+
+
+def test_xlrd_version_fallback():
+ pytest.importorskip('xlrd')
+ import_optional_dependency("xlrd")
+
+
+def test_bad_version():
+ name = 'fakemodule'
+ module = types.ModuleType(name)
+ module.__version__ = "0.9.0"
+ sys.modules[name] = module
+ VERSIONS[name] = '1.0.0'
+
+ match = "Pandas requires .*1.0.0.* of .fakemodule.*'0.9.0'"
+ with pytest.raises(ImportError, match=match):
+ import_optional_dependency("fakemodule")
+
+ with tm.assert_produces_warning(UserWarning):
+ result = import_optional_dependency("fakemodule", on_version="warn")
+ assert result is None
+
+ module.__version__ = "1.0.0" # exact match is OK
+ result = import_optional_dependency("fakemodule")
+ assert result is module
+
+
+def test_no_version_raises():
+ name = 'fakemodule'
+ module = types.ModuleType(name)
+ sys.modules[name] = module
+ VERSIONS[name] = '1.0.0'
+
+ with pytest.raises(ImportError, match="Can't determine .* fakemodule"):
+ import_optional_dependency(name)
| Standardizes how we do our optional dependency checking.
1. Adds a new `import_optional_dependency` helper that handles optional importing, raising with a nice message, and warning / raising if the version is not correct.
2. Changes inline `try / except ImportError` to use `import_optional_dependency`
3. Documents all(?) optional dependencies with their minimum version.
4. Documents that this is how devs should do optional dependencies.
```pytb
>>> pd.read_gbq('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/taugspurger/sandbox/pandas/pandas/io/gbq.py", line 140, in read_gbq
pandas_gbq = _try_import()
File "/Users/taugspurger/sandbox/pandas/pandas/io/gbq.py", line 14, in _try_import
extra=msg,
File "/Users/taugspurger/sandbox/pandas/pandas/compat/_optional.py", line 82, in import_optional_dependency
raise ImportError(message.format(name=name, extra=extra)) from None
ImportError: Missing optional dependency 'pandas_gbq'. pandas-gbq is required to load data from Google BigQuery. See the docs: https://pandas-gbq.readthedocs.io. Use pip or conda to install pandas_gbq.
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/26802 | 2019-06-12T03:16:04Z | 2019-06-12T17:56:54Z | 2019-06-12T17:56:54Z | 2019-06-12T18:59:01Z |
REF: remove unreachable code in core.internals | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index f86ef40a97299..f9178959d8272 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -417,17 +417,14 @@ def split_and_operate(self, mask, f, inplace):
new_values = self.values
def make_a_block(nv, ref_loc):
- if isinstance(nv, Block):
- block = nv
- elif isinstance(nv, list):
+ if isinstance(nv, list):
+ assert len(nv) == 1, nv
+ assert isinstance(nv[0], Block)
block = nv[0]
else:
# Put back the dimension that was taken from it and make
# a block out of the result.
- try:
- nv = _block_shape(nv, ndim=self.ndim)
- except (AttributeError, NotImplementedError):
- pass
+ nv = _block_shape(nv, ndim=self.ndim)
block = self.make_block(values=nv,
placement=ref_loc)
return block
@@ -2629,10 +2626,10 @@ def f(m, v, i):
values = fn(v.ravel(), **fn_kwargs)
try:
values = values.reshape(shape)
- values = _block_shape(values, ndim=self.ndim)
except (AttributeError, NotImplementedError):
pass
+ values = _block_shape(values, ndim=self.ndim)
return values
if by_item and not self._is_single_block:
@@ -3168,8 +3165,6 @@ def _putmask_smart(v, m, n):
# n should be the length of the mask or a scalar here
if not is_list_like(n):
n = np.repeat(n, len(m))
- elif isinstance(n, np.ndarray) and n.ndim == 0: # numpy scalar
- n = np.repeat(np.array(n, ndmin=1), len(m))
# see if we are only masking values that if putted
# will work in the current dtype
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 0b63588c9f5d9..6f0e8a909d36f 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -433,11 +433,11 @@ def quantile(self, axis=0, consolidate=True, transposed=False,
self._consolidate_inplace()
def get_axe(block, qs, axes):
+ # Because Series dispatches to DataFrame, we will always have
+ # block.ndim == 2
from pandas import Float64Index
if is_list_like(qs):
ax = Float64Index(qs)
- elif block.ndim == 1:
- ax = Float64Index([qs])
else:
ax = axes[0]
return ax
@@ -1345,27 +1345,6 @@ def take(self, indexer, axis=1, verify=True, convert=True):
return self.reindex_indexer(new_axis=new_labels, indexer=indexer,
axis=axis, allow_dups=True)
- def merge(self, other, lsuffix='', rsuffix=''):
- # We assume at this point that the axes of self and other match.
- # This is only called from Panel.join, which reindexes prior
- # to calling to ensure this assumption holds.
- l, r = items_overlap_with_suffix(left=self.items, lsuffix=lsuffix,
- right=other.items, rsuffix=rsuffix)
- new_items = _concat_indexes([l, r])
-
- new_blocks = [blk.copy(deep=False) for blk in self.blocks]
-
- offset = self.shape[0]
- for blk in other.blocks:
- blk = blk.copy(deep=False)
- blk.mgr_locs = blk.mgr_locs.add(offset)
- new_blocks.append(blk)
-
- new_axes = list(self.axes)
- new_axes[0] = new_items
-
- return self.__class__(_consolidate(new_blocks), new_axes)
-
def equals(self, other):
self_axes, other_axes = self.axes, other.axes
if len(self_axes) != len(other_axes):
@@ -1553,14 +1532,6 @@ def get_values(self):
""" return a dense type view """
return np.array(self._block.to_dense(), copy=False)
- @property
- def asobject(self):
- """
- return a object dtype array. datetime/timedelta like values are boxed
- to Timestamp/Timedelta instances.
- """
- return self._block.get_values(dtype=object)
-
@property
def _can_hold_na(self):
return self._block._can_hold_na
@@ -1949,10 +1920,7 @@ def _compare_or_regex_search(a, b, regex=False):
return result
-def _concat_indexes(indexes):
- return indexes[0].append(indexes[1:])
-
-
+# TODO: this is no longer used in this module, could be moved to concat
def items_overlap_with_suffix(left, lsuffix, right, rsuffix):
"""
If two indices overlap, add suffixes to overlapping entries.
| @TomAugspurger it looks like _sparse_blockify is never hit. Is that no longer reachable? | https://api.github.com/repos/pandas-dev/pandas/pulls/26800 | 2019-06-12T02:27:29Z | 2019-06-12T11:13:53Z | 2019-06-12T11:13:53Z | 2019-06-12T14:08:25Z |
TST/REF: parametrize arithmetic tests, simplify parts of core.ops | diff --git a/pandas/core/ops.py b/pandas/core/ops.py
index 86a255321f827..0b9e56fd19556 100644
--- a/pandas/core/ops.py
+++ b/pandas/core/ops.py
@@ -1077,7 +1077,7 @@ def fill_binop(left, right, fill_value):
return left, right
-def mask_cmp_op(x, y, op, allowed_types):
+def mask_cmp_op(x, y, op):
"""
Apply the function `op` to only non-null points in x and y.
@@ -1086,16 +1086,14 @@ def mask_cmp_op(x, y, op, allowed_types):
x : array-like
y : array-like
op : binary operation
- allowed_types : class or tuple of classes
Returns
-------
result : ndarray[bool]
"""
- # TODO: Can we make the allowed_types arg unnecessary?
xrav = x.ravel()
result = np.empty(x.size, dtype=bool)
- if isinstance(y, allowed_types):
+ if isinstance(y, (np.ndarray, ABCSeries)):
yrav = y.ravel()
mask = notna(xrav) & notna(yrav)
result[mask] = op(np.array(list(xrav[mask])),
@@ -1633,39 +1631,38 @@ def _arith_method_SERIES(cls, op, special):
if op in [divmod, rdivmod] else _construct_result)
def na_op(x, y):
- import pandas.core.computation.expressions as expressions
- try:
- result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs)
- except TypeError:
- result = masked_arith_op(x, y, op)
-
- result = missing.fill_zeros(result, x, y, op_name, fill_zeros)
- return result
-
- def safe_na_op(lvalues, rvalues):
"""
- return the result of evaluating na_op on the passed in values
+ Return the result of evaluating op on the passed in values.
- try coercion to object type if the native types are not compatible
+ If native types are not compatible, try coersion to object dtype.
Parameters
----------
- lvalues : array-like
- rvalues : array-like
+ x : array-like
+ y : array-like or scalar
+
+ Returns
+ -------
+ array-like
Raises
------
- TypeError: invalid operation
+ TypeError : invalid operation
"""
+ import pandas.core.computation.expressions as expressions
try:
- with np.errstate(all='ignore'):
- return na_op(lvalues, rvalues)
- except Exception:
- if is_object_dtype(lvalues):
- return libalgos.arrmap_object(lvalues,
- lambda x: op(x, rvalues))
+ result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs)
+ except TypeError:
+ result = masked_arith_op(x, y, op)
+ except Exception: # TODO: more specific?
+ if is_object_dtype(x):
+ return libalgos.arrmap_object(x,
+ lambda val: op(val, y))
raise
+ result = missing.fill_zeros(result, x, y, op_name, fill_zeros)
+ return result
+
def wrapper(left, right):
if isinstance(right, ABCDataFrame):
return NotImplemented
@@ -1713,7 +1710,8 @@ def wrapper(left, right):
if isinstance(rvalues, ABCSeries):
rvalues = rvalues.values
- result = safe_na_op(lvalues, rvalues)
+ with np.errstate(all='ignore'):
+ result = na_op(lvalues, rvalues)
return construct_result(left, result,
index=left.index, name=res_name, dtype=None)
@@ -2136,7 +2134,6 @@ def na_op(x, y):
result = masked_arith_op(x, y, op)
result = missing.fill_zeros(result, x, y, op_name, fill_zeros)
-
return result
if op_name in _op_descriptions:
@@ -2183,7 +2180,7 @@ def na_op(x, y):
with np.errstate(invalid='ignore'):
result = op(x, y)
except TypeError:
- result = mask_cmp_op(x, y, op, (np.ndarray, ABCSeries))
+ result = mask_cmp_op(x, y, op)
return result
doc = _flex_comp_doc_FRAME.format(op_name=op_name,
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index afd29852fea7e..64b4e162483f1 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -37,6 +37,27 @@ def assert_all(obj):
# ------------------------------------------------------------------
# Comparisons
+class TestDatetime64ArrayLikeComparisons:
+ # Comparison tests for datetime64 vectors fully parametrized over
+ # DataFrame/Series/DatetimeIndex/DateteimeArray. Ideally all comparison
+ # tests will eventually end up here.
+
+ def test_compare_zerodim(self, tz_naive_fixture, box_with_array):
+ # Test comparison with zero-dimensional array is unboxed
+ tz = tz_naive_fixture
+ box = box_with_array
+ xbox = box_with_array if box_with_array is not pd.Index else np.ndarray
+ dti = date_range('20130101', periods=3, tz=tz)
+
+ other = np.array(dti.to_numpy()[0])
+
+ # FIXME: ValueError with transpose on tzaware
+ dtarr = tm.box_expected(dti, box, transpose=False)
+ result = dtarr <= other
+ expected = np.array([True, False, False])
+ expected = tm.box_expected(expected, xbox, transpose=False)
+ tm.assert_equal(result, expected)
+
class TestDatetime64DataFrameComparison:
@pytest.mark.parametrize('timestamps', [
@@ -339,17 +360,6 @@ def test_comparison_tzawareness_compat(self, op):
class TestDatetimeIndexComparisons:
- # TODO: parametrize over box
- def test_compare_zerodim(self, tz_naive_fixture):
- # Test comparison with zero-dimensional array is unboxed
- tz = tz_naive_fixture
- dti = date_range('20130101', periods=3, tz=tz)
-
- other = np.array(dti.to_numpy()[0])
- result = dti <= other
- expected = np.array([True, False, False])
- tm.assert_numpy_array_equal(result, expected)
-
# TODO: moved from tests.indexes.test_base; parametrize and de-duplicate
@pytest.mark.parametrize("op", [
operator.eq, operator.ne, operator.gt, operator.lt,
diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py
index bc1b78bf944d1..413d58d9429e7 100644
--- a/pandas/tests/arithmetic/test_period.py
+++ b/pandas/tests/arithmetic/test_period.py
@@ -20,17 +20,27 @@
# Comparisons
-class TestPeriodIndexComparisons:
+class TestPeriodArrayLikeComparisons:
+ # Comparison tests for PeriodDtype vectors fully parametrized over
+ # DataFrame/Series/PeriodIndex/PeriodArray. Ideally all comparison
+ # tests will eventually end up here.
- # TODO: parameterize over boxes
- def test_compare_zerodim(self):
+ def test_compare_zerodim(self, box_with_array):
# GH#26689 make sure we unbox zero-dimensional arrays
+ xbox = box_with_array if box_with_array is not pd.Index else np.ndarray
+
pi = pd.period_range('2000', periods=4)
other = np.array(pi.to_numpy()[0])
+ pi = tm.box_expected(pi, box_with_array)
result = pi <= other
expected = np.array([True, False, False, False])
- tm.assert_numpy_array_equal(result, expected)
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(result, expected)
+
+
+class TestPeriodIndexComparisons:
+ # TODO: parameterize over boxes
@pytest.mark.parametrize("other", ["2017", 2017])
def test_eq(self, other):
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index 047900c3d7586..22b5fd452d661 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -31,22 +31,33 @@ def get_upcast_box(box, vector):
# ------------------------------------------------------------------
# Timedelta64[ns] dtype Comparisons
-class TestTimedelta64ArrayComparisons:
- # TODO: All of these need to be parametrized over box
+class TestTimedelta64ArrayLikeComparisons:
+ # Comparison tests for timedelta64[ns] vectors fully parametrized over
+ # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all comparison
+ # tests will eventually end up here.
- def test_compare_timedelta64_zerodim(self):
+ def test_compare_timedelta64_zerodim(self, box_with_array):
# GH#26689 should unbox when comparing with zerodim array
+ box = box_with_array
+ xbox = box_with_array if box_with_array is not pd.Index else np.ndarray
+
tdi = pd.timedelta_range('2H', periods=4)
other = np.array(tdi.to_numpy()[0])
+ tdi = tm.box_expected(tdi, box)
res = tdi <= other
expected = np.array([True, False, False, False])
- tm.assert_numpy_array_equal(res, expected)
+ expected = tm.box_expected(expected, xbox)
+ tm.assert_equal(res, expected)
with pytest.raises(TypeError):
# zero-dim of wrong dtype should still raise
tdi >= np.array(4)
+
+class TestTimedelta64ArrayComparisons:
+ # TODO: All of these need to be parametrized over box
+
def test_compare_timedelta_series(self):
# regression test for GH#5963
s = pd.Series([timedelta(days=1), timedelta(days=2)])
diff --git a/pandas/tests/tseries/offsets/test_offsets_properties.py b/pandas/tests/tseries/offsets/test_offsets_properties.py
index 50be2deca4d30..271f4ceef5f49 100644
--- a/pandas/tests/tseries/offsets/test_offsets_properties.py
+++ b/pandas/tests/tseries/offsets/test_offsets_properties.py
@@ -71,7 +71,10 @@ def test_on_offset_implementations(dt, offset):
assert offset.onOffset(dt) == (compare == dt)
-@pytest.mark.xfail
+@pytest.mark.xfail(reason="res_v2 below is incorrect, needs to use the "
+ "commented-out version with tz_localize. "
+ "But with that fix in place, hypothesis then "
+ "has errors in timezone generation.")
@given(gen_yqm_offset, gen_date_range)
def test_apply_index_implementations(offset, rng):
# offset.apply_index(dti)[i] should match dti[i] + offset
@@ -82,6 +85,7 @@ def test_apply_index_implementations(offset, rng):
res = rng + offset
res_v2 = offset.apply_index(rng)
+ # res_v2 = offset.apply_index(rng.tz_localize(None)).tz_localize(rng.tz)
assert (res == res_v2).all()
assert res[0] == rng[0] + offset
@@ -93,7 +97,7 @@ def test_apply_index_implementations(offset, rng):
# TODO: Check randomly assorted entries, not just first/last
-@pytest.mark.xfail
+@pytest.mark.xfail # TODO: reason?
@given(gen_yqm_offset)
def test_shift_across_dst(offset):
# GH#18319 check that 1) timezone is correctly normalized and
| Parametrization is straightforward.
Fixing xfailed test in test_properties is straightforward
In core.ops: ATM we have a nested closure that wraps all of na_op in a try/except, but there is really only one line we want to catch. This simplifies the closure and catches only the relevant line. | https://api.github.com/repos/pandas-dev/pandas/pulls/26799 | 2019-06-12T00:29:02Z | 2019-06-25T16:11:51Z | 2019-06-25T16:11:51Z | 2019-06-25T18:00:19Z |
DOC: Document existing functionality of pandas.DataFrame.to_sql() #11886 | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 6ade69fb4ca9d..1a5b36b07e93c 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2594,13 +2594,14 @@ def to_sql(
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
chunksize : int, optional
- Rows will be written in batches of this size at a time. By default,
- all rows will be written at once.
- dtype : dict, optional
- Specifying the datatype for columns. The keys should be the column
- names and the values should be the SQLAlchemy types or strings for
- the sqlite3 legacy mode.
- method : {None, 'multi', callable}, default None
+ Specify the number of rows in each batch to be written at a time.
+ By default, all rows will be written at once.
+ dtype : dict or scalar, optional
+ Specifying the datatype for columns. If a dictionary is used, the
+ keys should be the column names and the values should be the
+ SQLAlchemy types or strings for the sqlite3 legacy mode. If a
+ scalar is provided, it will be applied to all columns.
+ method : {None, 'multi', callable}, optional
Controls the SQL insertion clause used:
* None : Uses standard SQL ``INSERT`` clause (one per row).
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 72df00fd4c5a1..44cb399336d62 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -456,14 +456,14 @@ def to_sql(
Parameters
----------
frame : DataFrame, Series
- name : string
+ name : str
Name of SQL table.
con : SQLAlchemy connectable(engine/connection) or database string URI
or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
- schema : string, default None
+ schema : str, optional
Name of SQL schema in database to write to (if database flavor
supports this). If None, use default schema (default).
if_exists : {'fail', 'replace', 'append'}, default 'fail'
@@ -472,18 +472,19 @@ def to_sql(
- append: If table exists, insert data. Create if does not exist.
index : boolean, default True
Write DataFrame index as a column.
- index_label : string or sequence, default None
+ index_label : str or sequence, optional
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
- chunksize : int, default None
- If not None, then rows will be written in batches of this size at a
- time. If None, all rows will be written at once.
- dtype : single SQLtype or dict of column name to SQL type, default None
- Optional specifying the datatype for columns. The SQL type should
- be a SQLAlchemy type, or a string for sqlite3 fallback connection.
- If all columns are of the same type, one single value can be used.
- method : {None, 'multi', callable}, default None
+ chunksize : int, optional
+ Specify the number of rows in each batch to be written at a time.
+ By default, all rows will be written at once.
+ dtype : dict or scalar, optional
+ Specifying the datatype for columns. If a dictionary is used, the
+ keys should be the column names and the values should be the
+ SQLAlchemy types or strings for the sqlite3 fallback mode. If a
+ scalar is provided, it will be applied to all columns.
+ method : {None, 'multi', callable}, optional
Controls the SQL insertion clause used:
- None : Uses standard SQL ``INSERT`` clause (one per row).
| - [x] Adds documentation for #11886
- [ ] doc build fails (may be related to #26723)
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] **What's new?** Adds documentation to an existing functionality. In fact, the functionality is documented at `pandas.io.sql.to_sql` but it's not visible [here](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html).
| https://api.github.com/repos/pandas-dev/pandas/pulls/26795 | 2019-06-11T20:36:35Z | 2019-08-30T17:09:04Z | 2019-08-30T17:09:04Z | 2019-08-31T19:15:42Z |
DOC: Fix rolling doc with win_type triang (#22268) | diff --git a/pandas/core/window.py b/pandas/core/window.py
index f332075380c79..ab1f49aec2ad1 100644
--- a/pandas/core/window.py
+++ b/pandas/core/window.py
@@ -530,8 +530,8 @@ class Window(_Window):
>>> df.rolling(2, win_type='triang').sum()
B
0 NaN
- 1 1.0
- 2 2.5
+ 1 0.5
+ 2 1.5
3 NaN
4 NaN
| - [x] closes #22268
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/26794 | 2019-06-11T19:38:13Z | 2019-06-12T01:42:51Z | 2019-06-12T01:42:50Z | 2019-07-11T15:47:51Z |
TST/CLN: use float_frame fixture to remove use of tm.getSeriesData() | diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index 172c29b951001..256ee930b4cda 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -712,10 +712,9 @@ def test_datetime64_with_index(self):
tm.assert_series_equal(df['result'], df['expected'], check_names=False)
# TODO: taken from tests.frame.test_operators, needs cleanup
- def test_frame_operators(self):
- seriesd = tm.getSeriesData()
- frame = pd.DataFrame(seriesd)
- frame2 = pd.DataFrame(seriesd, columns=['D', 'C', 'B', 'A'])
+ def test_frame_operators(self, float_frame):
+ frame = float_frame
+ frame2 = pd.DataFrame(float_frame, columns=['D', 'C', 'B', 'A'])
garbage = np.random.random(4)
colSeries = pd.Series(garbage, index=np.array(frame.columns))
diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py
index 95592f1ab3f0f..f1c8445bf98e0 100644
--- a/pandas/tests/frame/test_operators.py
+++ b/pandas/tests/frame/test_operators.py
@@ -48,9 +48,8 @@ def test_neg_raises(self, df):
with pytest.raises(TypeError):
(- df['a'])
- def test_invert(self):
- _seriesd = tm.getSeriesData()
- df = pd.DataFrame(_seriesd)
+ def test_invert(self, float_frame):
+ df = float_frame
assert_frame_equal(-(df < 0), ~(df < 0))
diff --git a/pandas/tests/groupby/conftest.py b/pandas/tests/groupby/conftest.py
index cb4fe511651ee..3b636c87dc584 100644
--- a/pandas/tests/groupby/conftest.py
+++ b/pandas/tests/groupby/conftest.py
@@ -30,21 +30,11 @@ def ts():
return tm.makeTimeSeries()
-@pytest.fixture
-def seriesd():
- return tm.getSeriesData()
-
-
@pytest.fixture
def tsd():
return tm.getTimeSeriesData()
-@pytest.fixture
-def frame(seriesd):
- return DataFrame(seriesd)
-
-
@pytest.fixture
def tsframe(tsd):
return DataFrame(tsd)
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index b7abef9357072..87b57b0609b36 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -1306,12 +1306,12 @@ def test_skip_group_keys():
assert_series_equal(result, expected)
-def test_no_nonsense_name(frame):
+def test_no_nonsense_name(float_frame):
# GH #995
- s = frame['C'].copy()
+ s = float_frame['C'].copy()
s.name = None
- result = s.groupby(frame['A']).agg(np.sum)
+ result = s.groupby(float_frame['A']).agg(np.sum)
assert result.name is None
diff --git a/pandas/tests/indexing/test_ix.py b/pandas/tests/indexing/test_ix.py
index d56894a8c1f7b..270fa8c5502a6 100644
--- a/pandas/tests/indexing/test_ix.py
+++ b/pandas/tests/indexing/test_ix.py
@@ -182,9 +182,9 @@ def test_ix_weird_slicing(self):
4: 5}})
tm.assert_frame_equal(df, expected)
- def test_ix_assign_column_mixed(self):
+ def test_ix_assign_column_mixed(self, float_frame):
# GH #1142
- df = DataFrame(tm.getSeriesData())
+ df = float_frame
df['foo'] = 'bar'
orig = df.loc[:, 'B'].copy()
diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py
index 9666bc4977587..97d51f079fb2d 100644
--- a/pandas/tests/io/formats/test_to_html.py
+++ b/pandas/tests/io/formats/test_to_html.py
@@ -287,9 +287,8 @@ def test_to_html_with_no_bold():
assert '<strong' not in result
-def test_to_html_columns_arg():
- df = DataFrame(tm.getSeriesData())
- result = df.to_html(columns=['A'])
+def test_to_html_columns_arg(float_frame):
+ result = float_frame.to_html(columns=['A'])
assert '<th>B</th>' not in result
| this PR removes 2 unnecessary fixtures from `pandas\tests\groupby\conftest.py`
and a few small changes to remove use of `tm.getSeriesData()` with a couple of exceptions:
- conftest files: `pandas\conftest.py` and `pandas\tests\frame\conftest.py` (needed for fixtures)
- `pandas\tests\frame\common.py` (this module will be removed on completion of #22471)
- `pandas\tests\io\json\test_pandas.py` (would benefit from fixturisation and access to other frame fixtures, separate PR and then maybe have a code-checks rule for `getSeriesData` in `test_*.py` files)
| https://api.github.com/repos/pandas-dev/pandas/pulls/26787 | 2019-06-11T15:42:21Z | 2019-06-11T18:31:24Z | 2019-06-11T18:31:24Z | 2019-06-12T13:59:30Z |
DOC: Fixing some doc warnings | diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst
index 79beeb0022307..92f62a812d23b 100644
--- a/doc/source/reference/series.rst
+++ b/doc/source/reference/series.rst
@@ -472,6 +472,7 @@ strings and apply several methods to it. These can be accessed like
Series.str
Series.cat
Series.dt
+ Series.sparse
Index.str
.. _api.series.cat:
diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst
index 7883814e91c94..e8fb2b135fd61 100644
--- a/doc/source/user_guide/missing_data.rst
+++ b/doc/source/user_guide/missing_data.rst
@@ -466,7 +466,7 @@ at the new values.
.. _missing_data.interp_limits:
Interpolation Limits
-^^^^^^^^^^^^^^^^^^^^
+--------------------
Like other pandas fill methods, :meth:`~DataFrame.interpolate` accepts a ``limit`` keyword
argument. Use this argument to limit the number of consecutive ``NaN`` values
diff --git a/doc/source/user_guide/reshaping.rst b/doc/source/user_guide/reshaping.rst
index 28bf46cd4c583..8ad78a68977ad 100644
--- a/doc/source/user_guide/reshaping.rst
+++ b/doc/source/user_guide/reshaping.rst
@@ -705,7 +705,7 @@ handling of NaN:
you can use ``df["cat_col"] = pd.Categorical(df["col"])`` or
``df["cat_col"] = df["col"].astype("category")``. For full docs on :class:`~pandas.Categorical`,
see the :ref:`Categorical introduction <categorical>` and the
- :ref:`API documentation <api.categorical>`.
+ :ref:`API documentation <api.arrays.categorical>`.
Examples
--------
diff --git a/doc/source/whatsnew/v0.20.0.rst b/doc/source/whatsnew/v0.20.0.rst
index 6a88a5810eca4..55b5f12d3ea70 100644
--- a/doc/source/whatsnew/v0.20.0.rst
+++ b/doc/source/whatsnew/v0.20.0.rst
@@ -396,7 +396,7 @@ IntervalIndex
pandas has gained an ``IntervalIndex`` with its own dtype, ``interval`` as well as the ``Interval`` scalar type. These allow first-class support for interval
notation, specifically as a return type for the categories in :func:`cut` and :func:`qcut`. The ``IntervalIndex`` allows some unique indexing, see the
-:ref:`docs <indexing.intervallindex>`. (:issue:`7640`, :issue:`8625`)
+:ref:`docs <advanced.intervalindex>`. (:issue:`7640`, :issue:`8625`)
.. warning::
@@ -1564,7 +1564,7 @@ Removal of prior version deprecations/changes
- The ``pandas.rpy`` module is removed. Similar functionality can be accessed
through the `rpy2 <https://rpy2.readthedocs.io/>`__ project.
- See the :ref:`R interfacing docs <rpy>` for more details.
+ See the :ref:`R interfacing docs <https://pandas.pydata.org/pandas-docs/version/0.20/r_interface.html>`__ for more details.
- The ``pandas.io.ga`` module with a ``google-analytics`` interface is removed (:issue:`11308`).
Similar functionality can be found in the `Google2Pandas <https://github.com/panalysis/Google2Pandas>`__ package.
- ``pd.to_datetime`` and ``pd.to_timedelta`` have dropped the ``coerce`` parameter in favor of ``errors`` (:issue:`13602`)
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 8d8f1d312b784..6d850095510d0 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -72,7 +72,7 @@ column selection, the values can just be the functions to apply
This type of aggregation is the recommended alternative to the deprecated behavior when passing
a dict to a Series groupby aggregation (:ref:`whatsnew_0200.api_breaking.deprecate_group_agg_dict`).
-See :ref:`_groupby.aggregate.named` for more.
+See :ref:`groupby.aggregate.named` for more.
.. _whatsnew_0250.enhancements.other:
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 81ba8ab1c574e..b0c91543dabac 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -212,7 +212,7 @@ class TimelikeOps:
.. versionadded:: 0.24.0
- nonexistent : 'shift_forward', 'shift_backward, 'NaT', timedelta, \
+ nonexistent : 'shift_forward', 'shift_backward', 'NaT', timedelta, \
default 'raise'
A nonexistent time does not exist in a particular timezone
where clocks moved forward due to DST.
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 8ec8227d8a1d3..d85a3a1ddeff0 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -10283,8 +10283,8 @@ def _doc_parms(cls):
Returns
-------
%(name1)s or %(name2)s (if level specified)\
-%(see_also)s
-%(examples)s\
+%(see_also)s\
+%(examples)s
"""
_num_ddof_doc = """
@@ -10427,7 +10427,8 @@ def _doc_parms(cls):
Returns
-------
-%(name1)s or %(name2)s\n
+%(name1)s or %(name2)s
+
See Also
--------
core.window.Expanding.%(accum_func_name)s : Similar functionality
@@ -10788,10 +10789,10 @@ def _doc_parms(cls):
Series([], dtype: bool)
"""
-_shared_docs['stat_func_example'] = """\
+_shared_docs['stat_func_example'] = """
+
Examples
--------
-
>>> idx = pd.MultiIndex.from_arrays([
... ['warm', 'warm', 'cold', 'cold'],
... ['dog', 'falcon', 'fish', 'spider']],
@@ -10820,8 +10821,7 @@ def _doc_parms(cls):
blooded
warm {level_output_0}
cold {level_output_1}
-Name: legs, dtype: int64
-"""
+Name: legs, dtype: int64"""
_sum_examples = _shared_docs['stat_func_example'].format(
stat_func='sum',
@@ -10831,6 +10831,7 @@ def _doc_parms(cls):
level_output_1=8)
_sum_examples += """
+
By default, the sum of an empty or all-NA Series is ``0``.
>>> pd.Series([]).sum() # min_count=0 is the default
@@ -10849,8 +10850,7 @@ def _doc_parms(cls):
0.0
>>> pd.Series([np.nan]).sum(min_count=1)
-nan
-"""
+nan"""
_max_examples = _shared_docs['stat_func_example'].format(
stat_func='max',
@@ -10879,10 +10879,10 @@ def _doc_parms(cls):
DataFrame.min : Return the minimum over the requested axis.
DataFrame.max : Return the maximum over the requested axis.
DataFrame.idxmin : Return the index of the minimum over the requested axis.
-DataFrame.idxmax : Return the index of the maximum over the requested axis.
-"""
+DataFrame.idxmax : Return the index of the maximum over the requested axis."""
+
+_prod_examples = """
-_prod_examples = """\
Examples
--------
By default, the product of an empty or all-NA Series is ``1``
@@ -10902,8 +10902,7 @@ def _doc_parms(cls):
1.0
>>> pd.Series([np.nan]).prod(min_count=1)
-nan
-"""
+nan"""
_min_count_stub = """\
min_count : int, default 0
| - [x] xref #24173
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Fixing some docs warnings, still many more, but will open few PRs with fixes, try to get a clean build and start failing the CI for doc warnings. | https://api.github.com/repos/pandas-dev/pandas/pulls/26786 | 2019-06-11T14:39:57Z | 2019-06-12T09:02:14Z | 2019-06-12T09:02:14Z | 2019-06-12T09:02:14Z |
DOC: clean-up numpydoc patches now numpydoc 0.9 is released | diff --git a/doc/source/conf.py b/doc/source/conf.py
index 971aa04ba866a..2484a9d592e09 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -18,7 +18,7 @@
import jinja2
from sphinx.ext.autosummary import _import_by_name
from numpydoc.docscrape import NumpyDocString
-from numpydoc.docscrape_sphinx import SphinxDocString
+
logger = logging.getLogger(__name__)
@@ -110,6 +110,9 @@
else None)))
autosummary_generate = True if pattern is None else ['index']
+# numpydoc
+numpydoc_attributes_as_param_list = False
+
# matplotlib plot directive
plot_include_source = True
plot_formats = [("png", 90)]
@@ -422,62 +425,6 @@
]
-def sphinxdocstring_str(self, indent=0, func_role="obj"):
- # Pandas displays Attributes section in style like Methods section
-
- # Function is copy of `SphinxDocString.__str__`
- ns = {
- 'signature': self._str_signature(),
- 'index': self._str_index(),
- 'summary': self._str_summary(),
- 'extended_summary': self._str_extended_summary(),
- 'parameters': self._str_param_list('Parameters'),
- 'returns': self._str_returns('Returns'),
- 'yields': self._str_returns('Yields'),
- 'other_parameters': self._str_param_list('Other Parameters'),
- 'raises': self._str_param_list('Raises'),
- 'warns': self._str_param_list('Warns'),
- 'warnings': self._str_warnings(),
- 'see_also': self._str_see_also(func_role),
- 'notes': self._str_section('Notes'),
- 'references': self._str_references(),
- 'examples': self._str_examples(),
- # Replaced `self._str_param_list('Attributes', fake_autosummary=True)`
- # with `self._str_member_list('Attributes')`
- 'attributes': self._str_member_list('Attributes'),
- 'methods': self._str_member_list('Methods'),
- }
- ns = {k: '\n'.join(v) for k, v in ns.items()}
-
- rendered = self.template.render(**ns)
- return '\n'.join(self._str_indent(rendered.split('\n'), indent))
-
-
-SphinxDocString.__str__ = sphinxdocstring_str
-
-
-# Fix "WARNING: Inline strong start-string without end-string."
-# PR #155 "Escape the * in *args and **kwargs" from numpydoc
-# Can be removed after PR merges in v0.9.0
-def decorate_process_param(func):
- def _escape_args_and_kwargs(name):
- if name[:2] == '**':
- return r'\*\*' + name[2:]
- elif name[:1] == '*':
- return r'\*' + name[1:]
- else:
- return name
-
- def func_wrapper(self, param, desc, fake_autosummary):
- param = _escape_args_and_kwargs(param.strip())
- return func(self, param, desc, fake_autosummary)
-
- return func_wrapper
-
-
-func = SphinxDocString._process_param
-SphinxDocString._process_param = decorate_process_param(func)
-
# Add custom Documenter to handle attributes/methods of an AccessorProperty
# eg pandas.Series.str and pandas.Series.dt (see GH9322)
| Since numpydoc is released, we can do some cleanup of what was introduced in https://github.com/pandas-dev/pandas/pull/24098
cc @FHaase | https://api.github.com/repos/pandas-dev/pandas/pulls/26785 | 2019-06-11T14:38:21Z | 2019-06-11T19:23:24Z | 2019-06-11T19:23:24Z | 2019-06-11T19:23:30Z |
DOC: pin sphinx to 1.8.5 | diff --git a/ci/deps/travis-36-doc.yaml b/ci/deps/travis-36-doc.yaml
index a3c9f27f72d7e..9419543e601e2 100644
--- a/ci/deps/travis-36-doc.yaml
+++ b/ci/deps/travis-36-doc.yaml
@@ -33,8 +33,8 @@ dependencies:
- pytz
- scipy
- seaborn
- # recursion error with sphinx 2.1.0. https://github.com/pandas-dev/pandas/issues/26723
- - sphinx==2.0.1
+ # some styling is broken with sphinx >= 2 (https://github.com/pandas-dev/pandas/issues/26058)
+ - sphinx=1.8.5
- sqlalchemy
- statsmodels
- xarray
diff --git a/environment.yml b/environment.yml
index 897fd34ebb803..200aa0428f1e1 100644
--- a/environment.yml
+++ b/environment.yml
@@ -26,7 +26,8 @@ dependencies:
# documentation
- gitpython # obtain contributors from git for whatsnew
- - sphinx
+ # some styling is broken with sphinx >= 2 (https://github.com/pandas-dev/pandas/issues/26058)
+ - sphinx=1.8.5
- numpydoc>=0.9.0
# documentation (jupyter notebooks)
diff --git a/requirements-dev.txt b/requirements-dev.txt
index f5309df5aa6ce..46e857f2e9e0f 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -11,7 +11,7 @@ isort
mypy
pycodestyle
gitpython
-sphinx
+sphinx==1.8.5
numpydoc>=0.9.0
nbconvert>=5.4.1
nbsphinx
| xref https://github.com/pandas-dev/pandas/issues/26058 | https://api.github.com/repos/pandas-dev/pandas/pulls/26781 | 2019-06-11T12:10:08Z | 2019-06-12T15:12:14Z | 2019-06-12T15:12:13Z | 2019-10-06T07:37:26Z |
DOC: fix old whatsnew examples + few sphinx warnings | diff --git a/doc/source/whatsnew/v0.11.0.rst b/doc/source/whatsnew/v0.11.0.rst
index c919698d15689..0dfcfca9a7464 100644
--- a/doc/source/whatsnew/v0.11.0.rst
+++ b/doc/source/whatsnew/v0.11.0.rst
@@ -105,27 +105,54 @@ Conversion
Mixed Conversion
-.. ipython:: python
- :okwarning:
+.. code-block:: ipython
- df3['D'] = '1.'
- df3['E'] = '1'
- df3.convert_objects(convert_numeric=True).dtypes
+ In [12]: df3['D'] = '1.'
- # same, but specific dtype conversion
- df3['D'] = df3['D'].astype('float16')
- df3['E'] = df3['E'].astype('int32')
- df3.dtypes
+ In [13]: df3['E'] = '1'
+
+ In [14]: df3.convert_objects(convert_numeric=True).dtypes
+ Out[14]:
+ A float32
+ B float64
+ C float64
+ D float64
+ E int64
+ dtype: object
+
+ # same, but specific dtype conversion
+ In [15]: df3['D'] = df3['D'].astype('float16')
+
+ In [16]: df3['E'] = df3['E'].astype('int32')
+
+ In [17]: df3.dtypes
+ Out[17]:
+ A float32
+ B float64
+ C float64
+ D float16
+ E int32
+ dtype: object
Forcing Date coercion (and setting ``NaT`` when not datelike)
-.. ipython:: python
- :okwarning:
+.. code-block:: ipython
+
+ In [18]: import datetime
+
+ In [19]: s = pd.Series([datetime.datetime(2001, 1, 1, 0, 0), 'foo', 1.0, 1,
+ ....: pd.Timestamp('20010104'), '20010105'], dtype='O')
+ ....:
- import datetime
- s = pd.Series([datetime.datetime(2001, 1, 1, 0, 0), 'foo', 1.0, 1,
- pd.Timestamp('20010104'), '20010105'], dtype='O')
- s.convert_objects(convert_dates='coerce')
+ In [20]: s.convert_objects(convert_dates='coerce')
+ Out[20]:
+ 0 2001-01-01
+ 1 NaT
+ 2 NaT
+ 3 NaT
+ 4 2001-01-04
+ 5 2001-01-05
+ dtype: datetime64[ns]
Dtype Gotchas
~~~~~~~~~~~~~
@@ -138,11 +165,22 @@ dtypes, they *WILL* be respected, however (:issue:`2837`)
The following will all result in ``int64`` dtypes
-.. ipython:: python
+.. code-block:: ipython
+
+ In [21]: pd.DataFrame([1, 2], columns=['a']).dtypes
+ Out[21]:
+ a int64
+ dtype: object
+
+ In [22]: pd.DataFrame({'a': [1, 2]}).dtypes
+ Out[22]:
+ a int64
+ dtype: object
- pd.DataFrame([1, 2], columns=['a']).dtypes
- pd.DataFrame({'a': [1, 2]}).dtypes
- pd.DataFrame({'a': 1}, index=range(2)).dtypes
+ In [23]: pd.DataFrame({'a': 1}, index=range(2)).dtypes
+ Out[23]:
+ a int64
+ dtype: object
Keep in mind that ``DataFrame(np.array([1,2]))`` **WILL** result in ``int32`` on 32-bit platforms!
@@ -152,28 +190,95 @@ Keep in mind that ``DataFrame(np.array([1,2]))`` **WILL** result in ``int32`` on
Performing indexing operations on integer type data can easily upcast the data.
The dtype of the input data will be preserved in cases where ``nans`` are not introduced.
-.. ipython:: python
-
- dfi = df3.astype('int32')
- dfi['D'] = dfi['D'].astype('int64')
- dfi
- dfi.dtypes
-
- casted = dfi[dfi > 0]
- casted
- casted.dtypes
+.. code-block:: ipython
+
+ In [24]: dfi = df3.astype('int32')
+
+ In [25]: dfi['D'] = dfi['D'].astype('int64')
+
+ In [26]: dfi
+ Out[26]:
+ A B C D E
+ 0 0 0 0 1 1
+ 1 -2 0 1 1 1
+ 2 -2 0 2 1 1
+ 3 0 -1 3 1 1
+ 4 1 0 4 1 1
+ 5 0 0 5 1 1
+ 6 0 -1 6 1 1
+ 7 0 0 7 1 1
+
+ In [27]: dfi.dtypes
+ Out[27]:
+ A int32
+ B int32
+ C int32
+ D int64
+ E int32
+ dtype: object
+
+ In [28]: casted = dfi[dfi > 0]
+
+ In [29]: casted
+ Out[29]:
+ A B C D E
+ 0 NaN NaN NaN 1 1
+ 1 NaN NaN 1.0 1 1
+ 2 NaN NaN 2.0 1 1
+ 3 NaN NaN 3.0 1 1
+ 4 1.0 NaN 4.0 1 1
+ 5 NaN NaN 5.0 1 1
+ 6 NaN NaN 6.0 1 1
+ 7 NaN NaN 7.0 1 1
+
+ In [30]: casted.dtypes
+ Out[30]:
+ A float64
+ B float64
+ C float64
+ D int64
+ E int32
+ dtype: object
While float dtypes are unchanged.
-.. ipython:: python
-
- df4 = df3.copy()
- df4['A'] = df4['A'].astype('float32')
- df4.dtypes
-
- casted = df4[df4 > 0]
- casted
- casted.dtypes
+.. code-block:: ipython
+
+ In [31]: df4 = df3.copy()
+
+ In [32]: df4['A'] = df4['A'].astype('float32')
+
+ In [33]: df4.dtypes
+ Out[33]:
+ A float32
+ B float64
+ C float64
+ D float16
+ E int32
+ dtype: object
+
+ In [34]: casted = df4[df4 > 0]
+
+ In [35]: casted
+ Out[35]:
+ A B C D E
+ 0 NaN NaN NaN 1.0 1
+ 1 NaN 0.567020 1.0 1.0 1
+ 2 NaN 0.276232 2.0 1.0 1
+ 3 NaN NaN 3.0 1.0 1
+ 4 1.933792 NaN 4.0 1.0 1
+ 5 NaN 0.113648 5.0 1.0 1
+ 6 NaN NaN 6.0 1.0 1
+ 7 NaN 0.524988 7.0 1.0 1
+
+ In [36]: casted.dtypes
+ Out[36]:
+ A float32
+ B float64
+ C float64
+ D float16
+ E int32
+ dtype: object
Datetimes Conversion
~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/whatsnew/v0.13.0.rst b/doc/source/whatsnew/v0.13.0.rst
index 13a2f879211b3..095d1807ca873 100644
--- a/doc/source/whatsnew/v0.13.0.rst
+++ b/doc/source/whatsnew/v0.13.0.rst
@@ -271,17 +271,39 @@ This is like an ``append`` operation.
A Panel setting operation on an arbitrary axis aligns the input to the Panel
-.. ipython:: python
- :okwarning:
-
- p = pd.Panel(np.arange(16).reshape(2, 4, 2),
- items=['Item1', 'Item2'],
- major_axis=pd.date_range('2001/1/12', periods=4),
- minor_axis=['A', 'B'], dtype='float64')
- p
- p.loc[:, :, 'C'] = pd.Series([30, 32], index=p.items)
- p
- p.loc[:, :, 'C']
+.. code-block:: ipython
+
+ In [20]: p = pd.Panel(np.arange(16).reshape(2, 4, 2),
+ ....: items=['Item1', 'Item2'],
+ ....: major_axis=pd.date_range('2001/1/12', periods=4),
+ ....: minor_axis=['A', 'B'], dtype='float64')
+ ....:
+
+ In [21]: p
+ Out[21]:
+ <class 'pandas.core.panel.Panel'>
+ Dimensions: 2 (items) x 4 (major_axis) x 2 (minor_axis)
+ Items axis: Item1 to Item2
+ Major_axis axis: 2001-01-12 00:00:00 to 2001-01-15 00:00:00
+ Minor_axis axis: A to B
+
+ In [22]: p.loc[:, :, 'C'] = pd.Series([30, 32], index=p.items)
+
+ In [23]: p
+ Out[23]:
+ <class 'pandas.core.panel.Panel'>
+ Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)
+ Items axis: Item1 to Item2
+ Major_axis axis: 2001-01-12 00:00:00 to 2001-01-15 00:00:00
+ Minor_axis axis: A to C
+
+ In [24]: p.loc[:, :, 'C']
+ Out[24]:
+ Item1 Item2
+ 2001-01-12 30.0 32.0
+ 2001-01-13 30.0 32.0
+ 2001-01-14 30.0 32.0
+ 2001-01-15 30.0 32.0
Float64Index API Change
~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index f61c8bfbd782e..2e2d2d99126d9 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -145,29 +145,28 @@ Constructing a :class:`MultiIndex` with ``NaN`` levels or codes value < -1 was a
Now, construction with codes value < -1 is not allowed and ``NaN`` levels' corresponding codes
would be reassigned as -1. (:issue:`19387`)
-.. ipython:: python
-
- mi1 = pd.MultiIndex(levels=[[np.nan, None, pd.NaT, 128, 2]],
- codes=[[0, -1, 1, 2, 3, 4]])
- mi2 = pd.MultiIndex(levels=[[1, 2]], codes=[[0, -2]])
-
*Previous Behavior*:
.. code-block:: ipython
- In [1]: mi1
+ In [1]: pd.MultiIndex(levels=[[np.nan, None, pd.NaT, 128, 2]],
+ ...: codes=[[0, -1, 1, 2, 3, 4]])
+ ...:
Out[1]: MultiIndex(levels=[[nan, None, NaT, 128, 2]],
codes=[[0, -1, 1, 2, 3, 4]])
- In [2]: mi2
+
+ In [2]: pd.MultiIndex(levels=[[1, 2]], codes=[[0, -2]])
Out[2]: MultiIndex(levels=[[1, 2]],
codes=[[0, -2]])
*New Behavior*:
.. ipython:: python
+ :okexcept:
- mi1
- mi2
+ pd.MultiIndex(levels=[[np.nan, None, pd.NaT, 128, 2]],
+ codes=[[0, -1, 1, 2, 3, 4]])
+ pd.MultiIndex(levels=[[1, 2]], codes=[[0, -2]])
.. _whatsnew_0250.api_breaking.groupby_apply_first_group_once:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index bb3275c27a4ac..ef406ce3d6b02 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4000,6 +4000,7 @@ def rename(self, *args, **kwargs):
intent.
Rename columns using a mapping:
+
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(columns={"A": "a", "B": "c"})
a c
@@ -4008,6 +4009,7 @@ def rename(self, *args, **kwargs):
2 3 6
Rename index using a mapping:
+
>>> df.rename(index={0: "x", 1: "y", 2: "z"})
A B
x 1 4
@@ -4015,6 +4017,7 @@ def rename(self, *args, **kwargs):
z 3 6
Cast index labels to a different type:
+
>>> df.index
RangeIndex(start=0, stop=3, step=1)
>>> df.rename(index=str).index
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 81fe87f190822..8ec8227d8a1d3 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -10867,6 +10867,7 @@ def _doc_parms(cls):
level_output_1=0)
_stat_func_see_also = """
+
See Also
--------
Series.sum : Return the sum.
| https://api.github.com/repos/pandas-dev/pandas/pulls/26780 | 2019-06-11T11:52:04Z | 2019-06-11T15:47:40Z | 2019-06-11T15:47:39Z | 2019-06-11T15:55:32Z | |
PERF: avoid printing object in Dtype.construct_from_string message | diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index 0a0ba69659570..d1d48f9810419 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -214,6 +214,8 @@ def construct_from_string(cls, string: str):
... raise TypeError("Cannot construct a '{}' from "
... "'{}'".format(cls.__name__, string))
"""
+ if not isinstance(string, str):
+ raise TypeError("Expects a string, got {}".format(type(string)))
if string != cls.name:
raise TypeError("Cannot construct a '{}' from '{}'".format(
cls.__name__, string))
| xref https://github.com/pandas-dev/pandas/pull/26562#issuecomment-500120556 | https://api.github.com/repos/pandas-dev/pandas/pulls/26776 | 2019-06-11T07:34:05Z | 2019-06-12T14:44:22Z | 2019-06-12T14:44:22Z | 2019-06-12T14:44:29Z |
fix typo | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index c4e08f50958f7..dd6a680ab1a4e 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -7476,7 +7476,7 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
aligned; see ``.align()`` method). If an ndarray is passed, the
values are used as-is determine the groups. A label or list of
labels may be passed to group by the columns in ``self``. Notice
- that a tuple is interpreted a (single) key.
+ that a tuple is interpreted as a (single) key.
axis : {0 or 'index', 1 or 'columns'}, default 0
Split along rows (0) or columns (1).
level : int, level name, or sequence of such, default None
| - [N/A] closes #xxxx
- [none] tests added / passed
- [no (online Github minor change)] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [probably not necessary either?] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26775 | 2019-06-10T22:39:04Z | 2019-06-10T23:32:39Z | 2019-06-10T23:32:39Z | 2019-06-10T23:32:45Z |
PERF: 5x speedup for read_json() with orient='index' by avoiding transpose | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 68ecb4c487a1e..23c56f8b78043 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -939,6 +939,7 @@ Performance improvements
- Improved performance by removing the need for a garbage collect when checking for ``SettingWithCopyWarning`` (:issue:`27031`)
- For :meth:`to_datetime` changed default value of cache parameter to ``True`` (:issue:`26043`)
- Improved performance of :class:`DatetimeIndex` and :class:`PeriodIndex` slicing given non-unique, monotonic data (:issue:`27136`).
+- Improved performance of :meth:`pd.read_json` for index-oriented data. (:issue:`26773`)
.. _whatsnew_0250.bug_fixes:
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index 1f0728ee96469..508a71eaedb8b 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -1085,9 +1085,15 @@ def _parse_no_numpy(self):
self.check_keys_split(decoded)
self.obj = DataFrame(dtype=None, **decoded)
elif orient == "index":
- self.obj = DataFrame(
- loads(json, precise_float=self.precise_float), dtype=None
- ).T
+ self.obj = (
+ DataFrame.from_dict(
+ loads(json, precise_float=self.precise_float),
+ dtype=None,
+ orient="index",
+ )
+ .sort_index(axis="columns")
+ .sort_index(axis="index")
+ )
elif orient == "table":
self.obj = parse_table_schema(json, precise_float=self.precise_float)
else:
| The `.T` operator can be quite slow on mixed-type `DataFrame`s due to the creation of `object` dtype columns. In comparison to direct construction with `DataFrame.from_dict()` can generally be much more efficient.
Making that swap inside `pd.read_json()` yields a `~5-6x` speedup for the `orient='index'` case:
```
before after ratio
[d47fc0cb] [b0fd99ec]
<read_json_speedup~1> <read_json_speedup>
- 5.37±0.03s 907±5ms 0.17 io.json.ReadJSON.time_read_json('index', 'int')
- 5.27±0.01s 804±3ms 0.15 io.json.ReadJSON.time_read_json('index', 'datetime')
```
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26773 | 2019-06-10T19:11:37Z | 2019-07-17T11:49:29Z | 2019-07-17T11:49:29Z | 2019-07-17T11:49:32Z |
BENCH: fix noisy asv benchmarks that were running on exhausted generators | diff --git a/asv_bench/benchmarks/ctors.py b/asv_bench/benchmarks/ctors.py
index 1c6841a296377..42adede631a01 100644
--- a/asv_bench/benchmarks/ctors.py
+++ b/asv_bench/benchmarks/ctors.py
@@ -55,7 +55,14 @@ class SeriesConstructors:
[False, True],
['float', 'int']]
+ # Generators get exhausted on use, so run setup before every call
+ number = 1
+ repeat = (3, 250, 10)
+
def setup(self, data_fmt, with_index, dtype):
+ if data_fmt in (gen_of_str, gen_of_tuples) and with_index:
+ raise NotImplementedError('Series constructors do not support '
+ 'using generators with indexes')
N = 10**4
if dtype == 'float':
arr = np.random.randn(N)
diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py
index 19c2a913e8494..9533938b30fac 100644
--- a/asv_bench/benchmarks/frame_ctor.py
+++ b/asv_bench/benchmarks/frame_ctor.py
@@ -72,6 +72,10 @@ class FromRecords:
params = [None, 1000]
param_names = ['nrows']
+ # Generators get exhausted on use, so run setup before every call
+ number = 1
+ repeat = (3, 250, 10)
+
def setup(self, nrows):
N = 100000
self.gen = ((x, (x * 20), (x * 100)) for x in range(N))
| Generators get consumed on first use, yielding abnormally fast benchmark times on the `n>1` iterations. Fortunately we can instruct `asv` to call `setup()` prior to every sample by setting `number = 1` and `repeat` appropriately. My local runs suggest the typical number of samples is `~150-250`, so an upper limit of `250` appears to be a good fit.
Here is current `master` with old benchmark version:
```
[ 75.00%] ··· Running (ctors.SeriesConstructors.time_series_constructor--).
[100.00%] ··· ctors.SeriesConstructors.time_series_constructor 4/40 failed
[100.00%] ··· ===================================== =============== ============= ============== =============
-- with_index / dtype
------------------------------------- ----------------------------------------------------------
data_fmt False / float False / int True / float True / int
===================================== =============== ============= ============== =============
<function gen_of_str> 130±0.9μs 116±6μs failed failed
<function gen_of_tuples> 113±3μs 112±20μs failed failed
===================================== =============== ============= ============== =============
```
And with the fixed benchmarks, we see the existing ones falsely report a `40x` speedup:
```
[ 50.00%] ··· ===================================== =============== ============= ============== ============
-- with_index / dtype
------------------------------------- ---------------------------------------------------------
data_fmt False / float False / int True / float True / int
===================================== =============== ============= ============== ============
<function gen_of_str> 4.61±0.1ms 4.21±0.07ms n/a n/a
<function gen_of_tuples> 3.39±0.1ms 3.43±0.07ms n/a n/a
===================================== =============== ============= ============== ============
```
Additionally, this PR resolves a few failing `asv` tests that I introduced in the first iteration.
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26772 | 2019-06-10T19:01:43Z | 2019-06-21T02:03:03Z | 2019-06-21T02:03:03Z | 2019-08-14T07:00:54Z |
Fix matplotlib converter registering warning | diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index 81f5b5cb0f74c..78c7082c69b6b 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -5,19 +5,16 @@
from pandas.core.dtypes.common import is_integer, is_list_like
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
-import pandas
from pandas.core.base import PandasObject
from pandas.core.generic import _shared_doc_kwargs, _shared_docs
-# Automatically registering converters was deprecated in 0.21, but
-# the deprecation warning wasn't showing until 0.24
-# This block will be eventually removed, but it's not clear when
-if pandas.get_option('plotting.matplotlib.register_converters'):
- try:
- from .misc import register
- register(explicit=False)
- except ImportError:
- pass
+# Trigger matplotlib import, which implicitly registers our
+# converts. Implicit registration is deprecated, and when enforced
+# we can lazily import matplotlib.
+try:
+ import pandas.plotting._matplotlib # noqa
+except ImportError:
+ pass
df_kind = """- 'scatter' : scatter plot
- 'hexbin' : hexbin plot"""
diff --git a/pandas/plotting/_matplotlib/__init__.py b/pandas/plotting/_matplotlib/__init__.py
index 5cfb6843db9ed..1b775d03349d0 100644
--- a/pandas/plotting/_matplotlib/__init__.py
+++ b/pandas/plotting/_matplotlib/__init__.py
@@ -1,3 +1,5 @@
+from pandas._config import get_option
+
from pandas.plotting._matplotlib.boxplot import (
BoxPlot, boxplot, boxplot_frame, boxplot_frame_groupby)
from pandas.plotting._matplotlib.converter import deregister, register
@@ -11,6 +13,10 @@
from pandas.plotting._matplotlib.timeseries import tsplot
from pandas.plotting._matplotlib.tools import table
+if get_option("plotting.matplotlib.register_converters"):
+ register(explicit=False)
+
+
__all__ = ['LinePlot', 'BarPlot', 'BarhPlot', 'HistPlot', 'BoxPlot', 'KdePlot',
'AreaPlot', 'PiePlot', 'ScatterPlot', 'HexBinPlot', 'hist_series',
'hist_frame', 'boxplot', 'boxplot_frame', 'boxplot_frame_groupby',
diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py
index b8a7da5270fc0..f8bc531e3c344 100644
--- a/pandas/plotting/_matplotlib/boxplot.py
+++ b/pandas/plotting/_matplotlib/boxplot.py
@@ -1,7 +1,6 @@
from collections import namedtuple
import warnings
-from matplotlib import pyplot as plt
from matplotlib.artist import setp
import numpy as np
@@ -11,6 +10,7 @@
import pandas as pd
from pandas.io.formats.printing import pprint_thing
+from pandas.plotting._matplotlib import converter
from pandas.plotting._matplotlib.core import LinePlot, MPLPlot
from pandas.plotting._matplotlib.style import _get_standard_colors
from pandas.plotting._matplotlib.tools import _flatten, _subplots
@@ -215,6 +215,7 @@ def boxplot(data, column=None, by=None, ax=None, fontsize=None,
rot=0, grid=True, figsize=None, layout=None, return_type=None,
**kwds):
+ import matplotlib.pyplot as plt
# validate return_type:
if return_type not in BoxPlot._valid_return_types:
raise ValueError("return_type must be {'axes', 'dict', 'both'}")
@@ -296,6 +297,8 @@ def plot_group(keys, values, ax):
def boxplot_frame(self, column=None, by=None, ax=None, fontsize=None, rot=0,
grid=True, figsize=None, layout=None,
return_type=None, **kwds):
+ import matplotlib.pyplot as plt
+ converter._WARN = False # no warning for pandas plots
ax = boxplot(self, column=column, by=by, ax=ax, fontsize=fontsize,
grid=grid, rot=rot, figsize=figsize, layout=layout,
return_type=return_type, **kwds)
@@ -306,6 +309,7 @@ def boxplot_frame(self, column=None, by=None, ax=None, fontsize=None, rot=0,
def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None,
rot=0, grid=True, ax=None, figsize=None,
layout=None, sharex=False, sharey=True, **kwds):
+ converter._WARN = False # no warning for pandas plots
if subplots is True:
naxes = len(grouped)
fig, axes = _subplots(naxes=naxes, squeeze=False,
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index a7049afee80b0..5fb4d201223bd 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -2,7 +2,6 @@
from typing import Optional # noqa
import warnings
-import matplotlib.pyplot as plt
import numpy as np
from pandas._config import get_option
@@ -61,6 +60,8 @@ def __init__(self, data, kind=None, by=None, subplots=False, sharex=None,
secondary_y=False, colormap=None,
table=False, layout=None, **kwds):
+ import matplotlib.pyplot as plt
+ converter._WARN = False # no warning for pandas plots
self.data = data
self.by = by
@@ -103,7 +104,7 @@ def __init__(self, data, kind=None, by=None, subplots=False, sharex=None,
self.rot = self._default_rot
if grid is None:
- grid = False if secondary_y else self.plt.rcParams['axes.grid']
+ grid = False if secondary_y else plt.rcParams['axes.grid']
self.grid = grid
self.legend = legend
@@ -618,6 +619,8 @@ def _get_ax(self, i):
@classmethod
def get_default_ax(cls, ax):
+ import matplotlib.pyplot as plt
+
if ax is None and len(plt.get_fignums()) > 0:
with plt.rc_context():
ax = plt.gca()
diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py
index 585c407e33311..d34c0cb6a3889 100644
--- a/pandas/plotting/_matplotlib/hist.py
+++ b/pandas/plotting/_matplotlib/hist.py
@@ -1,6 +1,5 @@
import warnings
-import matplotlib.pyplot as plt
import numpy as np
from pandas.core.dtypes.common import is_integer, is_list_like
@@ -10,6 +9,7 @@
import pandas.core.common as com
from pandas.io.formats.printing import pprint_thing
+from pandas.plotting._matplotlib import converter
from pandas.plotting._matplotlib.core import LinePlot, MPLPlot
from pandas.plotting._matplotlib.tools import (
_flatten, _set_ticks_props, _subplots)
@@ -203,6 +203,7 @@ def _grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None,
def plot_group(group, ax):
ax.hist(group.dropna().values, bins=bins, **kwargs)
+ converter._WARN = False # no warning for pandas plots
xrot = xrot or rot
fig, axes = _grouped_plot(plot_group, data, column=column,
@@ -220,6 +221,7 @@ def plot_group(group, ax):
def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
xrot=None, ylabelsize=None, yrot=None, figsize=None,
bins=10, **kwds):
+ import matplotlib.pyplot as plt
if by is None:
if kwds.get('layout', None) is not None:
raise ValueError("The 'layout' keyword is not supported when "
@@ -261,6 +263,7 @@ def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False,
sharey=False, figsize=None, layout=None, bins=10, **kwds):
+ converter._WARN = False # no warning for pandas plots
if by is not None:
axes = _grouped_hist(data, column=column, by=by, ax=ax, grid=grid,
figsize=figsize, sharex=sharex, sharey=sharey,
diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py
index dacc9ef04f819..663a3c5153fac 100644
--- a/pandas/plotting/_matplotlib/misc.py
+++ b/pandas/plotting/_matplotlib/misc.py
@@ -2,7 +2,6 @@
import matplotlib.lines as mlines
import matplotlib.patches as patches
-import matplotlib.pyplot as plt
import numpy as np
from pandas.core.dtypes.missing import notna
@@ -105,6 +104,7 @@ def _get_marker_compat(marker):
def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds):
+ import matplotlib.pyplot as plt
def normalize(series):
a = min(series)
@@ -169,6 +169,7 @@ def normalize(series):
def andrews_curves(frame, class_column, ax=None, samples=200, color=None,
colormap=None, **kwds):
+ import matplotlib.pyplot as plt
def function(amplitudes):
def f(t):
@@ -224,6 +225,7 @@ def f(t):
def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds):
+ import matplotlib.pyplot as plt
# random.sample(ndarray, int) fails on python 3.3, sigh
data = list(series.values)
samplings = [random.sample(data, size) for _ in range(samples)]
@@ -270,6 +272,7 @@ def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
use_columns=False, xticks=None, colormap=None,
axvlines=True, axvlines_kwds=None, sort_labels=False,
**kwds):
+ import matplotlib.pyplot as plt
if axvlines_kwds is None:
axvlines_kwds = {'linewidth': 1, 'color': 'black'}
@@ -336,6 +339,7 @@ def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
def lag_plot(series, lag=1, ax=None, **kwds):
# workaround because `c='b'` is hardcoded in matplotlibs scatter method
+ import matplotlib.pyplot as plt
kwds.setdefault('c', plt.rcParams['patch.facecolor'])
data = series.values
@@ -350,6 +354,8 @@ def lag_plot(series, lag=1, ax=None, **kwds):
def autocorrelation_plot(series, ax=None, **kwds):
+ import matplotlib.pyplot as plt
+
n = len(series)
data = np.asarray(series)
if ax is None:
diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py
index 80a15942a2867..8c9e3ea330dd3 100644
--- a/pandas/plotting/_matplotlib/style.py
+++ b/pandas/plotting/_matplotlib/style.py
@@ -3,7 +3,6 @@
import matplotlib.cm as cm
import matplotlib.colors
-import matplotlib.pyplot as plt
import numpy as np
from pandas.core.dtypes.common import is_list_like
@@ -13,6 +12,7 @@
def _get_standard_colors(num_colors=None, colormap=None, color_type='default',
color=None):
+ import matplotlib.pyplot as plt
if color is None and colormap is not None:
if isinstance(colormap, str):
cmap = colormap
diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py
index 30038b599a386..e36ffed10d94f 100644
--- a/pandas/plotting/_matplotlib/timeseries.py
+++ b/pandas/plotting/_matplotlib/timeseries.py
@@ -3,8 +3,6 @@
import functools
import warnings
-from matplotlib import pylab
-import matplotlib.pyplot as plt
import numpy as np
from pandas._libs.tslibs.frequencies import (
@@ -42,6 +40,7 @@ def tsplot(series, plotf, ax=None, **kwargs):
.. deprecated:: 0.23.0
Use Series.plot() instead
"""
+ import matplotlib.pyplot as plt
warnings.warn("'tsplot' is deprecated and will be removed in a "
"future version. Please use Series.plot() instead.",
FutureWarning, stacklevel=2)
@@ -323,6 +322,7 @@ def format_dateaxis(subplot, freq, index):
default, changing the limits of the x axis will intelligently change
the positions of the ticks.
"""
+ from matplotlib import pylab
# handle index specific formatting
# Note: DatetimeIndex does not use this
diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py
index f6393fc76892f..e491cfc3309a0 100644
--- a/pandas/plotting/_matplotlib/tools.py
+++ b/pandas/plotting/_matplotlib/tools.py
@@ -2,7 +2,6 @@
from math import ceil
import warnings
-import matplotlib.pyplot as plt
import matplotlib.table
import matplotlib.ticker as ticker
import numpy as np
@@ -168,6 +167,7 @@ def _subplots(naxes=None, sharex=False, sharey=False, squeeze=True,
# Four polar axes
plt.subplots(2, 2, subplot_kw=dict(polar=True))
"""
+ import matplotlib.pyplot as plt
if subplot_kw is None:
subplot_kw = {}
@@ -345,6 +345,7 @@ def _get_xlim(lines):
def _set_ticks_props(axes, xlabelsize=None, xrot=None,
ylabelsize=None, yrot=None):
+ import matplotlib.pyplot as plt
for ax in _flatten(axes):
if xlabelsize is not None:
plt.setp(ax.get_xticklabels(), fontsize=xlabelsize)
diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py
index 39cd48ff35f96..92d207e46b7ab 100644
--- a/pandas/tests/plotting/test_converter.py
+++ b/pandas/tests/plotting/test_converter.py
@@ -12,11 +12,30 @@
from pandas import Index, Period, Series, Timestamp, date_range
import pandas.util.testing as tm
+from pandas.plotting import (
+ deregister_matplotlib_converters, register_matplotlib_converters)
from pandas.tseries.offsets import Day, Micro, Milli, Second
-converter = pytest.importorskip('pandas.plotting._converter')
-from pandas.plotting import (deregister_matplotlib_converters, # isort:skip
- register_matplotlib_converters)
+try:
+ from pandas.plotting._matplotlib import converter
+except ImportError:
+ # try / except, rather than skip, to avoid internal refactoring
+ # causing an improprer skip
+ pass
+
+pytest.importorskip('matplotlib.pyplot')
+
+
+def test_initial_warning():
+ code = (
+ "import pandas as pd; import matplotlib.pyplot as plt; "
+ "s = pd.Series(1, pd.date_range('2000', periods=12)); "
+ "fig, ax = plt.subplots(); "
+ "ax.plot(s.index, s.values)"
+ )
+ call = [sys.executable, '-c', code]
+ out = subprocess.check_output(call, stderr=subprocess.STDOUT).decode()
+ assert 'Using an implicitly' in out
def test_timtetonum_accepts_unicode():
diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py
index 10743ca95e29e..c3d824389aa4d 100644
--- a/pandas/tests/plotting/test_datetimelike.py
+++ b/pandas/tests/plotting/test_datetimelike.py
@@ -374,7 +374,6 @@ def test_axis_limits(self):
def _test(ax):
xlim = ax.get_xlim()
ax.set_xlim(xlim[0] - 5, xlim[1] + 10)
- ax.get_figure().canvas.draw()
result = ax.get_xlim()
assert result[0] == xlim[0] - 5
assert result[1] == xlim[1] + 10
@@ -383,7 +382,6 @@ def _test(ax):
expected = (Period('1/1/2000', ax.freq),
Period('4/1/2000', ax.freq))
ax.set_xlim('1/1/2000', '4/1/2000')
- ax.get_figure().canvas.draw()
result = ax.get_xlim()
assert int(result[0]) == expected[0].ordinal
assert int(result[1]) == expected[1].ordinal
@@ -392,7 +390,6 @@ def _test(ax):
expected = (Period('1/1/2000', ax.freq),
Period('4/1/2000', ax.freq))
ax.set_xlim(datetime(2000, 1, 1), datetime(2000, 4, 1))
- ax.get_figure().canvas.draw()
result = ax.get_xlim()
assert int(result[0]) == expected[0].ordinal
assert int(result[1]) == expected[1].ordinal
@@ -429,12 +426,7 @@ def test_get_finder(self):
def test_finder_daily(self):
day_lst = [10, 40, 252, 400, 950, 2750, 10000]
- if self.mpl_ge_3_0_0 or not self.mpl_ge_2_2_3:
- xpl1 = xpl2 = [Period('1999-1-1', freq='B').ordinal] * len(day_lst)
- else: # 2.2.3, 2.2.4
- xpl1 = [7565, 7564, 7553, 7546, 7518, 7428, 7066]
- xpl2 = [7566, 7564, 7554, 7546, 7519, 7429, 7066]
-
+ xpl1 = xpl2 = [Period('1999-1-1', freq='B').ordinal] * len(day_lst)
rs1 = []
rs2 = []
for i, n in enumerate(day_lst):
@@ -457,12 +449,7 @@ def test_finder_daily(self):
def test_finder_quarterly(self):
yrs = [3.5, 11]
- if self.mpl_ge_3_0_0 or not self.mpl_ge_2_2_3:
- xpl1 = xpl2 = [Period('1988Q1').ordinal] * len(yrs)
- else: # 2.2.3, 2.2.4
- xpl1 = [68, 68]
- xpl2 = [72, 68]
-
+ xpl1 = xpl2 = [Period('1988Q1').ordinal] * len(yrs)
rs1 = []
rs2 = []
for i, n in enumerate(yrs):
@@ -485,12 +472,7 @@ def test_finder_quarterly(self):
def test_finder_monthly(self):
yrs = [1.15, 2.5, 4, 11]
- if self.mpl_ge_3_0_0 or not self.mpl_ge_2_2_3:
- xpl1 = xpl2 = [Period('Jan 1988').ordinal] * len(yrs)
- else: # 2.2.3, 2.2.4
- xpl1 = [216, 216, 204, 204]
- xpl2 = [216, 216, 216, 204]
-
+ xpl1 = xpl2 = [Period('Jan 1988').ordinal] * len(yrs)
rs1 = []
rs2 = []
for i, n in enumerate(yrs):
@@ -521,11 +503,7 @@ def test_finder_monthly_long(self):
@pytest.mark.slow
def test_finder_annual(self):
- if self.mpl_ge_3_0_0 or not self.mpl_ge_2_2_3:
- xp = [1987, 1988, 1990, 1990, 1995, 2020, 2070, 2170]
- else: # 2.2.3, 2.2.4
- xp = [1986, 1986, 1990, 1990, 1995, 2020, 1970, 1970]
-
+ xp = [1987, 1988, 1990, 1990, 1995, 2020, 2070, 2170]
xp = [Period(x, freq='A').ordinal for x in xp]
rs = []
for i, nyears in enumerate([5, 10, 19, 49, 99, 199, 599, 1001]):
@@ -1093,7 +1071,6 @@ def test_time(self):
df.plot(ax=ax)
# verify tick labels
- fig.canvas.draw()
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
for t, l in zip(ticks, labels):
@@ -1120,7 +1097,6 @@ def test_time_change_xlim(self):
df.plot(ax=ax)
# verify tick labels
- fig.canvas.draw()
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
for t, l in zip(ticks, labels):
@@ -1138,7 +1114,6 @@ def test_time_change_xlim(self):
ax.set_xlim('1:30', '5:00')
# check tick labels again
- fig.canvas.draw()
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
for t, l in zip(ticks, labels):
@@ -1165,7 +1140,6 @@ def test_time_musec(self):
ax = df.plot(ax=ax)
# verify tick labels
- fig.canvas.draw()
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
for t, l in zip(ticks, labels):
@@ -1432,7 +1406,7 @@ def test_format_timedelta_ticks_narrow(self):
df = DataFrame(np.random.randn(len(rng), 3), rng)
fig, ax = self.plt.subplots()
df.plot(fontsize=2, ax=ax)
- fig.canvas.draw()
+ self.plt.draw()
labels = ax.get_xticklabels()
result_labels = [x.get_text() for x in labels]
@@ -1456,7 +1430,7 @@ def test_format_timedelta_ticks_wide(self):
df = DataFrame(np.random.randn(len(rng), 3), rng)
fig, ax = self.plt.subplots()
ax = df.plot(fontsize=2, ax=ax)
- fig.canvas.draw()
+ self.plt.draw()
labels = ax.get_xticklabels()
result_labels = [x.get_text() for x in labels]
@@ -1529,7 +1503,7 @@ def test_matplotlib_scatter_datetime64(self):
df["time"] = date_range("2018-01-01", periods=10, freq="D")
fig, ax = self.plt.subplots()
ax.scatter(x="time", y="y", data=df)
- fig.canvas.draw()
+ self.plt.draw()
label = ax.get_xticklabels()[0]
if self.mpl_ge_3_0_0:
expected = "2017-12-08"
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index 4cc316ffdd7ab..e81a51e99f5a3 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -75,7 +75,7 @@ def safe_import(mod_name, min_version=None):
def _skip_if_no_mpl():
mod = safe_import("matplotlib")
if mod:
- mod.use("Agg", warn=False)
+ mod.use("Agg", warn=True)
else:
return True
| Closes #26760
Tests were being skipped, because the module name changed in https://github.com/pandas-dev/pandas/pull/18307/files. | https://api.github.com/repos/pandas-dev/pandas/pulls/26770 | 2019-06-10T17:11:09Z | 2019-06-21T02:06:35Z | 2019-06-21T02:06:35Z | 2019-06-21T02:06:57Z |
BLD: fix py37 build warnings | diff --git a/pandas/io/msgpack/_unpacker.pyx b/pandas/io/msgpack/_unpacker.pyx
index 8734990c44da0..c2e2dfc521a51 100644
--- a/pandas/io/msgpack/_unpacker.pyx
+++ b/pandas/io/msgpack/_unpacker.pyx
@@ -5,15 +5,13 @@ from cython cimport Py_ssize_t
from cpython cimport (
PyCallable_Check,
- PyBUF_SIMPLE, PyObject_GetBuffer, PyBuffer_Release,
+ PyBUF_SIMPLE, PyObject_GetBuffer, PyBuffer_Release, Py_buffer,
PyBytes_Size,
PyBytes_FromStringAndSize,
PyBytes_AsString)
cdef extern from "Python.h":
ctypedef struct PyObject
- cdef int PyObject_AsReadBuffer(object o, const void** buff,
- Py_ssize_t* buf_len) except -1
from libc.stdlib cimport free, malloc
from libc.string cimport memcpy, memmove
@@ -129,8 +127,14 @@ def unpackb(object packed, object object_hook=None, object list_hook=None,
Py_ssize_t buf_len
char* cenc = NULL
char* cerr = NULL
+ Py_buffer view
+ bytes extra_bytes
- PyObject_AsReadBuffer(packed, <const void**>&buf, &buf_len)
+ # GH#26769 Effectively re-implement deprecated PyObject_AsReadBuffer;
+ # based on https://xpra.org/trac/ticket/1884
+ PyObject_GetBuffer(packed, &view, PyBUF_SIMPLE)
+ buf = <char*>view.buf
+ buf_len = view.len
if encoding is not None:
if isinstance(encoding, unicode):
@@ -149,10 +153,13 @@ def unpackb(object packed, object object_hook=None, object list_hook=None,
if ret == 1:
obj = unpack_data(&ctx)
if <Py_ssize_t> off < buf_len:
- raise ExtraData(obj, PyBytes_FromStringAndSize(
- buf + off, buf_len - off))
+ extra_bytes = PyBytes_FromStringAndSize(buf + off, buf_len - off)
+ PyBuffer_Release(&view)
+ raise ExtraData(obj, extra_bytes)
+ PyBuffer_Release(&view)
return obj
else:
+ PyBuffer_Release(&view)
raise UnpackValueError("Unpack failed: error = {ret}".format(ret=ret))
| Not at all sure this is the optimal way to do this, cc @WillAyd for suggestions | https://api.github.com/repos/pandas-dev/pandas/pulls/26769 | 2019-06-10T17:02:38Z | 2019-06-27T21:59:49Z | 2019-06-27T21:59:49Z | 2019-06-27T22:05:10Z |
[26660] compare int with double by subtracting during describe percen… | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 844e062b20ca3..21e75d5d1ad07 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -97,7 +97,7 @@ Other Enhancements
- :func:`merge_asof` now gives a more clear error message when merge keys are categoricals that are not equal (:issue:`26136`)
- :meth:`pandas.core.window.Rolling` supports exponential (or Poisson) window type (:issue:`21303`)
- :class:`DatetimeIndex` and :class:`TimedeltaIndex` now have a `mean` method (:issue:`24757`)
--
+- :meth:`DataFrame.describe` now formats integer percentiles without decimal point (:issue:`26660`)
.. _whatsnew_0250.api_breaking:
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 765b31f294bcb..f632bc13a5b24 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -1246,7 +1246,7 @@ def format_percentiles(percentiles):
raise ValueError("percentiles should all be in the interval [0,1]")
percentiles = 100 * percentiles
- int_idx = (percentiles.astype(int) == percentiles)
+ int_idx = np.isclose(percentiles.astype(int), percentiles)
if np.all(int_idx):
out = percentiles.astype(int).astype(str)
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py
index 568b229435434..18d8d351e48c1 100644
--- a/pandas/tests/frame/test_analytics.py
+++ b/pandas/tests/frame/test_analytics.py
@@ -704,6 +704,17 @@ def test_describe_tz_values(self, tz_naive_fixture):
result = df.describe(include='all')
tm.assert_frame_equal(result, expected)
+ def test_describe_percentiles_integer_idx(self):
+ # Issue 26660
+ df = pd.DataFrame({'x': [1]})
+ pct = np.linspace(0, 1, 10 + 1)
+ result = df.describe(percentiles=pct)
+
+ expected = DataFrame(
+ {'x': [1.0, 1.0, np.NaN, 1.0, *[1.0 for _ in pct], 1.0]},
+ index=['count', 'mean', 'std', 'min', '0%', '10%', '20%', '30%',
+ '40%', '50%', '60%', '70%', '80%', '90%', '100%', 'max'])
+ tm.assert_frame_equal(result, expected)
# ---------------------------------------------------------------------
# Reductions
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index bae2470459f62..edb7c2136825d 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -2740,6 +2740,14 @@ def test_format_percentiles():
fmt.format_percentiles([0.1, 0.5, 'a'])
+def test_format_percentiles_integer_idx():
+ # Issue #26660
+ result = fmt.format_percentiles(np.linspace(0, 1, 10 + 1))
+ expected = ['0%', '10%', '20%', '30%', '40%', '50%',
+ '60%', '70%', '80%', '90%', '100%']
+ assert result == expected
+
+
def test_repr_html_ipython_config(ip):
code = textwrap.dedent("""\
import pandas as pd
| - [x] closes #26660
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
I am not sure whether I had put my issue in whatsnew entry in appropriate place. | https://api.github.com/repos/pandas-dev/pandas/pulls/26768 | 2019-06-10T14:33:19Z | 2019-06-11T00:16:58Z | 2019-06-11T00:16:58Z | 2019-06-11T05:35:28Z |
BUG: fix IntervalIndex for pivot table raise type error | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 76ee21b4c9a50..0ea022e83ea08 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -720,6 +720,7 @@ Reshaping
- Bug in :func:`pandas.cut` where large bins could incorrectly raise an error due to an integer overflow (:issue:`26045`)
- Bug in :func:`DataFrame.sort_index` where an error is thrown when a multi-indexed ``DataFrame`` is sorted on all levels with the initial level sorted last (:issue:`26053`)
- Bug in :meth:`Series.nlargest` treats ``True`` as smaller than ``False`` (:issue:`26154`)
+- Bug in :func:`DataFrame.pivot_table` with a :class:`IntervalIndex` as pivot index would raise ``TypeError`` (:issue:`25814`)
Sparse
^^^^^^
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index dc77599444505..c079b860bb924 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -181,7 +181,7 @@ def contains(cat, key, container):
# can't be in container either.
try:
loc = cat.categories.get_loc(key)
- except KeyError:
+ except (KeyError, TypeError):
return False
# loc is the location of key in categories, but also the *value*
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index cc91bef525eff..8543d2c2df7d6 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -19,6 +19,12 @@ def dropna(request):
return request.param
+@pytest.fixture(params=[([0] * 4, [1] * 4), (range(0, 3), range(1, 4))])
+def interval_values(request, closed):
+ left, right = request.param
+ return Categorical(pd.IntervalIndex.from_arrays(left, right, closed))
+
+
class TestPivotTable:
def setup_method(self, method):
@@ -198,6 +204,18 @@ def test_pivot_with_non_observable_dropna(self, dropna):
tm.assert_frame_equal(result, expected)
+ def test_pivot_with_interval_index(self, interval_values, dropna):
+ # GH 25814
+ df = DataFrame(
+ {'A': interval_values,
+ 'B': 1})
+ result = df.pivot_table(index='A', values='B', dropna=dropna)
+ expected = DataFrame(
+ {'B': 1},
+ index=Index(interval_values.unique(),
+ name='A'))
+ tm.assert_frame_equal(result, expected)
+
def test_pass_array(self):
result = self.data.pivot_table(
'D', index=self.data.A, columns=self.data.C)
| Close (#25814). When use IntervalIndex for pivot table, raise
TypeError: cannot determine next label for type <class 'str'>
- [x] closes #25814
- [x] tets added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26765 | 2019-06-10T10:55:26Z | 2019-06-13T20:41:45Z | 2019-06-13T20:41:44Z | 2019-06-14T02:06:04Z |
TST/CLN: declass smaller test files in tests\io\excel | diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py
index 8be96a771f3aa..6815d2aa079f8 100644
--- a/pandas/tests/io/excel/test_openpyxl.py
+++ b/pandas/tests/io/excel/test_openpyxl.py
@@ -1,124 +1,123 @@
import pytest
-import pandas.util._test_decorators as td
-
from pandas import DataFrame
from pandas.util.testing import ensure_clean
from pandas.io.excel import ExcelWriter, _OpenpyxlWriter
-
-@td.skip_if_no('openpyxl')
-@pytest.mark.parametrize("ext", ['.xlsx'])
-class TestOpenpyxlTests:
-
- def test_to_excel_styleconverter(self, ext):
- from openpyxl import styles
-
- hstyle = {
- "font": {
- "color": '00FF0000',
- "bold": True,
- },
- "borders": {
- "top": "thin",
- "right": "thin",
- "bottom": "thin",
- "left": "thin",
- },
- "alignment": {
- "horizontal": "center",
- "vertical": "top",
- },
- "fill": {
- "patternType": 'solid',
- 'fgColor': {
- 'rgb': '006666FF',
- 'tint': 0.3,
- },
- },
- "number_format": {
- "format_code": "0.00"
- },
- "protection": {
- "locked": True,
- "hidden": False,
+openpyxl = pytest.importorskip("openpyxl")
+
+pytestmark = pytest.mark.parametrize("ext", ['.xlsx'])
+
+
+def test_to_excel_styleconverter(ext):
+ from openpyxl import styles
+
+ hstyle = {
+ "font": {
+ "color": '00FF0000',
+ "bold": True,
+ },
+ "borders": {
+ "top": "thin",
+ "right": "thin",
+ "bottom": "thin",
+ "left": "thin",
+ },
+ "alignment": {
+ "horizontal": "center",
+ "vertical": "top",
+ },
+ "fill": {
+ "patternType": 'solid',
+ 'fgColor': {
+ 'rgb': '006666FF',
+ 'tint': 0.3,
},
- }
-
- font_color = styles.Color('00FF0000')
- font = styles.Font(bold=True, color=font_color)
- side = styles.Side(style=styles.borders.BORDER_THIN)
- border = styles.Border(top=side, right=side, bottom=side, left=side)
- alignment = styles.Alignment(horizontal='center', vertical='top')
- fill_color = styles.Color(rgb='006666FF', tint=0.3)
- fill = styles.PatternFill(patternType='solid', fgColor=fill_color)
-
- number_format = '0.00'
-
- protection = styles.Protection(locked=True, hidden=False)
-
- kw = _OpenpyxlWriter._convert_to_style_kwargs(hstyle)
- assert kw['font'] == font
- assert kw['border'] == border
- assert kw['alignment'] == alignment
- assert kw['fill'] == fill
- assert kw['number_format'] == number_format
- assert kw['protection'] == protection
-
- def test_write_cells_merge_styled(self, ext):
- from pandas.io.formats.excel import ExcelCell
-
- sheet_name = 'merge_styled'
-
- sty_b1 = {'font': {'color': '00FF0000'}}
- sty_a2 = {'font': {'color': '0000FF00'}}
-
- initial_cells = [
- ExcelCell(col=1, row=0, val=42, style=sty_b1),
- ExcelCell(col=0, row=1, val=99, style=sty_a2),
- ]
-
- sty_merged = {'font': {'color': '000000FF', 'bold': True}}
- sty_kwargs = _OpenpyxlWriter._convert_to_style_kwargs(sty_merged)
- openpyxl_sty_merged = sty_kwargs['font']
- merge_cells = [
- ExcelCell(col=0, row=0, val='pandas',
- mergestart=1, mergeend=1, style=sty_merged),
- ]
-
- with ensure_clean(ext) as path:
- writer = _OpenpyxlWriter(path)
- writer.write_cells(initial_cells, sheet_name=sheet_name)
- writer.write_cells(merge_cells, sheet_name=sheet_name)
-
- wks = writer.sheets[sheet_name]
- xcell_b1 = wks['B1']
- xcell_a2 = wks['A2']
- assert xcell_b1.font == openpyxl_sty_merged
- assert xcell_a2.font == openpyxl_sty_merged
-
- @pytest.mark.parametrize("mode,expected", [
- ('w', ['baz']), ('a', ['foo', 'bar', 'baz'])])
- def test_write_append_mode(self, ext, mode, expected):
- import openpyxl
- df = DataFrame([1], columns=['baz'])
-
- with ensure_clean(ext) as f:
- wb = openpyxl.Workbook()
- wb.worksheets[0].title = 'foo'
- wb.worksheets[0]['A1'].value = 'foo'
- wb.create_sheet('bar')
- wb.worksheets[1]['A1'].value = 'bar'
- wb.save(f)
-
- writer = ExcelWriter(f, engine='openpyxl', mode=mode)
- df.to_excel(writer, sheet_name='baz', index=False)
- writer.save()
-
- wb2 = openpyxl.load_workbook(f)
- result = [sheet.title for sheet in wb2.worksheets]
- assert result == expected
-
- for index, cell_value in enumerate(expected):
- assert wb2.worksheets[index]['A1'].value == cell_value
+ },
+ "number_format": {
+ "format_code": "0.00"
+ },
+ "protection": {
+ "locked": True,
+ "hidden": False,
+ },
+ }
+
+ font_color = styles.Color('00FF0000')
+ font = styles.Font(bold=True, color=font_color)
+ side = styles.Side(style=styles.borders.BORDER_THIN)
+ border = styles.Border(top=side, right=side, bottom=side, left=side)
+ alignment = styles.Alignment(horizontal='center', vertical='top')
+ fill_color = styles.Color(rgb='006666FF', tint=0.3)
+ fill = styles.PatternFill(patternType='solid', fgColor=fill_color)
+
+ number_format = '0.00'
+
+ protection = styles.Protection(locked=True, hidden=False)
+
+ kw = _OpenpyxlWriter._convert_to_style_kwargs(hstyle)
+ assert kw['font'] == font
+ assert kw['border'] == border
+ assert kw['alignment'] == alignment
+ assert kw['fill'] == fill
+ assert kw['number_format'] == number_format
+ assert kw['protection'] == protection
+
+
+def test_write_cells_merge_styled(ext):
+ from pandas.io.formats.excel import ExcelCell
+
+ sheet_name = 'merge_styled'
+
+ sty_b1 = {'font': {'color': '00FF0000'}}
+ sty_a2 = {'font': {'color': '0000FF00'}}
+
+ initial_cells = [
+ ExcelCell(col=1, row=0, val=42, style=sty_b1),
+ ExcelCell(col=0, row=1, val=99, style=sty_a2),
+ ]
+
+ sty_merged = {'font': {'color': '000000FF', 'bold': True}}
+ sty_kwargs = _OpenpyxlWriter._convert_to_style_kwargs(sty_merged)
+ openpyxl_sty_merged = sty_kwargs['font']
+ merge_cells = [
+ ExcelCell(col=0, row=0, val='pandas',
+ mergestart=1, mergeend=1, style=sty_merged),
+ ]
+
+ with ensure_clean(ext) as path:
+ writer = _OpenpyxlWriter(path)
+ writer.write_cells(initial_cells, sheet_name=sheet_name)
+ writer.write_cells(merge_cells, sheet_name=sheet_name)
+
+ wks = writer.sheets[sheet_name]
+ xcell_b1 = wks['B1']
+ xcell_a2 = wks['A2']
+ assert xcell_b1.font == openpyxl_sty_merged
+ assert xcell_a2.font == openpyxl_sty_merged
+
+
+@pytest.mark.parametrize("mode,expected", [
+ ('w', ['baz']), ('a', ['foo', 'bar', 'baz'])])
+def test_write_append_mode(ext, mode, expected):
+ df = DataFrame([1], columns=['baz'])
+
+ with ensure_clean(ext) as f:
+ wb = openpyxl.Workbook()
+ wb.worksheets[0].title = 'foo'
+ wb.worksheets[0]['A1'].value = 'foo'
+ wb.create_sheet('bar')
+ wb.worksheets[1]['A1'].value = 'bar'
+ wb.save(f)
+
+ writer = ExcelWriter(f, engine='openpyxl', mode=mode)
+ df.to_excel(writer, sheet_name='baz', index=False)
+ writer.save()
+
+ wb2 = openpyxl.load_workbook(f)
+ result = [sheet.title for sheet in wb2.worksheets]
+ assert result == expected
+
+ for index, cell_value in enumerate(expected):
+ assert wb2.worksheets[index]['A1'].value == cell_value
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
index 18eac830d447e..b9fc9305a4033 100644
--- a/pandas/tests/io/excel/test_xlrd.py
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -1,4 +1,4 @@
-import pandas.util._test_decorators as td
+import pytest
import pandas as pd
import pandas.util.testing as tm
@@ -6,30 +6,24 @@
from pandas.io.excel import ExcelFile
+xlrd = pytest.importorskip("xlrd")
+xlwt = pytest.importorskip("xlwt")
-@td.skip_if_no('xlrd')
-class TestXlrdReader:
- """
- This is the base class for the xlrd tests, and 3 different file formats
- are supported: xls, xlsx, xlsm
- """
- @td.skip_if_no("xlwt")
- def test_read_xlrd_book(self, read_ext, frame):
- import xlrd
- df = frame
+def test_read_xlrd_book(read_ext, frame):
+ df = frame
- engine = "xlrd"
- sheet_name = "SheetA"
+ engine = "xlrd"
+ sheet_name = "SheetA"
- with ensure_clean(read_ext) as pth:
- df.to_excel(pth, sheet_name)
- book = xlrd.open_workbook(pth)
+ with ensure_clean(read_ext) as pth:
+ df.to_excel(pth, sheet_name)
+ book = xlrd.open_workbook(pth)
- with ExcelFile(book, engine=engine) as xl:
- result = pd.read_excel(xl, sheet_name, index_col=0)
- tm.assert_frame_equal(df, result)
-
- result = pd.read_excel(book, sheet_name=sheet_name,
- engine=engine, index_col=0)
+ with ExcelFile(book, engine=engine) as xl:
+ result = pd.read_excel(xl, sheet_name, index_col=0)
tm.assert_frame_equal(df, result)
+
+ result = pd.read_excel(book, sheet_name=sheet_name,
+ engine=engine, index_col=0)
+ tm.assert_frame_equal(df, result)
diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py
index f8c78c57f44a7..391a1085161f0 100644
--- a/pandas/tests/io/excel/test_xlsxwriter.py
+++ b/pandas/tests/io/excel/test_xlsxwriter.py
@@ -2,66 +2,64 @@
import pytest
-import pandas.util._test_decorators as td
-
from pandas import DataFrame
from pandas.util.testing import ensure_clean
from pandas.io.excel import ExcelWriter
+xlsxwriter = pytest.importorskip("xlsxwriter")
+
+pytestmark = pytest.mark.parametrize("ext", ['.xlsx'])
+
+
+def test_column_format(ext):
+ # Test that column formats are applied to cells. Test for issue #9167.
+ # Applicable to xlsxwriter only.
+ with warnings.catch_warnings():
+ # Ignore the openpyxl lxml warning.
+ warnings.simplefilter("ignore")
+ openpyxl = pytest.importorskip("openpyxl")
+
+ with ensure_clean(ext) as path:
+ frame = DataFrame({'A': [123456, 123456],
+ 'B': [123456, 123456]})
+
+ writer = ExcelWriter(path)
+ frame.to_excel(writer)
+
+ # Add a number format to col B and ensure it is applied to cells.
+ num_format = '#,##0'
+ write_workbook = writer.book
+ write_worksheet = write_workbook.worksheets()[0]
+ col_format = write_workbook.add_format({'num_format': num_format})
+ write_worksheet.set_column('B:B', None, col_format)
+ writer.save()
+
+ read_workbook = openpyxl.load_workbook(path)
+ try:
+ read_worksheet = read_workbook['Sheet1']
+ except TypeError:
+ # compat
+ read_worksheet = read_workbook.get_sheet_by_name(name='Sheet1')
+
+ # Get the number format from the cell.
+ try:
+ cell = read_worksheet['B2']
+ except TypeError:
+ # compat
+ cell = read_worksheet.cell('B2')
+
+ try:
+ read_num_format = cell.number_format
+ except Exception:
+ read_num_format = cell.style.number_format._format_code
+
+ assert read_num_format == num_format
+
+
+def test_write_append_mode_raises(ext):
+ msg = "Append mode is not supported with xlsxwriter!"
-@td.skip_if_no('xlsxwriter')
-@pytest.mark.parametrize("ext", ['.xlsx'])
-class TestXlsxWriterTests:
-
- @td.skip_if_no('openpyxl')
- def test_column_format(self, ext):
- # Test that column formats are applied to cells. Test for issue #9167.
- # Applicable to xlsxwriter only.
- with warnings.catch_warnings():
- # Ignore the openpyxl lxml warning.
- warnings.simplefilter("ignore")
- import openpyxl
-
- with ensure_clean(ext) as path:
- frame = DataFrame({'A': [123456, 123456],
- 'B': [123456, 123456]})
-
- writer = ExcelWriter(path)
- frame.to_excel(writer)
-
- # Add a number format to col B and ensure it is applied to cells.
- num_format = '#,##0'
- write_workbook = writer.book
- write_worksheet = write_workbook.worksheets()[0]
- col_format = write_workbook.add_format({'num_format': num_format})
- write_worksheet.set_column('B:B', None, col_format)
- writer.save()
-
- read_workbook = openpyxl.load_workbook(path)
- try:
- read_worksheet = read_workbook['Sheet1']
- except TypeError:
- # compat
- read_worksheet = read_workbook.get_sheet_by_name(name='Sheet1')
-
- # Get the number format from the cell.
- try:
- cell = read_worksheet['B2']
- except TypeError:
- # compat
- cell = read_worksheet.cell('B2')
-
- try:
- read_num_format = cell.number_format
- except Exception:
- read_num_format = cell.style.number_format._format_code
-
- assert read_num_format == num_format
-
- def test_write_append_mode_raises(self, ext):
- msg = "Append mode is not supported with xlsxwriter!"
-
- with ensure_clean(ext) as f:
- with pytest.raises(ValueError, match=msg):
- ExcelWriter(f, engine='xlsxwriter', mode='a')
+ with ensure_clean(ext) as f:
+ with pytest.raises(ValueError, match=msg):
+ ExcelWriter(f, engine='xlsxwriter', mode='a')
diff --git a/pandas/tests/io/excel/test_xlwt.py b/pandas/tests/io/excel/test_xlwt.py
index bbed8a3d67ecf..9c687f1f514f9 100644
--- a/pandas/tests/io/excel/test_xlwt.py
+++ b/pandas/tests/io/excel/test_xlwt.py
@@ -1,69 +1,68 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
import pandas as pd
from pandas import DataFrame, MultiIndex
from pandas.util.testing import ensure_clean
from pandas.io.excel import ExcelWriter, _XlwtWriter
+xlwt = pytest.importorskip("xlwt")
-@td.skip_if_no('xlwt')
-@pytest.mark.parametrize("ext,", ['.xls'])
-class TestXlwtTests:
-
- def test_excel_raise_error_on_multiindex_columns_and_no_index(
- self, ext):
- # MultiIndex as columns is not yet implemented 9794
- cols = MultiIndex.from_tuples([('site', ''),
- ('2014', 'height'),
- ('2014', 'weight')])
- df = DataFrame(np.random.randn(10, 3), columns=cols)
- with pytest.raises(NotImplementedError):
- with ensure_clean(ext) as path:
- df.to_excel(path, index=False)
-
- def test_excel_multiindex_columns_and_index_true(self, ext):
- cols = MultiIndex.from_tuples([('site', ''),
- ('2014', 'height'),
- ('2014', 'weight')])
- df = pd.DataFrame(np.random.randn(10, 3), columns=cols)
- with ensure_clean(ext) as path:
- df.to_excel(path, index=True)
-
- def test_excel_multiindex_index(self, ext):
- # MultiIndex as index works so assert no error #9794
- cols = MultiIndex.from_tuples([('site', ''),
- ('2014', 'height'),
- ('2014', 'weight')])
- df = DataFrame(np.random.randn(3, 10), index=cols)
+pytestmark = pytest.mark.parametrize("ext,", ['.xls'])
+
+
+def test_excel_raise_error_on_multiindex_columns_and_no_index(ext):
+ # MultiIndex as columns is not yet implemented 9794
+ cols = MultiIndex.from_tuples([('site', ''),
+ ('2014', 'height'),
+ ('2014', 'weight')])
+ df = DataFrame(np.random.randn(10, 3), columns=cols)
+ with pytest.raises(NotImplementedError):
with ensure_clean(ext) as path:
df.to_excel(path, index=False)
- def test_to_excel_styleconverter(self, ext):
- import xlwt
-
- hstyle = {"font": {"bold": True},
- "borders": {"top": "thin",
- "right": "thin",
- "bottom": "thin",
- "left": "thin"},
- "alignment": {"horizontal": "center", "vertical": "top"}}
-
- xls_style = _XlwtWriter._convert_to_style(hstyle)
- assert xls_style.font.bold
- assert xlwt.Borders.THIN == xls_style.borders.top
- assert xlwt.Borders.THIN == xls_style.borders.right
- assert xlwt.Borders.THIN == xls_style.borders.bottom
- assert xlwt.Borders.THIN == xls_style.borders.left
- assert xlwt.Alignment.HORZ_CENTER == xls_style.alignment.horz
- assert xlwt.Alignment.VERT_TOP == xls_style.alignment.vert
-
- def test_write_append_mode_raises(self, ext):
- msg = "Append mode is not supported with xlwt!"
-
- with ensure_clean(ext) as f:
- with pytest.raises(ValueError, match=msg):
- ExcelWriter(f, engine='xlwt', mode='a')
+
+def test_excel_multiindex_columns_and_index_true(ext):
+ cols = MultiIndex.from_tuples([('site', ''),
+ ('2014', 'height'),
+ ('2014', 'weight')])
+ df = pd.DataFrame(np.random.randn(10, 3), columns=cols)
+ with ensure_clean(ext) as path:
+ df.to_excel(path, index=True)
+
+
+def test_excel_multiindex_index(ext):
+ # MultiIndex as index works so assert no error #9794
+ cols = MultiIndex.from_tuples([('site', ''),
+ ('2014', 'height'),
+ ('2014', 'weight')])
+ df = DataFrame(np.random.randn(3, 10), index=cols)
+ with ensure_clean(ext) as path:
+ df.to_excel(path, index=False)
+
+
+def test_to_excel_styleconverter(ext):
+ hstyle = {"font": {"bold": True},
+ "borders": {"top": "thin",
+ "right": "thin",
+ "bottom": "thin",
+ "left": "thin"},
+ "alignment": {"horizontal": "center", "vertical": "top"}}
+
+ xls_style = _XlwtWriter._convert_to_style(hstyle)
+ assert xls_style.font.bold
+ assert xlwt.Borders.THIN == xls_style.borders.top
+ assert xlwt.Borders.THIN == xls_style.borders.right
+ assert xlwt.Borders.THIN == xls_style.borders.bottom
+ assert xlwt.Borders.THIN == xls_style.borders.left
+ assert xlwt.Alignment.HORZ_CENTER == xls_style.alignment.horz
+ assert xlwt.Alignment.VERT_TOP == xls_style.alignment.vert
+
+
+def test_write_append_mode_raises(ext):
+ msg = "Append mode is not supported with xlwt!"
+
+ with ensure_clean(ext) as f:
+ with pytest.raises(ValueError, match=msg):
+ ExcelWriter(f, engine='xlwt', mode='a')
| xref https://github.com/pandas-dev/pandas/pull/26755#pullrequestreview-247416090
the larger files `pandas/tests/io/excel/test_readers.py` and `pandas/tests/io/excel/test_writers.py` have been left for separate PRs
any idiom changes other than required to declass are also omitted to make the diff easier to check. | https://api.github.com/repos/pandas-dev/pandas/pulls/26764 | 2019-06-10T10:15:53Z | 2019-06-10T17:32:01Z | 2019-06-10T17:32:01Z | 2019-06-11T14:49:29Z |
TST/CLN: reuse float_frame fixture in tests\reshape\test_concat.py | diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py
index ecd62380d8c65..1420d4420e430 100644
--- a/pandas/tests/reshape/test_concat.py
+++ b/pandas/tests/reshape/test_concat.py
@@ -39,15 +39,7 @@ def sort_with_none(request):
return request.param
-class ConcatenateBase:
-
- def setup_method(self, method):
- self.frame = DataFrame(tm.getSeriesData())
- self.mixed_frame = self.frame.copy()
- self.mixed_frame['foo'] = 'bar'
-
-
-class TestConcatAppendCommon(ConcatenateBase):
+class TestConcatAppendCommon:
"""
Test common dtype coercion rules between concat and append.
@@ -731,17 +723,20 @@ def test_concat_categorical_empty(self):
tm.assert_series_equal(s2.append(s1, ignore_index=True), exp)
-class TestAppend(ConcatenateBase):
+class TestAppend:
+
+ def test_append(self, sort, float_frame):
+ mixed_frame = float_frame.copy()
+ mixed_frame['foo'] = 'bar'
- def test_append(self, sort):
- begin_index = self.frame.index[:5]
- end_index = self.frame.index[5:]
+ begin_index = float_frame.index[:5]
+ end_index = float_frame.index[5:]
- begin_frame = self.frame.reindex(begin_index)
- end_frame = self.frame.reindex(end_index)
+ begin_frame = float_frame.reindex(begin_index)
+ end_frame = float_frame.reindex(end_index)
appended = begin_frame.append(end_frame)
- tm.assert_almost_equal(appended['A'], self.frame['A'])
+ tm.assert_almost_equal(appended['A'], float_frame['A'])
del end_frame['A']
partial_appended = begin_frame.append(end_frame, sort=sort)
@@ -751,35 +746,35 @@ def test_append(self, sort):
assert 'A' in partial_appended
# mixed type handling
- appended = self.mixed_frame[:5].append(self.mixed_frame[5:])
- tm.assert_frame_equal(appended, self.mixed_frame)
+ appended = mixed_frame[:5].append(mixed_frame[5:])
+ tm.assert_frame_equal(appended, mixed_frame)
# what to test here
- mixed_appended = self.mixed_frame[:5].append(self.frame[5:], sort=sort)
- mixed_appended2 = self.frame[:5].append(self.mixed_frame[5:],
- sort=sort)
+ mixed_appended = mixed_frame[:5].append(float_frame[5:], sort=sort)
+ mixed_appended2 = float_frame[:5].append(mixed_frame[5:], sort=sort)
# all equal except 'foo' column
tm.assert_frame_equal(
mixed_appended.reindex(columns=['A', 'B', 'C', 'D']),
mixed_appended2.reindex(columns=['A', 'B', 'C', 'D']))
- # append empty
+ def test_append_empty(self, float_frame):
empty = DataFrame()
- appended = self.frame.append(empty)
- tm.assert_frame_equal(self.frame, appended)
- assert appended is not self.frame
+ appended = float_frame.append(empty)
+ tm.assert_frame_equal(float_frame, appended)
+ assert appended is not float_frame
- appended = empty.append(self.frame)
- tm.assert_frame_equal(self.frame, appended)
- assert appended is not self.frame
+ appended = empty.append(float_frame)
+ tm.assert_frame_equal(float_frame, appended)
+ assert appended is not float_frame
- # Overlap
+ def test_append_overlap_raises(self, float_frame):
msg = "Indexes have overlapping values"
with pytest.raises(ValueError, match=msg):
- self.frame.append(self.frame, verify_integrity=True)
+ float_frame.append(float_frame, verify_integrity=True)
+ def test_append_new_columns(self):
# see gh-6129: new columns
df = DataFrame({'a': {'x': 1, 'y': 2}, 'b': {'x': 3, 'y': 4}})
row = Series([5, 6, 7], index=['a', 'b', 'c'], name='z')
@@ -851,17 +846,17 @@ def test_append_different_columns(self, sort):
assert isna(appended['strings'][0:4]).all()
assert isna(appended['bools'][5:]).all()
- def test_append_many(self, sort):
- chunks = [self.frame[:5], self.frame[5:10],
- self.frame[10:15], self.frame[15:]]
+ def test_append_many(self, sort, float_frame):
+ chunks = [float_frame[:5], float_frame[5:10],
+ float_frame[10:15], float_frame[15:]]
result = chunks[0].append(chunks[1:])
- tm.assert_frame_equal(result, self.frame)
+ tm.assert_frame_equal(result, float_frame)
chunks[-1] = chunks[-1].copy()
chunks[-1]['foo'] = 'bar'
result = chunks[0].append(chunks[1:], sort=sort)
- tm.assert_frame_equal(result.loc[:, self.frame.columns], self.frame)
+ tm.assert_frame_equal(result.loc[:, float_frame.columns], float_frame)
assert (result['foo'][15:] == 'bar').all()
assert result['foo'][:15].isna().all()
@@ -1042,7 +1037,7 @@ def test_append_empty_frame_to_series_with_dateutil_tz(self):
assert_frame_equal(result, expected)
-class TestConcatenate(ConcatenateBase):
+class TestConcatenate:
def test_concat_copy(self):
df = DataFrame(np.random.randn(4, 3))
| https://api.github.com/repos/pandas-dev/pandas/pulls/26763 | 2019-06-10T08:26:17Z | 2019-06-10T21:52:41Z | 2019-06-10T21:52:41Z | 2019-06-11T14:50:52Z | |
BLD: use unsigned instead of signed for lengths, avoid build warnings | diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index 88b918e9cc515..b73b70caf1597 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -119,24 +119,24 @@ cdef extern from "parser/tokenizer.h":
# where to write out tokenized data
char *stream
- int64_t stream_len
- int64_t stream_cap
+ uint64_t stream_len
+ uint64_t stream_cap
# Store words in (potentially ragged) matrix for now, hmm
char **words
int64_t *word_starts # where we are in the stream
- int64_t words_len
- int64_t words_cap
- int64_t max_words_cap # maximum word cap encountered
+ uint64_t words_len
+ uint64_t words_cap
+ uint64_t max_words_cap # maximum word cap encountered
char *pword_start # pointer to stream start of current field
int64_t word_start # position start of current field
int64_t *line_start # position in words for start of line
int64_t *line_fields # Number of fields in each line
- int64_t lines # Number of lines observed
- int64_t file_lines # Number of lines observed (with bad/skipped)
- int64_t lines_cap # Vector capacity
+ uint64_t lines # Number of lines observed
+ uint64_t file_lines # Number of lines observed (with bad/skipped)
+ uint64_t lines_cap # Vector capacity
# Tokenizing stuff
ParserState state
@@ -168,7 +168,7 @@ cdef extern from "parser/tokenizer.h":
int header # Boolean: 1: has header, 0: no header
int64_t header_start # header row start
- int64_t header_end # header row end
+ uint64_t header_end # header row end
void *skipset
PyObject *skipfunc
diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c
index 723bf56a79512..3146e49455609 100644
--- a/pandas/_libs/src/parser/tokenizer.c
+++ b/pandas/_libs/src/parser/tokenizer.c
@@ -71,9 +71,9 @@ static void free_if_not_null(void **ptr) {
*/
-static void *grow_buffer(void *buffer, int64_t length, int64_t *capacity,
+static void *grow_buffer(void *buffer, uint64_t length, uint64_t *capacity,
int64_t space, int64_t elsize, int *error) {
- int64_t cap = *capacity;
+ uint64_t cap = *capacity;
void *newbuffer = buffer;
// Can we fit potentially nbytes tokens (+ null terminators) in the stream?
@@ -248,7 +248,7 @@ void parser_del(parser_t *self) {
}
static int make_stream_space(parser_t *self, size_t nbytes) {
- int64_t i, cap, length;
+ uint64_t i, cap, length;
int status;
void *orig_ptr, *newptr;
@@ -263,7 +263,7 @@ static int make_stream_space(parser_t *self, size_t nbytes) {
("\n\nmake_stream_space: nbytes = %zu. grow_buffer(self->stream...)\n",
nbytes))
self->stream = (char *)grow_buffer((void *)self->stream, self->stream_len,
- (int64_t*)&self->stream_cap, nbytes * 2,
+ &self->stream_cap, nbytes * 2,
sizeof(char), &status);
TRACE(
("make_stream_space: self->stream=%p, self->stream_len = %zu, "
@@ -305,7 +305,7 @@ static int make_stream_space(parser_t *self, size_t nbytes) {
self->words =
(char **)grow_buffer((void *)self->words, length,
- (int64_t*)&self->words_cap, nbytes,
+ &self->words_cap, nbytes,
sizeof(char *), &status);
TRACE(
("make_stream_space: grow_buffer(self->self->words, %zu, %zu, %zu, "
@@ -336,7 +336,7 @@ static int make_stream_space(parser_t *self, size_t nbytes) {
cap = self->lines_cap;
self->line_start =
(int64_t *)grow_buffer((void *)self->line_start, self->lines + 1,
- (int64_t*)&self->lines_cap, nbytes,
+ &self->lines_cap, nbytes,
sizeof(int64_t), &status);
TRACE((
"make_stream_space: grow_buffer(self->line_start, %zu, %zu, %zu, %d)\n",
@@ -471,7 +471,7 @@ static int end_line(parser_t *self) {
return 0;
}
- if (!(self->lines <= (int64_t) self->header_end + 1) &&
+ if (!(self->lines <= self->header_end + 1) &&
(self->expected_fields < 0 && fields > ex_fields) && !(self->usecols)) {
// increment file line count
self->file_lines++;
@@ -507,7 +507,7 @@ static int end_line(parser_t *self) {
}
} else {
// missing trailing delimiters
- if ((self->lines >= (int64_t) self->header_end + 1) &&
+ if ((self->lines >= self->header_end + 1) &&
fields < ex_fields) {
// might overrun the buffer when closing fields
if (make_stream_space(self, ex_fields - fields) < 0) {
@@ -651,7 +651,7 @@ static int parser_buffer_bytes(parser_t *self, size_t nbytes) {
stream = self->stream + self->stream_len; \
slen = self->stream_len; \
self->state = STATE; \
- if (line_limit > 0 && self->lines == start_lines + (int64_t)line_limit) { \
+ if (line_limit > 0 && self->lines == start_lines + line_limit) { \
goto linelimit; \
}
@@ -666,7 +666,7 @@ static int parser_buffer_bytes(parser_t *self, size_t nbytes) {
stream = self->stream + self->stream_len; \
slen = self->stream_len; \
self->state = STATE; \
- if (line_limit > 0 && self->lines == start_lines + (int64_t)line_limit) { \
+ if (line_limit > 0 && self->lines == start_lines + line_limit) { \
goto linelimit; \
}
@@ -737,7 +737,8 @@ int skip_this_line(parser_t *self, int64_t rownum) {
int tokenize_bytes(parser_t *self,
size_t line_limit, int64_t start_lines) {
- int64_t i, slen;
+ int64_t i;
+ uint64_t slen;
int should_skip;
char c;
char *stream;
@@ -1203,7 +1204,8 @@ static int parser_handle_eof(parser_t *self) {
}
int parser_consume_rows(parser_t *self, size_t nrows) {
- int64_t i, offset, word_deletions, char_count;
+ int64_t offset, word_deletions;
+ uint64_t char_count, i;
if (nrows > self->lines) {
nrows = self->lines;
@@ -1229,6 +1231,8 @@ int parser_consume_rows(parser_t *self, size_t nrows) {
self->stream_len -= char_count;
/* move token metadata */
+ // Note: We should always have words_len < word_deletions, so this
+ // subtraction will remain appropriately-typed.
for (i = 0; i < self->words_len - word_deletions; ++i) {
offset = i + word_deletions;
@@ -1242,6 +1246,8 @@ int parser_consume_rows(parser_t *self, size_t nrows) {
self->word_start -= char_count;
/* move line metadata */
+ // Note: We should always have self->lines - nrows + 1 >= 0, so this
+ // subtraction will remain appropriately-typed.
for (i = 0; i < self->lines - nrows + 1; ++i) {
offset = i + nrows;
self->line_start[i] = self->line_start[offset] - word_deletions;
@@ -1265,7 +1271,7 @@ int parser_trim_buffers(parser_t *self) {
size_t new_cap;
void *newptr;
- int64_t i;
+ uint64_t i;
/**
* Before we free up space and trim, we should
diff --git a/pandas/_libs/src/parser/tokenizer.h b/pandas/_libs/src/parser/tokenizer.h
index b6d5d6937f4db..66ef1887d6bc3 100644
--- a/pandas/_libs/src/parser/tokenizer.h
+++ b/pandas/_libs/src/parser/tokenizer.h
@@ -104,24 +104,24 @@ typedef struct parser_t {
// where to write out tokenized data
char *stream;
- int64_t stream_len;
- int64_t stream_cap;
+ uint64_t stream_len;
+ uint64_t stream_cap;
// Store words in (potentially ragged) matrix for now, hmm
char **words;
int64_t *word_starts; // where we are in the stream
- int64_t words_len;
- int64_t words_cap;
- int64_t max_words_cap; // maximum word cap encountered
+ uint64_t words_len;
+ uint64_t words_cap;
+ uint64_t max_words_cap; // maximum word cap encountered
char *pword_start; // pointer to stream start of current field
int64_t word_start; // position start of current field
int64_t *line_start; // position in words for start of line
int64_t *line_fields; // Number of fields in each line
- int64_t lines; // Number of (good) lines observed
- int64_t file_lines; // Number of lines (including bad or skipped)
- int64_t lines_cap; // Vector capacity
+ uint64_t lines; // Number of (good) lines observed
+ uint64_t file_lines; // Number of lines (including bad or skipped)
+ uint64_t lines_cap; // Vector capacity
// Tokenizing stuff
ParserState state;
@@ -153,7 +153,7 @@ typedef struct parser_t {
int header; // Boolean: 1: has header, 0: no header
int64_t header_start; // header row start
- int64_t header_end; // header row end
+ uint64_t header_end; // header row end
void *skipset;
PyObject *skipfunc;
| I'm much more confident about the other two BLD PRs (#26757, #26758) than this, largely because:
- [ ] in a couple of comments here I wrote that a certain term should always be non-negative. I haven't actually confirmed that this is always the case
- [ ] This changed things from int64_t to uint64_t, but could also reasonably have changed them to size_t. I don't have a compelling reason for the correctness of the uint64_t choice. | https://api.github.com/repos/pandas-dev/pandas/pulls/26759 | 2019-06-10T03:30:26Z | 2019-06-22T17:19:03Z | 2019-06-22T17:19:03Z | 2019-06-22T18:07:48Z |
BLD: fix build warnings in tslib by casting explicitly to object | diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 3ea70541382de..0eb3e3c79aa47 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -127,7 +127,7 @@ def ints_to_pydatetime(int64_t[:] arr, object tz=None, object freq=None,
for i in range(n):
value = arr[i]
if value == NPY_NAT:
- result[i] = NaT
+ result[i] = <object>NaT
else:
dt64_to_dtstruct(value, &dts)
result[i] = func_create(value, dts, tz, freq)
@@ -135,7 +135,7 @@ def ints_to_pydatetime(int64_t[:] arr, object tz=None, object freq=None,
for i in range(n):
value = arr[i]
if value == NPY_NAT:
- result[i] = NaT
+ result[i] = <object>NaT
else:
# Python datetime objects do not support nanosecond
# resolution (yet, PEP 564). Need to compute new value
@@ -152,7 +152,7 @@ def ints_to_pydatetime(int64_t[:] arr, object tz=None, object freq=None,
for i in range(n):
value = arr[i]
if value == NPY_NAT:
- result[i] = NaT
+ result[i] = <object>NaT
else:
# Adjust datetime64 timestamp, recompute datetimestruct
dt64_to_dtstruct(value + delta, &dts)
@@ -164,7 +164,7 @@ def ints_to_pydatetime(int64_t[:] arr, object tz=None, object freq=None,
for i in range(n):
value = arr[i]
if value == NPY_NAT:
- result[i] = NaT
+ result[i] = <object>NaT
else:
# Adjust datetime64 timestamp, recompute datetimestruct
pos = trans.searchsorted(value, side='right') - 1
@@ -175,7 +175,7 @@ def ints_to_pydatetime(int64_t[:] arr, object tz=None, object freq=None,
for i in range(n):
value = arr[i]
if value == NPY_NAT:
- result[i] = NaT
+ result[i] = <object>NaT
else:
# Adjust datetime64 timestamp, recompute datetimestruct
pos = trans.searchsorted(value, side='right') - 1
@@ -439,11 +439,11 @@ def array_with_unit_to_datetime(ndarray values, object unit,
val = values[i]
if checknull_with_nat(val):
- oresult[i] = NaT
+ oresult[i] = <object>NaT
elif is_integer_object(val) or is_float_object(val):
if val != val or val == NPY_NAT:
- oresult[i] = NaT
+ oresult[i] = <object>NaT
else:
try:
oresult[i] = Timestamp(cast_from_unit(val, unit))
@@ -452,7 +452,7 @@ def array_with_unit_to_datetime(ndarray values, object unit,
elif isinstance(val, str):
if len(val) == 0 or val in nat_strings:
- oresult[i] = NaT
+ oresult[i] = <object>NaT
else:
oresult[i] = val
@@ -816,7 +816,7 @@ cdef array_to_datetime_object(ndarray[object] values, str errors,
check_dts_bounds(&dts)
except (ValueError, OverflowError):
if is_coerce:
- oresult[i] = NaT
+ oresult[i] = <object>NaT
continue
if is_raise:
raise
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index 16093ddd77667..ad60165e98d4f 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -117,7 +117,7 @@ def ints_to_pytimedelta(int64_t[:] arr, box=False):
value = arr[i]
if value == NPY_NAT:
- result[i] = NaT
+ result[i] = <object>NaT
else:
if box:
result[i] = Timedelta(value)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26758 | 2019-06-10T03:20:47Z | 2019-06-10T12:30:42Z | 2019-06-10T12:30:42Z | 2019-06-10T13:56:20Z |
BLD: fix build warnings | diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx
index faa7ab95fd28b..f9e1ebb11116b 100644
--- a/pandas/_libs/join.pyx
+++ b/pandas/_libs/join.pyx
@@ -119,7 +119,8 @@ def left_outer_join(const int64_t[:] left, const int64_t[:] right,
right_indexer = _get_result_indexer(right_sorter, right_indexer)
if not sort: # if not asked to sort, revert to original order
- if len(left) == len(left_indexer):
+ # cast to avoid build warning GH#26757
+ if <Py_ssize_t>len(left) == len(left_indexer):
# no multiple matches for any row on the left
# this is a short-cut to avoid groupsort_indexer
# otherwise, the `else` path also works in this case
diff --git a/pandas/_libs/ops.pyx b/pandas/_libs/ops.pyx
index a86600ef6de9c..27f7016ab4057 100644
--- a/pandas/_libs/ops.pyx
+++ b/pandas/_libs/ops.pyx
@@ -122,7 +122,7 @@ def vec_compare(object[:] left, object[:] right, object op):
ndarray[uint8_t, cast=True] result
int flag
- if n != len(right):
+ if n != <Py_ssize_t>len(right):
raise ValueError('Arrays were different lengths: {n} vs {nright}'
.format(n=n, nright=len(right)))
@@ -223,7 +223,7 @@ def vec_binop(object[:] left, object[:] right, object op):
Py_ssize_t i, n = len(left)
object[:] result
- if n != len(right):
+ if n != <Py_ssize_t>len(right):
raise ValueError('Arrays were different lengths: {n} vs {nright}'
.format(n=n, nright=len(right)))
diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx
index 068ad016459a8..eb99f090e8565 100644
--- a/pandas/_libs/tslibs/parsing.pyx
+++ b/pandas/_libs/tslibs/parsing.pyx
@@ -8,6 +8,7 @@ from io import StringIO
from libc.string cimport strchr
import cython
+from cython import Py_ssize_t
from cpython cimport PyObject_Str, PyUnicode_Join
@@ -607,7 +608,8 @@ def try_parse_date_and_time(object[:] dates, object[:] times,
object[:] result
n = len(dates)
- if len(times) != n:
+ # Cast to avoid build warning see GH#26757
+ if <Py_ssize_t>len(times) != n:
raise ValueError('Length of dates and times must be equal')
result = np.empty(n, dtype='O')
@@ -643,7 +645,8 @@ def try_parse_year_month_day(object[:] years, object[:] months,
object[:] result
n = len(years)
- if len(months) != n or len(days) != n:
+ # Cast to avoid build warning see GH#26757
+ if <Py_ssize_t>len(months) != n or <Py_ssize_t>len(days) != n:
raise ValueError('Length of years/months/days must all be equal')
result = np.empty(n, dtype='O')
@@ -668,8 +671,10 @@ def try_parse_datetime_components(object[:] years,
double micros
n = len(years)
- if (len(months) != n or len(days) != n or len(hours) != n or
- len(minutes) != n or len(seconds) != n):
+ # Cast to avoid build warning see GH#26757
+ if (<Py_ssize_t>len(months) != n or <Py_ssize_t>len(days) != n or
+ <Py_ssize_t>len(hours) != n or <Py_ssize_t>len(minutes) != n or
+ <Py_ssize_t>len(seconds) != n):
raise ValueError('Length of all datetime components must be equal')
result = np.empty(n, dtype='O')
diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx
index de755ca0245e6..48b554ca02a9d 100644
--- a/pandas/_libs/window.pyx
+++ b/pandas/_libs/window.pyx
@@ -1827,7 +1827,7 @@ def ewmcov(float64_t[:] input_x, float64_t[:] input_y,
Py_ssize_t i, nobs
ndarray[float64_t] output
- if len(input_y) != N:
+ if <Py_ssize_t>len(input_y) != N:
raise ValueError("arrays are of different lengths "
"({N} and {len_y})".format(N=N, len_y=len(input_y)))
diff --git a/pandas/io/sas/sas.pyx b/pandas/io/sas/sas.pyx
index 022c95397b76f..6378198225516 100644
--- a/pandas/io/sas/sas.pyx
+++ b/pandas/io/sas/sas.pyx
@@ -1,5 +1,6 @@
# cython: profile=False
# cython: boundscheck=False, initializedcheck=False
+from cython import Py_ssize_t
import numpy as np
import pandas.io.sas.sas_constants as const
@@ -18,8 +19,9 @@ cdef const uint8_t[:] rle_decompress(int result_length,
cdef:
uint8_t control_byte, x
uint8_t[:] result = np.zeros(result_length, np.uint8)
- int rpos = 0, ipos = 0, length = len(inbuff)
+ int rpos = 0
int i, nbytes, end_of_first_byte
+ Py_ssize_t ipos = 0, length = len(inbuff)
while ipos < length:
control_byte = inbuff[ipos] & 0xF0
@@ -123,12 +125,13 @@ cdef const uint8_t[:] rdc_decompress(int result_length,
cdef:
uint8_t cmd
uint16_t ctrl_bits, ctrl_mask = 0, ofs, cnt
- int ipos = 0, rpos = 0, k
+ int rpos = 0, k
uint8_t[:] outbuff = np.zeros(result_length, dtype=np.uint8)
+ Py_ssize_t ipos = 0, length = len(inbuff)
ii = -1
- while ipos < len(inbuff):
+ while ipos < length:
ii += 1
ctrl_mask = ctrl_mask >> 1
if ctrl_mask == 0:
| xref #25995, #17936
AFAICT these warnings are caused by cython casting `len(some_ndarray)` to `int` or `Py_ssize_t` but casting `len(some_memoryview)` to `size_t`. Easiest fix is to declare the affected len variables as `size_t` since we know they'll never be negative. | https://api.github.com/repos/pandas-dev/pandas/pulls/26757 | 2019-06-10T01:58:04Z | 2019-06-12T15:44:56Z | 2019-06-12T15:44:56Z | 2019-06-12T16:52:48Z |
TST/CLN: reuse float_frame fixture in tests\io\formats\test_format.py | diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index 2779e3f56f923..bae2470459f62 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -11,7 +11,6 @@
from shutil import get_terminal_size
import sys
import textwrap
-import warnings
import dateutil
import numpy as np
@@ -31,8 +30,6 @@
use_32bit_repr = is_platform_windows() or is_platform_32bit()
-_frame = DataFrame(tm.getSeriesData())
-
def curpath():
pth, _ = os.path.split(os.path.abspath(__file__))
@@ -101,18 +98,9 @@ def has_expanded_repr(df):
return False
+@pytest.mark.filterwarnings('ignore::FutureWarning:.*format')
class TestDataFrameFormatting:
- def setup_method(self, method):
- self.warn_filters = warnings.filters
- warnings.filterwarnings('ignore', category=FutureWarning,
- module=".*format")
-
- self.frame = _frame.copy()
-
- def teardown_method(self, method):
- warnings.filters = self.warn_filters
-
def test_repr_embedded_ndarray(self):
arr = np.empty(10, dtype=[('err', object)])
for i in range(len(arr)):
@@ -123,17 +111,18 @@ def test_repr_embedded_ndarray(self):
repr(df)
df.to_string()
- def test_eng_float_formatter(self):
- self.frame.loc[5] = 0
+ def test_eng_float_formatter(self, float_frame):
+ df = float_frame
+ df.loc[5] = 0
fmt.set_eng_float_format()
- repr(self.frame)
+ repr(df)
fmt.set_eng_float_format(use_eng_prefix=True)
- repr(self.frame)
+ repr(df)
fmt.set_eng_float_format(accuracy=0)
- repr(self.frame)
+ repr(df)
tm.reset_display_options()
def test_show_null_counts(self):
@@ -467,7 +456,7 @@ def test_to_string_repr_unicode(self):
finally:
sys.stdin = _stdin
- def test_to_string_unicode_columns(self):
+ def test_to_string_unicode_columns(self, float_frame):
df = DataFrame({'\u03c3': np.arange(10.)})
buf = StringIO()
@@ -478,7 +467,7 @@ def test_to_string_unicode_columns(self):
df.info(buf=buf)
buf.getvalue()
- result = self.frame.to_string()
+ result = float_frame.to_string()
assert isinstance(result, str)
def test_to_string_utf8_columns(self):
@@ -1513,14 +1502,15 @@ def test_show_dimensions(self):
assert '5 rows' not in str(df)
assert '5 rows' not in df._repr_html_()
- def test_repr_html(self):
- self.frame._repr_html_()
+ def test_repr_html(self, float_frame):
+ df = float_frame
+ df._repr_html_()
fmt.set_option('display.max_rows', 1, 'display.max_columns', 1)
- self.frame._repr_html_()
+ df._repr_html_()
fmt.set_option('display.notebook_repr_html', False)
- self.frame._repr_html_()
+ df._repr_html_()
tm.reset_display_options()
@@ -1698,16 +1688,18 @@ def test_info_repr_html(self):
'display.max_columns', max_cols):
assert '<class' in df._repr_html_()
- def test_fake_qtconsole_repr_html(self):
+ def test_fake_qtconsole_repr_html(self, float_frame):
+ df = float_frame
+
def get_ipython():
return {'config': {'KernelApp':
{'parent_appname': 'ipython-qtconsole'}}}
- repstr = self.frame._repr_html_()
+ repstr = df._repr_html_()
assert repstr is not None
fmt.set_option('display.max_rows', 5, 'display.max_columns', 2)
- repstr = self.frame._repr_html_()
+ repstr = df._repr_html_()
assert 'class' in repstr # info fallback
tm.reset_display_options()
| follow-on from #26603
| https://api.github.com/repos/pandas-dev/pandas/pulls/26756 | 2019-06-09T21:17:33Z | 2019-06-09T21:58:23Z | 2019-06-09T21:58:23Z | 2019-06-10T07:59:54Z |
Split test_excel into submodule | diff --git a/pandas/tests/io/excel/__init__.py b/pandas/tests/io/excel/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/io/excel/conftest.py b/pandas/tests/io/excel/conftest.py
new file mode 100644
index 0000000000000..935db254bd2e5
--- /dev/null
+++ b/pandas/tests/io/excel/conftest.py
@@ -0,0 +1,38 @@
+import pytest
+
+import pandas.util.testing as tm
+
+from pandas.io.parsers import read_csv
+
+
+@pytest.fixture
+def frame(float_frame):
+ return float_frame[:10]
+
+
+@pytest.fixture
+def tsframe():
+ return tm.makeTimeDataFrame()[:5]
+
+
+@pytest.fixture(params=[True, False])
+def merge_cells(request):
+ return request.param
+
+
+@pytest.fixture
+def df_ref():
+ """
+ Obtain the reference data from read_csv with the Python engine.
+ """
+ df_ref = read_csv('test1.csv', index_col=0,
+ parse_dates=True, engine='python')
+ return df_ref
+
+
+@pytest.fixture(params=['.xls', '.xlsx', '.xlsm'])
+def read_ext(request):
+ """
+ Valid extensions for reading Excel files.
+ """
+ return request.param
diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py
new file mode 100644
index 0000000000000..8be96a771f3aa
--- /dev/null
+++ b/pandas/tests/io/excel/test_openpyxl.py
@@ -0,0 +1,124 @@
+import pytest
+
+import pandas.util._test_decorators as td
+
+from pandas import DataFrame
+from pandas.util.testing import ensure_clean
+
+from pandas.io.excel import ExcelWriter, _OpenpyxlWriter
+
+
+@td.skip_if_no('openpyxl')
+@pytest.mark.parametrize("ext", ['.xlsx'])
+class TestOpenpyxlTests:
+
+ def test_to_excel_styleconverter(self, ext):
+ from openpyxl import styles
+
+ hstyle = {
+ "font": {
+ "color": '00FF0000',
+ "bold": True,
+ },
+ "borders": {
+ "top": "thin",
+ "right": "thin",
+ "bottom": "thin",
+ "left": "thin",
+ },
+ "alignment": {
+ "horizontal": "center",
+ "vertical": "top",
+ },
+ "fill": {
+ "patternType": 'solid',
+ 'fgColor': {
+ 'rgb': '006666FF',
+ 'tint': 0.3,
+ },
+ },
+ "number_format": {
+ "format_code": "0.00"
+ },
+ "protection": {
+ "locked": True,
+ "hidden": False,
+ },
+ }
+
+ font_color = styles.Color('00FF0000')
+ font = styles.Font(bold=True, color=font_color)
+ side = styles.Side(style=styles.borders.BORDER_THIN)
+ border = styles.Border(top=side, right=side, bottom=side, left=side)
+ alignment = styles.Alignment(horizontal='center', vertical='top')
+ fill_color = styles.Color(rgb='006666FF', tint=0.3)
+ fill = styles.PatternFill(patternType='solid', fgColor=fill_color)
+
+ number_format = '0.00'
+
+ protection = styles.Protection(locked=True, hidden=False)
+
+ kw = _OpenpyxlWriter._convert_to_style_kwargs(hstyle)
+ assert kw['font'] == font
+ assert kw['border'] == border
+ assert kw['alignment'] == alignment
+ assert kw['fill'] == fill
+ assert kw['number_format'] == number_format
+ assert kw['protection'] == protection
+
+ def test_write_cells_merge_styled(self, ext):
+ from pandas.io.formats.excel import ExcelCell
+
+ sheet_name = 'merge_styled'
+
+ sty_b1 = {'font': {'color': '00FF0000'}}
+ sty_a2 = {'font': {'color': '0000FF00'}}
+
+ initial_cells = [
+ ExcelCell(col=1, row=0, val=42, style=sty_b1),
+ ExcelCell(col=0, row=1, val=99, style=sty_a2),
+ ]
+
+ sty_merged = {'font': {'color': '000000FF', 'bold': True}}
+ sty_kwargs = _OpenpyxlWriter._convert_to_style_kwargs(sty_merged)
+ openpyxl_sty_merged = sty_kwargs['font']
+ merge_cells = [
+ ExcelCell(col=0, row=0, val='pandas',
+ mergestart=1, mergeend=1, style=sty_merged),
+ ]
+
+ with ensure_clean(ext) as path:
+ writer = _OpenpyxlWriter(path)
+ writer.write_cells(initial_cells, sheet_name=sheet_name)
+ writer.write_cells(merge_cells, sheet_name=sheet_name)
+
+ wks = writer.sheets[sheet_name]
+ xcell_b1 = wks['B1']
+ xcell_a2 = wks['A2']
+ assert xcell_b1.font == openpyxl_sty_merged
+ assert xcell_a2.font == openpyxl_sty_merged
+
+ @pytest.mark.parametrize("mode,expected", [
+ ('w', ['baz']), ('a', ['foo', 'bar', 'baz'])])
+ def test_write_append_mode(self, ext, mode, expected):
+ import openpyxl
+ df = DataFrame([1], columns=['baz'])
+
+ with ensure_clean(ext) as f:
+ wb = openpyxl.Workbook()
+ wb.worksheets[0].title = 'foo'
+ wb.worksheets[0]['A1'].value = 'foo'
+ wb.create_sheet('bar')
+ wb.worksheets[1]['A1'].value = 'bar'
+ wb.save(f)
+
+ writer = ExcelWriter(f, engine='openpyxl', mode=mode)
+ df.to_excel(writer, sheet_name='baz', index=False)
+ writer.save()
+
+ wb2 = openpyxl.load_workbook(f)
+ result = [sheet.title for sheet in wb2.worksheets]
+ assert result == expected
+
+ for index, cell_value in enumerate(expected):
+ assert wb2.worksheets[index]['A1'].value == cell_value
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
new file mode 100644
index 0000000000000..140727599b182
--- /dev/null
+++ b/pandas/tests/io/excel/test_readers.py
@@ -0,0 +1,836 @@
+from collections import OrderedDict
+import contextlib
+from datetime import datetime, time
+from functools import partial
+import os
+import warnings
+
+import numpy as np
+import pytest
+
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import DataFrame, Index, MultiIndex, Series
+import pandas.util.testing as tm
+
+from pandas.io.common import URLError
+from pandas.io.excel import ExcelFile
+
+
+@contextlib.contextmanager
+def ignore_xlrd_time_clock_warning():
+ """
+ Context manager to ignore warnings raised by the xlrd library,
+ regarding the deprecation of `time.clock` in Python 3.7.
+ """
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ action='ignore',
+ message='time.clock has been deprecated',
+ category=DeprecationWarning)
+ yield
+
+
+class TestReaders:
+
+ @pytest.fixture(autouse=True, params=[
+ # Add any engines to test here
+ pytest.param('xlrd', marks=pytest.mark.skipif(
+ not td.safe_import("xlrd"), reason="no xlrd")),
+ pytest.param(None, marks=pytest.mark.skipif(
+ not td.safe_import("xlrd"), reason="no xlrd")),
+ ])
+ def cd_and_set_engine(self, request, datapath, monkeypatch):
+ """
+ Change directory and set engine for read_excel calls.
+ """
+ func = partial(pd.read_excel, engine=request.param)
+ monkeypatch.chdir(datapath("io", "data"))
+ monkeypatch.setattr(pd, 'read_excel', func)
+
+ def test_usecols_int(self, read_ext, df_ref):
+ df_ref = df_ref.reindex(columns=["A", "B", "C"])
+
+ # usecols as int
+ with tm.assert_produces_warning(FutureWarning,
+ check_stacklevel=False):
+ with ignore_xlrd_time_clock_warning():
+ df1 = pd.read_excel("test1" + read_ext, "Sheet1",
+ index_col=0, usecols=3)
+
+ # usecols as int
+ with tm.assert_produces_warning(FutureWarning,
+ check_stacklevel=False):
+ with ignore_xlrd_time_clock_warning():
+ df2 = pd.read_excel("test1" + read_ext, "Sheet2", skiprows=[1],
+ index_col=0, usecols=3)
+
+ # TODO add index to xls file)
+ tm.assert_frame_equal(df1, df_ref, check_names=False)
+ tm.assert_frame_equal(df2, df_ref, check_names=False)
+
+ def test_usecols_list(self, read_ext, df_ref):
+
+ df_ref = df_ref.reindex(columns=['B', 'C'])
+ df1 = pd.read_excel('test1' + read_ext, 'Sheet1', index_col=0,
+ usecols=[0, 2, 3])
+ df2 = pd.read_excel('test1' + read_ext, 'Sheet2', skiprows=[1],
+ index_col=0, usecols=[0, 2, 3])
+
+ # TODO add index to xls file)
+ tm.assert_frame_equal(df1, df_ref, check_names=False)
+ tm.assert_frame_equal(df2, df_ref, check_names=False)
+
+ def test_usecols_str(self, read_ext, df_ref):
+
+ df1 = df_ref.reindex(columns=['A', 'B', 'C'])
+ df2 = pd.read_excel('test1' + read_ext, 'Sheet1', index_col=0,
+ usecols='A:D')
+ df3 = pd.read_excel('test1' + read_ext, 'Sheet2', skiprows=[1],
+ index_col=0, usecols='A:D')
+
+ # TODO add index to xls, read xls ignores index name ?
+ tm.assert_frame_equal(df2, df1, check_names=False)
+ tm.assert_frame_equal(df3, df1, check_names=False)
+
+ df1 = df_ref.reindex(columns=['B', 'C'])
+ df2 = pd.read_excel('test1' + read_ext, 'Sheet1', index_col=0,
+ usecols='A,C,D')
+ df3 = pd.read_excel('test1' + read_ext, 'Sheet2', skiprows=[1],
+ index_col=0, usecols='A,C,D')
+ # TODO add index to xls file
+ tm.assert_frame_equal(df2, df1, check_names=False)
+ tm.assert_frame_equal(df3, df1, check_names=False)
+
+ df1 = df_ref.reindex(columns=['B', 'C'])
+ df2 = pd.read_excel('test1' + read_ext, 'Sheet1', index_col=0,
+ usecols='A,C:D')
+ df3 = pd.read_excel('test1' + read_ext, 'Sheet2', skiprows=[1],
+ index_col=0, usecols='A,C:D')
+ tm.assert_frame_equal(df2, df1, check_names=False)
+ tm.assert_frame_equal(df3, df1, check_names=False)
+
+ @pytest.mark.parametrize("usecols", [
+ [0, 1, 3], [0, 3, 1],
+ [1, 0, 3], [1, 3, 0],
+ [3, 0, 1], [3, 1, 0],
+ ])
+ def test_usecols_diff_positional_int_columns_order(
+ self, read_ext, usecols, df_ref):
+ expected = df_ref[["A", "C"]]
+ result = pd.read_excel("test1" + read_ext, "Sheet1",
+ index_col=0, usecols=usecols)
+ tm.assert_frame_equal(result, expected, check_names=False)
+
+ @pytest.mark.parametrize("usecols", [
+ ["B", "D"], ["D", "B"]
+ ])
+ def test_usecols_diff_positional_str_columns_order(
+ self, read_ext, usecols, df_ref):
+ expected = df_ref[["B", "D"]]
+ expected.index = range(len(expected))
+
+ result = pd.read_excel("test1" + read_ext, "Sheet1", usecols=usecols)
+ tm.assert_frame_equal(result, expected, check_names=False)
+
+ def test_read_excel_without_slicing(self, read_ext, df_ref):
+ expected = df_ref
+ result = pd.read_excel("test1" + read_ext, "Sheet1", index_col=0)
+ tm.assert_frame_equal(result, expected, check_names=False)
+
+ def test_usecols_excel_range_str(self, read_ext, df_ref):
+ expected = df_ref[["C", "D"]]
+ result = pd.read_excel("test1" + read_ext, "Sheet1",
+ index_col=0, usecols="A,D:E")
+ tm.assert_frame_equal(result, expected, check_names=False)
+
+ def test_usecols_excel_range_str_invalid(self, read_ext):
+ msg = "Invalid column name: E1"
+
+ with pytest.raises(ValueError, match=msg):
+ pd.read_excel("test1" + read_ext, "Sheet1", usecols="D:E1")
+
+ def test_index_col_label_error(self, read_ext):
+ msg = "list indices must be integers.*, not str"
+
+ with pytest.raises(TypeError, match=msg):
+ pd.read_excel("test1" + read_ext, "Sheet1", index_col=["A"],
+ usecols=["A", "C"])
+
+ def test_index_col_empty(self, read_ext):
+ # see gh-9208
+ result = pd.read_excel("test1" + read_ext, "Sheet3",
+ index_col=["A", "B", "C"])
+ expected = DataFrame(columns=["D", "E", "F"],
+ index=MultiIndex(levels=[[]] * 3,
+ codes=[[]] * 3,
+ names=["A", "B", "C"]))
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("index_col", [None, 2])
+ def test_index_col_with_unnamed(self, read_ext, index_col):
+ # see gh-18792
+ result = pd.read_excel(
+ "test1" + read_ext, "Sheet4", index_col=index_col)
+ expected = DataFrame([["i1", "a", "x"], ["i2", "b", "y"]],
+ columns=["Unnamed: 0", "col1", "col2"])
+ if index_col:
+ expected = expected.set_index(expected.columns[index_col])
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_usecols_pass_non_existent_column(self, read_ext):
+ msg = ("Usecols do not match columns, "
+ "columns expected but not found: " + r"\['E'\]")
+
+ with pytest.raises(ValueError, match=msg):
+ pd.read_excel("test1" + read_ext, usecols=["E"])
+
+ def test_usecols_wrong_type(self, read_ext):
+ msg = ("'usecols' must either be list-like of "
+ "all strings, all unicode, all integers or a callable.")
+
+ with pytest.raises(ValueError, match=msg):
+ pd.read_excel("test1" + read_ext, usecols=["E1", 0])
+
+ def test_excel_stop_iterator(self, read_ext):
+
+ parsed = pd.read_excel('test2' + read_ext, 'Sheet1')
+ expected = DataFrame([['aaaa', 'bbbbb']], columns=['Test', 'Test1'])
+ tm.assert_frame_equal(parsed, expected)
+
+ def test_excel_cell_error_na(self, read_ext):
+
+ parsed = pd.read_excel('test3' + read_ext, 'Sheet1')
+ expected = DataFrame([[np.nan]], columns=['Test'])
+ tm.assert_frame_equal(parsed, expected)
+
+ def test_excel_table(self, read_ext, df_ref):
+
+ df1 = pd.read_excel('test1' + read_ext, 'Sheet1', index_col=0)
+ df2 = pd.read_excel('test1' + read_ext, 'Sheet2', skiprows=[1],
+ index_col=0)
+ # TODO add index to file
+ tm.assert_frame_equal(df1, df_ref, check_names=False)
+ tm.assert_frame_equal(df2, df_ref, check_names=False)
+
+ df3 = pd.read_excel(
+ 'test1' + read_ext, 'Sheet1', index_col=0, skipfooter=1)
+ tm.assert_frame_equal(df3, df1.iloc[:-1])
+
+ def test_reader_special_dtypes(self, read_ext):
+
+ expected = DataFrame.from_dict(OrderedDict([
+ ("IntCol", [1, 2, -3, 4, 0]),
+ ("FloatCol", [1.25, 2.25, 1.83, 1.92, 0.0000000005]),
+ ("BoolCol", [True, False, True, True, False]),
+ ("StrCol", [1, 2, 3, 4, 5]),
+ # GH5394 - this is why convert_float isn't vectorized
+ ("Str2Col", ["a", 3, "c", "d", "e"]),
+ ("DateCol", [datetime(2013, 10, 30), datetime(2013, 10, 31),
+ datetime(1905, 1, 1), datetime(2013, 12, 14),
+ datetime(2015, 3, 14)])
+ ]))
+ basename = 'test_types'
+
+ # should read in correctly and infer types
+ actual = pd.read_excel(basename + read_ext, 'Sheet1')
+ tm.assert_frame_equal(actual, expected)
+
+ # if not coercing number, then int comes in as float
+ float_expected = expected.copy()
+ float_expected["IntCol"] = float_expected["IntCol"].astype(float)
+ float_expected.loc[float_expected.index[1], "Str2Col"] = 3.0
+ actual = pd.read_excel(
+ basename + read_ext, 'Sheet1', convert_float=False)
+ tm.assert_frame_equal(actual, float_expected)
+
+ # check setting Index (assuming xls and xlsx are the same here)
+ for icol, name in enumerate(expected.columns):
+ actual = pd.read_excel(
+ basename + read_ext, 'Sheet1', index_col=icol)
+ exp = expected.set_index(name)
+ tm.assert_frame_equal(actual, exp)
+
+ # convert_float and converters should be different but both accepted
+ expected["StrCol"] = expected["StrCol"].apply(str)
+ actual = pd.read_excel(basename + read_ext, 'Sheet1',
+ converters={"StrCol": str})
+ tm.assert_frame_equal(actual, expected)
+
+ no_convert_float = float_expected.copy()
+ no_convert_float["StrCol"] = no_convert_float["StrCol"].apply(str)
+ actual = pd.read_excel(
+ basename + read_ext, 'Sheet1',
+ convert_float=False, converters={"StrCol": str})
+ tm.assert_frame_equal(actual, no_convert_float)
+
+ # GH8212 - support for converters and missing values
+ def test_reader_converters(self, read_ext):
+
+ basename = 'test_converters'
+
+ expected = DataFrame.from_dict(OrderedDict([
+ ("IntCol", [1, 2, -3, -1000, 0]),
+ ("FloatCol", [12.5, np.nan, 18.3, 19.2, 0.000000005]),
+ ("BoolCol", ['Found', 'Found', 'Found', 'Not found', 'Found']),
+ ("StrCol", ['1', np.nan, '3', '4', '5']),
+ ]))
+
+ converters = {'IntCol': lambda x: int(x) if x != '' else -1000,
+ 'FloatCol': lambda x: 10 * x if x else np.nan,
+ 2: lambda x: 'Found' if x != '' else 'Not found',
+ 3: lambda x: str(x) if x else '',
+ }
+
+ # should read in correctly and set types of single cells (not array
+ # dtypes)
+ actual = pd.read_excel(
+ basename + read_ext, 'Sheet1', converters=converters)
+ tm.assert_frame_equal(actual, expected)
+
+ def test_reader_dtype(self, read_ext):
+ # GH 8212
+ basename = 'testdtype'
+ actual = pd.read_excel(basename + read_ext)
+
+ expected = DataFrame({
+ 'a': [1, 2, 3, 4],
+ 'b': [2.5, 3.5, 4.5, 5.5],
+ 'c': [1, 2, 3, 4],
+ 'd': [1.0, 2.0, np.nan, 4.0]}).reindex(
+ columns=['a', 'b', 'c', 'd'])
+
+ tm.assert_frame_equal(actual, expected)
+
+ actual = pd.read_excel(basename + read_ext,
+ dtype={'a': 'float64',
+ 'b': 'float32',
+ 'c': str})
+
+ expected['a'] = expected['a'].astype('float64')
+ expected['b'] = expected['b'].astype('float32')
+ expected['c'] = ['001', '002', '003', '004']
+ tm.assert_frame_equal(actual, expected)
+
+ with pytest.raises(ValueError):
+ pd.read_excel(basename + read_ext, dtype={'d': 'int64'})
+
+ @pytest.mark.parametrize("dtype,expected", [
+ (None,
+ DataFrame({
+ "a": [1, 2, 3, 4],
+ "b": [2.5, 3.5, 4.5, 5.5],
+ "c": [1, 2, 3, 4],
+ "d": [1.0, 2.0, np.nan, 4.0]
+ })),
+ ({"a": "float64",
+ "b": "float32",
+ "c": str,
+ "d": str
+ },
+ DataFrame({
+ "a": Series([1, 2, 3, 4], dtype="float64"),
+ "b": Series([2.5, 3.5, 4.5, 5.5], dtype="float32"),
+ "c": ["001", "002", "003", "004"],
+ "d": ["1", "2", np.nan, "4"]
+ })),
+ ])
+ def test_reader_dtype_str(self, read_ext, dtype, expected):
+ # see gh-20377
+ basename = "testdtype"
+
+ actual = pd.read_excel(basename + read_ext, dtype=dtype)
+ tm.assert_frame_equal(actual, expected)
+
+ def test_reading_all_sheets(self, read_ext):
+ # Test reading all sheetnames by setting sheetname to None,
+ # Ensure a dict is returned.
+ # See PR #9450
+ basename = 'test_multisheet'
+ dfs = pd.read_excel(basename + read_ext, sheet_name=None)
+ # ensure this is not alphabetical to test order preservation
+ expected_keys = ['Charlie', 'Alpha', 'Beta']
+ tm.assert_contains_all(expected_keys, dfs.keys())
+ # Issue 9930
+ # Ensure sheet order is preserved
+ assert expected_keys == list(dfs.keys())
+
+ def test_reading_multiple_specific_sheets(self, read_ext):
+ # Test reading specific sheetnames by specifying a mixed list
+ # of integers and strings, and confirm that duplicated sheet
+ # references (positions/names) are removed properly.
+ # Ensure a dict is returned
+ # See PR #9450
+ basename = 'test_multisheet'
+ # Explicitly request duplicates. Only the set should be returned.
+ expected_keys = [2, 'Charlie', 'Charlie']
+ dfs = pd.read_excel(basename + read_ext, sheet_name=expected_keys)
+ expected_keys = list(set(expected_keys))
+ tm.assert_contains_all(expected_keys, dfs.keys())
+ assert len(expected_keys) == len(dfs.keys())
+
+ def test_reading_all_sheets_with_blank(self, read_ext):
+ # Test reading all sheetnames by setting sheetname to None,
+ # In the case where some sheets are blank.
+ # Issue #11711
+ basename = 'blank_with_header'
+ dfs = pd.read_excel(basename + read_ext, sheet_name=None)
+ expected_keys = ['Sheet1', 'Sheet2', 'Sheet3']
+ tm.assert_contains_all(expected_keys, dfs.keys())
+
+ # GH6403
+ def test_read_excel_blank(self, read_ext):
+ actual = pd.read_excel('blank' + read_ext, 'Sheet1')
+ tm.assert_frame_equal(actual, DataFrame())
+
+ def test_read_excel_blank_with_header(self, read_ext):
+ expected = DataFrame(columns=['col_1', 'col_2'])
+ actual = pd.read_excel('blank_with_header' + read_ext, 'Sheet1')
+ tm.assert_frame_equal(actual, expected)
+
+ def test_date_conversion_overflow(self, read_ext):
+ # GH 10001 : pandas.ExcelFile ignore parse_dates=False
+ expected = pd.DataFrame([[pd.Timestamp('2016-03-12'), 'Marc Johnson'],
+ [pd.Timestamp('2016-03-16'), 'Jack Black'],
+ [1e+20, 'Timothy Brown']],
+ columns=['DateColWithBigInt', 'StringCol'])
+
+ result = pd.read_excel('testdateoverflow' + read_ext)
+ tm.assert_frame_equal(result, expected)
+
+ def test_sheet_name(self, read_ext, df_ref):
+ filename = "test1"
+ sheet_name = "Sheet1"
+
+ df1 = pd.read_excel(filename + read_ext,
+ sheet_name=sheet_name, index_col=0) # doc
+ with ignore_xlrd_time_clock_warning():
+ df2 = pd.read_excel(filename + read_ext, index_col=0,
+ sheet_name=sheet_name)
+
+ tm.assert_frame_equal(df1, df_ref, check_names=False)
+ tm.assert_frame_equal(df2, df_ref, check_names=False)
+
+ def test_excel_read_buffer(self, read_ext):
+
+ pth = 'test1' + read_ext
+ expected = pd.read_excel(pth, 'Sheet1', index_col=0)
+ with open(pth, 'rb') as f:
+ actual = pd.read_excel(f, 'Sheet1', index_col=0)
+ tm.assert_frame_equal(expected, actual)
+
+ def test_bad_engine_raises(self, read_ext):
+ bad_engine = 'foo'
+ with pytest.raises(ValueError, match="Unknown engine: foo"):
+ pd.read_excel('', engine=bad_engine)
+
+ @tm.network
+ def test_read_from_http_url(self, read_ext):
+ url = ('https://raw.github.com/pandas-dev/pandas/master/'
+ 'pandas/tests/io/data/test1' + read_ext)
+ url_table = pd.read_excel(url)
+ local_table = pd.read_excel('test1' + read_ext)
+ tm.assert_frame_equal(url_table, local_table)
+
+ @td.skip_if_not_us_locale
+ def test_read_from_s3_url(self, read_ext, s3_resource):
+ # Bucket "pandas-test" created in tests/io/conftest.py
+ with open('test1' + read_ext, "rb") as f:
+ s3_resource.Bucket("pandas-test").put_object(
+ Key="test1" + read_ext, Body=f)
+
+ url = ('s3://pandas-test/test1' + read_ext)
+ url_table = pd.read_excel(url)
+ local_table = pd.read_excel('test1' + read_ext)
+ tm.assert_frame_equal(url_table, local_table)
+
+ @pytest.mark.slow
+ # ignore warning from old xlrd
+ @pytest.mark.filterwarnings("ignore:This metho:PendingDeprecationWarning")
+ def test_read_from_file_url(self, read_ext, datapath):
+
+ # FILE
+ localtable = os.path.join(datapath("io", "data"), 'test1' + read_ext)
+ local_table = pd.read_excel(localtable)
+
+ try:
+ url_table = pd.read_excel('file://localhost/' + localtable)
+ except URLError:
+ # fails on some systems
+ import platform
+ pytest.skip("failing on %s" %
+ ' '.join(platform.uname()).strip())
+
+ tm.assert_frame_equal(url_table, local_table)
+
+ def test_read_from_pathlib_path(self, read_ext):
+
+ # GH12655
+ from pathlib import Path
+
+ str_path = 'test1' + read_ext
+ expected = pd.read_excel(str_path, 'Sheet1', index_col=0)
+
+ path_obj = Path('test1' + read_ext)
+ actual = pd.read_excel(path_obj, 'Sheet1', index_col=0)
+
+ tm.assert_frame_equal(expected, actual)
+
+ @td.skip_if_no('py.path')
+ def test_read_from_py_localpath(self, read_ext):
+
+ # GH12655
+ from py.path import local as LocalPath
+
+ str_path = os.path.join('test1' + read_ext)
+ expected = pd.read_excel(str_path, 'Sheet1', index_col=0)
+
+ path_obj = LocalPath().join('test1' + read_ext)
+ actual = pd.read_excel(path_obj, 'Sheet1', index_col=0)
+
+ tm.assert_frame_equal(expected, actual)
+
+ def test_reader_seconds(self, read_ext):
+
+ # Test reading times with and without milliseconds. GH5945.
+ expected = DataFrame.from_dict({"Time": [time(1, 2, 3),
+ time(2, 45, 56, 100000),
+ time(4, 29, 49, 200000),
+ time(6, 13, 42, 300000),
+ time(7, 57, 35, 400000),
+ time(9, 41, 28, 500000),
+ time(11, 25, 21, 600000),
+ time(13, 9, 14, 700000),
+ time(14, 53, 7, 800000),
+ time(16, 37, 0, 900000),
+ time(18, 20, 54)]})
+
+ actual = pd.read_excel('times_1900' + read_ext, 'Sheet1')
+ tm.assert_frame_equal(actual, expected)
+
+ actual = pd.read_excel('times_1904' + read_ext, 'Sheet1')
+ tm.assert_frame_equal(actual, expected)
+
+ def test_read_excel_multiindex(self, read_ext):
+ # see gh-4679
+ mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]])
+ mi_file = "testmultiindex" + read_ext
+
+ # "mi_column" sheet
+ 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)
+
+ actual = pd.read_excel(
+ mi_file, "mi_column", header=[0, 1], index_col=0)
+ tm.assert_frame_equal(actual, expected)
+
+ # "mi_index" sheet
+ expected.index = mi
+ expected.columns = ["a", "b", "c", "d"]
+
+ actual = pd.read_excel(mi_file, "mi_index", index_col=[0, 1])
+ tm.assert_frame_equal(actual, expected, check_names=False)
+
+ # "both" sheet
+ expected.columns = mi
+
+ actual = pd.read_excel(
+ mi_file, "both", index_col=[0, 1], header=[0, 1])
+ tm.assert_frame_equal(actual, expected, check_names=False)
+
+ # "mi_index_name" sheet
+ expected.columns = ["a", "b", "c", "d"]
+ expected.index = mi.set_names(["ilvl1", "ilvl2"])
+
+ actual = pd.read_excel(
+ mi_file, "mi_index_name", index_col=[0, 1])
+ tm.assert_frame_equal(actual, expected)
+
+ # "mi_column_name" sheet
+ expected.index = list(range(4))
+ expected.columns = mi.set_names(["c1", "c2"])
+ actual = pd.read_excel(mi_file, "mi_column_name",
+ header=[0, 1], index_col=0)
+ tm.assert_frame_equal(actual, expected)
+
+ # see gh-11317
+ # "name_with_int" sheet
+ expected.columns = mi.set_levels(
+ [1, 2], level=1).set_names(["c1", "c2"])
+
+ actual = pd.read_excel(mi_file, "name_with_int",
+ index_col=0, header=[0, 1])
+ tm.assert_frame_equal(actual, expected)
+
+ # "both_name" sheet
+ expected.columns = mi.set_names(["c1", "c2"])
+ expected.index = mi.set_names(["ilvl1", "ilvl2"])
+
+ actual = pd.read_excel(mi_file, "both_name",
+ index_col=[0, 1], header=[0, 1])
+ tm.assert_frame_equal(actual, expected)
+
+ # "both_skiprows" sheet
+ actual = pd.read_excel(mi_file, "both_name_skiprows", index_col=[0, 1],
+ header=[0, 1], skiprows=2)
+ tm.assert_frame_equal(actual, expected)
+
+ def test_read_excel_multiindex_header_only(self, read_ext):
+ # see gh-11733.
+ #
+ # Don't try to parse a header name if there isn't one.
+ mi_file = "testmultiindex" + read_ext
+ result = pd.read_excel(mi_file, "index_col_none", header=[0, 1])
+
+ exp_columns = MultiIndex.from_product([("A", "B"), ("key", "val")])
+ expected = DataFrame([[1, 2, 3, 4]] * 2, columns=exp_columns)
+ tm.assert_frame_equal(result, expected)
+
+ def test_excel_old_index_format(self, read_ext):
+ # see gh-4679
+ filename = "test_index_name_pre17" + read_ext
+
+ # We detect headers to determine if index names exist, so
+ # that "index" name in the "names" version of the data will
+ # now be interpreted as rows that include null data.
+ data = np.array([[None, None, None, None, None],
+ ["R0C0", "R0C1", "R0C2", "R0C3", "R0C4"],
+ ["R1C0", "R1C1", "R1C2", "R1C3", "R1C4"],
+ ["R2C0", "R2C1", "R2C2", "R2C3", "R2C4"],
+ ["R3C0", "R3C1", "R3C2", "R3C3", "R3C4"],
+ ["R4C0", "R4C1", "R4C2", "R4C3", "R4C4"]])
+ columns = ["C_l0_g0", "C_l0_g1", "C_l0_g2", "C_l0_g3", "C_l0_g4"]
+ mi = MultiIndex(levels=[["R0", "R_l0_g0", "R_l0_g1",
+ "R_l0_g2", "R_l0_g3", "R_l0_g4"],
+ ["R1", "R_l1_g0", "R_l1_g1",
+ "R_l1_g2", "R_l1_g3", "R_l1_g4"]],
+ codes=[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]],
+ names=[None, None])
+ si = Index(["R0", "R_l0_g0", "R_l0_g1", "R_l0_g2",
+ "R_l0_g3", "R_l0_g4"], name=None)
+
+ expected = pd.DataFrame(data, index=si, columns=columns)
+
+ actual = pd.read_excel(filename, "single_names", index_col=0)
+ tm.assert_frame_equal(actual, expected)
+
+ expected.index = mi
+
+ actual = pd.read_excel(filename, "multi_names", index_col=[0, 1])
+ tm.assert_frame_equal(actual, expected)
+
+ # The analogous versions of the "names" version data
+ # where there are explicitly no names for the indices.
+ data = np.array([["R0C0", "R0C1", "R0C2", "R0C3", "R0C4"],
+ ["R1C0", "R1C1", "R1C2", "R1C3", "R1C4"],
+ ["R2C0", "R2C1", "R2C2", "R2C3", "R2C4"],
+ ["R3C0", "R3C1", "R3C2", "R3C3", "R3C4"],
+ ["R4C0", "R4C1", "R4C2", "R4C3", "R4C4"]])
+ columns = ["C_l0_g0", "C_l0_g1", "C_l0_g2", "C_l0_g3", "C_l0_g4"]
+ mi = MultiIndex(levels=[["R_l0_g0", "R_l0_g1", "R_l0_g2",
+ "R_l0_g3", "R_l0_g4"],
+ ["R_l1_g0", "R_l1_g1", "R_l1_g2",
+ "R_l1_g3", "R_l1_g4"]],
+ codes=[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]],
+ names=[None, None])
+ si = Index(["R_l0_g0", "R_l0_g1", "R_l0_g2",
+ "R_l0_g3", "R_l0_g4"], name=None)
+
+ expected = pd.DataFrame(data, index=si, columns=columns)
+
+ actual = pd.read_excel(filename, "single_no_names", index_col=0)
+ tm.assert_frame_equal(actual, expected)
+
+ expected.index = mi
+
+ actual = pd.read_excel(filename, "multi_no_names", index_col=[0, 1])
+ tm.assert_frame_equal(actual, expected, check_names=False)
+
+ def test_read_excel_bool_header_arg(self, read_ext):
+ # GH 6114
+ for arg in [True, False]:
+ with pytest.raises(TypeError):
+ pd.read_excel('test1' + read_ext, header=arg)
+
+ def test_read_excel_chunksize(self, read_ext):
+ # GH 8011
+ with pytest.raises(NotImplementedError):
+ pd.read_excel('test1' + read_ext, chunksize=100)
+
+ def test_read_excel_skiprows_list(self, read_ext):
+ # GH 4903
+ actual = pd.read_excel('testskiprows' + read_ext,
+ 'skiprows_list', skiprows=[0, 2])
+ 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=['a', 'b', 'c', 'd'])
+ tm.assert_frame_equal(actual, expected)
+
+ actual = pd.read_excel('testskiprows' + read_ext,
+ 'skiprows_list', skiprows=np.array([0, 2]))
+ tm.assert_frame_equal(actual, expected)
+
+ def test_read_excel_nrows(self, read_ext):
+ # GH 16645
+ num_rows_to_pull = 5
+ actual = pd.read_excel('test1' + read_ext, nrows=num_rows_to_pull)
+ expected = pd.read_excel('test1' + read_ext)
+ expected = expected[:num_rows_to_pull]
+ tm.assert_frame_equal(actual, expected)
+
+ def test_read_excel_nrows_greater_than_nrows_in_file(self, read_ext):
+ # GH 16645
+ expected = pd.read_excel('test1' + read_ext)
+ num_records_in_file = len(expected)
+ num_rows_to_pull = num_records_in_file + 10
+ actual = pd.read_excel('test1' + read_ext, nrows=num_rows_to_pull)
+ tm.assert_frame_equal(actual, expected)
+
+ def test_read_excel_nrows_non_integer_parameter(self, read_ext):
+ # GH 16645
+ msg = "'nrows' must be an integer >=0"
+ with pytest.raises(ValueError, match=msg):
+ pd.read_excel('test1' + read_ext, nrows='5')
+
+ def test_read_excel_squeeze(self, read_ext):
+ # GH 12157
+ f = 'test_squeeze' + read_ext
+
+ actual = pd.read_excel(f, 'two_columns', index_col=0, squeeze=True)
+ expected = pd.Series([2, 3, 4], [4, 5, 6], name='b')
+ expected.index.name = 'a'
+ tm.assert_series_equal(actual, expected)
+
+ actual = pd.read_excel(f, 'two_columns', squeeze=True)
+ expected = pd.DataFrame({'a': [4, 5, 6],
+ 'b': [2, 3, 4]})
+ tm.assert_frame_equal(actual, expected)
+
+ actual = pd.read_excel(f, 'one_column', squeeze=True)
+ expected = pd.Series([1, 2, 3], name='a')
+ tm.assert_series_equal(actual, expected)
+
+
+class TestExcelFileRead:
+
+ @pytest.fixture(autouse=True, params=[
+ # Add any engines to test here
+ pytest.param('xlrd', marks=pytest.mark.skipif(
+ not td.safe_import("xlrd"), reason="no xlrd")),
+ pytest.param(None, marks=pytest.mark.skipif(
+ not td.safe_import("xlrd"), reason="no xlrd")),
+ ])
+ def cd_and_set_engine(self, request, datapath, monkeypatch):
+ """
+ Change directory and set engine for ExcelFile objects.
+ """
+ func = partial(pd.ExcelFile, engine=request.param)
+ monkeypatch.chdir(datapath("io", "data"))
+ monkeypatch.setattr(pd, 'ExcelFile', func)
+
+ def test_excel_passes_na(self, read_ext):
+
+ excel = ExcelFile('test4' + read_ext)
+
+ parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=False,
+ na_values=['apple'])
+ expected = DataFrame([['NA'], [1], ['NA'], [np.nan], ['rabbit']],
+ columns=['Test'])
+ tm.assert_frame_equal(parsed, expected)
+
+ parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=True,
+ na_values=['apple'])
+ expected = DataFrame([[np.nan], [1], [np.nan], [np.nan], ['rabbit']],
+ columns=['Test'])
+ tm.assert_frame_equal(parsed, expected)
+
+ # 13967
+ excel = ExcelFile('test5' + read_ext)
+
+ parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=False,
+ na_values=['apple'])
+ expected = DataFrame([['1.#QNAN'], [1], ['nan'], [np.nan], ['rabbit']],
+ columns=['Test'])
+ tm.assert_frame_equal(parsed, expected)
+
+ parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=True,
+ na_values=['apple'])
+ expected = DataFrame([[np.nan], [1], [np.nan], [np.nan], ['rabbit']],
+ columns=['Test'])
+ tm.assert_frame_equal(parsed, expected)
+
+ @pytest.mark.parametrize('arg', ['sheet', 'sheetname', 'parse_cols'])
+ def test_unexpected_kwargs_raises(self, read_ext, arg):
+ # gh-17964
+ excel = ExcelFile('test1' + read_ext)
+
+ kwarg = {arg: 'Sheet1'}
+ msg = "unexpected keyword argument `{}`".format(arg)
+ with pytest.raises(TypeError, match=msg):
+ pd.read_excel(excel, **kwarg)
+
+ def test_excel_table_sheet_by_index(self, read_ext, df_ref):
+
+ excel = ExcelFile('test1' + read_ext)
+
+ df1 = pd.read_excel(excel, 0, index_col=0)
+ df2 = pd.read_excel(excel, 1, skiprows=[1], index_col=0)
+ tm.assert_frame_equal(df1, df_ref, check_names=False)
+ tm.assert_frame_equal(df2, df_ref, check_names=False)
+
+ df1 = excel.parse(0, index_col=0)
+ df2 = excel.parse(1, skiprows=[1], index_col=0)
+ tm.assert_frame_equal(df1, df_ref, check_names=False)
+ tm.assert_frame_equal(df2, df_ref, check_names=False)
+
+ df3 = pd.read_excel(excel, 0, index_col=0, skipfooter=1)
+ tm.assert_frame_equal(df3, df1.iloc[:-1])
+
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ df4 = pd.read_excel(excel, 0, index_col=0, skip_footer=1)
+ tm.assert_frame_equal(df3, df4)
+
+ df3 = excel.parse(0, index_col=0, skipfooter=1)
+ tm.assert_frame_equal(df3, df1.iloc[:-1])
+
+ import xlrd # will move to engine-specific tests as new ones are added
+ with pytest.raises(xlrd.XLRDError):
+ pd.read_excel(excel, 'asdf')
+
+ def test_sheet_name(self, read_ext, df_ref):
+ filename = "test1"
+ sheet_name = "Sheet1"
+
+ excel = ExcelFile(filename + read_ext)
+ df1_parse = excel.parse(sheet_name=sheet_name, index_col=0) # doc
+ df2_parse = excel.parse(index_col=0,
+ sheet_name=sheet_name)
+
+ tm.assert_frame_equal(df1_parse, df_ref, check_names=False)
+ tm.assert_frame_equal(df2_parse, df_ref, check_names=False)
+
+ def test_excel_read_buffer(self, read_ext):
+
+ pth = 'test1' + read_ext
+ expected = pd.read_excel(pth, 'Sheet1', index_col=0)
+
+ with open(pth, 'rb') as f:
+ xls = ExcelFile(f)
+ actual = pd.read_excel(xls, 'Sheet1', index_col=0)
+ tm.assert_frame_equal(expected, actual)
+
+ def test_reader_closes_file(self, read_ext):
+
+ f = open('test1' + read_ext, 'rb')
+ with ExcelFile(f) as xlsx:
+ # parses okay
+ pd.read_excel(xlsx, 'Sheet1', index_col=0)
+
+ assert f.closed
diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py
new file mode 100644
index 0000000000000..d8426f54bb188
--- /dev/null
+++ b/pandas/tests/io/excel/test_style.py
@@ -0,0 +1,165 @@
+from distutils.version import LooseVersion
+
+import numpy as np
+import pytest
+
+from pandas import DataFrame
+from pandas.util.testing import ensure_clean
+
+from pandas.io.excel import ExcelWriter
+from pandas.io.formats.excel import ExcelFormatter
+
+
+@pytest.mark.parametrize('engine', [
+ pytest.param('xlwt',
+ marks=pytest.mark.xfail(reason='xlwt does not support '
+ 'openpyxl-compatible '
+ 'style dicts')),
+ 'xlsxwriter',
+ 'openpyxl',
+])
+def test_styler_to_excel(engine):
+ def style(df):
+ # XXX: RGB colors not supported in xlwt
+ return DataFrame([['font-weight: bold', '', ''],
+ ['', 'color: blue', ''],
+ ['', '', 'text-decoration: underline'],
+ ['border-style: solid', '', ''],
+ ['', 'font-style: italic', ''],
+ ['', '', 'text-align: right'],
+ ['background-color: red', '', ''],
+ ['number-format: 0%', '', ''],
+ ['', '', ''],
+ ['', '', ''],
+ ['', '', '']],
+ index=df.index, columns=df.columns)
+
+ def assert_equal_style(cell1, cell2, engine):
+ if engine in ['xlsxwriter', 'openpyxl']:
+ pytest.xfail(reason=("GH25351: failing on some attribute "
+ "comparisons in {}".format(engine)))
+ # XXX: should find a better way to check equality
+ assert cell1.alignment.__dict__ == cell2.alignment.__dict__
+ assert cell1.border.__dict__ == cell2.border.__dict__
+ assert cell1.fill.__dict__ == cell2.fill.__dict__
+ assert cell1.font.__dict__ == cell2.font.__dict__
+ assert cell1.number_format == cell2.number_format
+ assert cell1.protection.__dict__ == cell2.protection.__dict__
+
+ def custom_converter(css):
+ # use bold iff there is custom style attached to the cell
+ if css.strip(' \n;'):
+ return {'font': {'bold': True}}
+ return {}
+
+ pytest.importorskip('jinja2')
+ pytest.importorskip(engine)
+
+ # Prepare spreadsheets
+
+ df = DataFrame(np.random.randn(11, 3))
+ with ensure_clean('.xlsx' if engine != 'xlwt' else '.xls') as path:
+ writer = ExcelWriter(path, engine=engine)
+ df.to_excel(writer, sheet_name='frame')
+ df.style.to_excel(writer, sheet_name='unstyled')
+ styled = df.style.apply(style, axis=None)
+ styled.to_excel(writer, sheet_name='styled')
+ ExcelFormatter(styled, style_converter=custom_converter).write(
+ writer, sheet_name='custom')
+ writer.save()
+
+ if engine not in ('openpyxl', 'xlsxwriter'):
+ # For other engines, we only smoke test
+ return
+ openpyxl = pytest.importorskip('openpyxl')
+ wb = openpyxl.load_workbook(path)
+
+ # (1) compare DataFrame.to_excel and Styler.to_excel when unstyled
+ n_cells = 0
+ for col1, col2 in zip(wb['frame'].columns,
+ wb['unstyled'].columns):
+ assert len(col1) == len(col2)
+ for cell1, cell2 in zip(col1, col2):
+ assert cell1.value == cell2.value
+ assert_equal_style(cell1, cell2, engine)
+ n_cells += 1
+
+ # ensure iteration actually happened:
+ assert n_cells == (11 + 1) * (3 + 1)
+
+ # (2) check styling with default converter
+
+ # XXX: openpyxl (as at 2.4) prefixes colors with 00, xlsxwriter with FF
+ alpha = '00' if engine == 'openpyxl' else 'FF'
+
+ n_cells = 0
+ for col1, col2 in zip(wb['frame'].columns,
+ wb['styled'].columns):
+ assert len(col1) == len(col2)
+ for cell1, cell2 in zip(col1, col2):
+ ref = '%s%d' % (cell2.column, cell2.row)
+ # XXX: this isn't as strong a test as ideal; we should
+ # confirm that differences are exclusive
+ if ref == 'B2':
+ assert not cell1.font.bold
+ assert cell2.font.bold
+ elif ref == 'C3':
+ assert cell1.font.color.rgb != cell2.font.color.rgb
+ assert cell2.font.color.rgb == alpha + '0000FF'
+ elif ref == 'D4':
+ # This fails with engine=xlsxwriter due to
+ # https://bitbucket.org/openpyxl/openpyxl/issues/800
+ if engine == 'xlsxwriter' \
+ and (LooseVersion(openpyxl.__version__) <
+ LooseVersion('2.4.6')):
+ pass
+ else:
+ assert cell1.font.underline != cell2.font.underline
+ assert cell2.font.underline == 'single'
+ elif ref == 'B5':
+ assert not cell1.border.left.style
+ assert (cell2.border.top.style ==
+ cell2.border.right.style ==
+ cell2.border.bottom.style ==
+ cell2.border.left.style ==
+ 'medium')
+ elif ref == 'C6':
+ assert not cell1.font.italic
+ assert cell2.font.italic
+ elif ref == 'D7':
+ assert (cell1.alignment.horizontal !=
+ cell2.alignment.horizontal)
+ assert cell2.alignment.horizontal == 'right'
+ elif ref == 'B8':
+ assert cell1.fill.fgColor.rgb != cell2.fill.fgColor.rgb
+ assert cell1.fill.patternType != cell2.fill.patternType
+ assert cell2.fill.fgColor.rgb == alpha + 'FF0000'
+ assert cell2.fill.patternType == 'solid'
+ elif ref == 'B9':
+ assert cell1.number_format == 'General'
+ assert cell2.number_format == '0%'
+ else:
+ assert_equal_style(cell1, cell2, engine)
+
+ assert cell1.value == cell2.value
+ n_cells += 1
+
+ assert n_cells == (11 + 1) * (3 + 1)
+
+ # (3) check styling with custom converter
+ n_cells = 0
+ for col1, col2 in zip(wb['frame'].columns,
+ wb['custom'].columns):
+ assert len(col1) == len(col2)
+ for cell1, cell2 in zip(col1, col2):
+ ref = '%s%d' % (cell2.column, cell2.row)
+ if ref in ('B2', 'C3', 'D4', 'B5', 'C6', 'D7', 'B8', 'B9'):
+ assert not cell1.font.bold
+ assert cell2.font.bold
+ else:
+ assert_equal_style(cell1, cell2, engine)
+
+ assert cell1.value == cell2.value
+ n_cells += 1
+
+ assert n_cells == (11 + 1) * (3 + 1)
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
new file mode 100644
index 0000000000000..961d781764b67
--- /dev/null
+++ b/pandas/tests/io/excel/test_writers.py
@@ -0,0 +1,1239 @@
+from datetime import date, datetime, timedelta
+from functools import partial
+from io import BytesIO
+import os
+
+import numpy as np
+from numpy import nan
+import pytest
+
+from pandas.compat import PY36
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import DataFrame, Index, MultiIndex, get_option, set_option
+import pandas.util.testing as tm
+from pandas.util.testing import ensure_clean, makeCustomDataframe as mkdf
+
+from pandas.io.excel import (
+ ExcelFile, ExcelWriter, _OpenpyxlWriter, _XlsxWriter, _XlwtWriter,
+ register_writer)
+
+
+@td.skip_if_no('xlrd')
+@pytest.mark.parametrize("ext", ['.xls', '.xlsx', '.xlsm'])
+class TestRoundTrip:
+
+ @td.skip_if_no("xlwt")
+ @td.skip_if_no("openpyxl")
+ @pytest.mark.parametrize("header,expected", [
+ (None, DataFrame([np.nan] * 4)),
+ (0, DataFrame({"Unnamed: 0": [np.nan] * 3}))
+ ])
+ def test_read_one_empty_col_no_header(self, ext, header, expected):
+ # xref gh-12292
+ filename = "no_header"
+ df = pd.DataFrame(
+ [["", 1, 100],
+ ["", 2, 200],
+ ["", 3, 300],
+ ["", 4, 400]]
+ )
+
+ with ensure_clean(ext) as path:
+ df.to_excel(path, filename, index=False, header=False)
+ result = pd.read_excel(path, filename, usecols=[0], header=header)
+
+ tm.assert_frame_equal(result, expected)
+
+ @td.skip_if_no("xlwt")
+ @td.skip_if_no("openpyxl")
+ @pytest.mark.parametrize("header,expected", [
+ (None, DataFrame([0] + [np.nan] * 4)),
+ (0, DataFrame([np.nan] * 4))
+ ])
+ def test_read_one_empty_col_with_header(self, ext, header, expected):
+ filename = "with_header"
+ df = pd.DataFrame(
+ [["", 1, 100],
+ ["", 2, 200],
+ ["", 3, 300],
+ ["", 4, 400]]
+ )
+
+ with ensure_clean(ext) as path:
+ df.to_excel(path, 'with_header', index=False, header=True)
+ result = pd.read_excel(path, filename, usecols=[0], header=header)
+
+ tm.assert_frame_equal(result, expected)
+
+ @td.skip_if_no('openpyxl')
+ @td.skip_if_no('xlwt')
+ def test_set_column_names_in_parameter(self, ext):
+ # GH 12870 : pass down column names associated with
+ # keyword argument names
+ refdf = pd.DataFrame([[1, 'foo'], [2, 'bar'],
+ [3, 'baz']], columns=['a', 'b'])
+
+ with ensure_clean(ext) as pth:
+ with ExcelWriter(pth) as writer:
+ refdf.to_excel(writer, 'Data_no_head',
+ header=False, index=False)
+ refdf.to_excel(writer, 'Data_with_head', index=False)
+
+ refdf.columns = ['A', 'B']
+
+ with ExcelFile(pth) as reader:
+ xlsdf_no_head = pd.read_excel(reader, 'Data_no_head',
+ header=None, names=['A', 'B'])
+ xlsdf_with_head = pd.read_excel(
+ reader, 'Data_with_head', index_col=None, names=['A', 'B'])
+
+ tm.assert_frame_equal(xlsdf_no_head, refdf)
+ tm.assert_frame_equal(xlsdf_with_head, refdf)
+
+ @td.skip_if_no("xlwt")
+ @td.skip_if_no("openpyxl")
+ def test_creating_and_reading_multiple_sheets(self, ext):
+ # see gh-9450
+ #
+ # Test reading multiple sheets, from a runtime
+ # created Excel file with multiple sheets.
+ def tdf(col_sheet_name):
+ d, i = [11, 22, 33], [1, 2, 3]
+ return DataFrame(d, i, columns=[col_sheet_name])
+
+ sheets = ["AAA", "BBB", "CCC"]
+
+ dfs = [tdf(s) for s in sheets]
+ dfs = dict(zip(sheets, dfs))
+
+ with ensure_clean(ext) as pth:
+ with ExcelWriter(pth) as ew:
+ for sheetname, df in dfs.items():
+ df.to_excel(ew, sheetname)
+
+ dfs_returned = pd.read_excel(pth, sheet_name=sheets, index_col=0)
+
+ for s in sheets:
+ tm.assert_frame_equal(dfs[s], dfs_returned[s])
+
+ @td.skip_if_no("xlsxwriter")
+ def test_read_excel_multiindex_empty_level(self, ext):
+ # see gh-12453
+ with ensure_clean(ext) as path:
+ df = DataFrame({
+ ("One", "x"): {0: 1},
+ ("Two", "X"): {0: 3},
+ ("Two", "Y"): {0: 7},
+ ("Zero", ""): {0: 0}
+ })
+
+ expected = DataFrame({
+ ("One", "x"): {0: 1},
+ ("Two", "X"): {0: 3},
+ ("Two", "Y"): {0: 7},
+ ("Zero", "Unnamed: 4_level_1"): {0: 0}
+ })
+
+ df.to_excel(path)
+ actual = pd.read_excel(path, header=[0, 1], index_col=0)
+ tm.assert_frame_equal(actual, expected)
+
+ df = pd.DataFrame({
+ ("Beg", ""): {0: 0},
+ ("Middle", "x"): {0: 1},
+ ("Tail", "X"): {0: 3},
+ ("Tail", "Y"): {0: 7}
+ })
+
+ expected = pd.DataFrame({
+ ("Beg", "Unnamed: 1_level_1"): {0: 0},
+ ("Middle", "x"): {0: 1},
+ ("Tail", "X"): {0: 3},
+ ("Tail", "Y"): {0: 7}
+ })
+
+ df.to_excel(path)
+ actual = pd.read_excel(path, header=[0, 1], index_col=0)
+ tm.assert_frame_equal(actual, expected)
+
+ @td.skip_if_no("xlsxwriter")
+ @pytest.mark.parametrize("c_idx_names", [True, False])
+ @pytest.mark.parametrize("r_idx_names", [True, False])
+ @pytest.mark.parametrize("c_idx_levels", [1, 3])
+ @pytest.mark.parametrize("r_idx_levels", [1, 3])
+ def test_excel_multindex_roundtrip(self, ext, c_idx_names, r_idx_names,
+ c_idx_levels, r_idx_levels):
+ # see gh-4679
+ with ensure_clean(ext) as pth:
+ if c_idx_levels == 1 and c_idx_names:
+ pytest.skip("Column index name cannot be "
+ "serialized unless it's a MultiIndex")
+
+ # Empty name case current read in as
+ # unnamed levels, not Nones.
+ check_names = r_idx_names or r_idx_levels <= 1
+
+ df = mkdf(5, 5, c_idx_names, r_idx_names,
+ c_idx_levels, r_idx_levels)
+ df.to_excel(pth)
+
+ act = pd.read_excel(pth, index_col=list(range(r_idx_levels)),
+ header=list(range(c_idx_levels)))
+ tm.assert_frame_equal(df, act, check_names=check_names)
+
+ df.iloc[0, :] = np.nan
+ df.to_excel(pth)
+
+ act = pd.read_excel(pth, index_col=list(range(r_idx_levels)),
+ header=list(range(c_idx_levels)))
+ tm.assert_frame_equal(df, act, check_names=check_names)
+
+ df.iloc[-1, :] = np.nan
+ df.to_excel(pth)
+ act = pd.read_excel(pth, index_col=list(range(r_idx_levels)),
+ header=list(range(c_idx_levels)))
+ tm.assert_frame_equal(df, act, check_names=check_names)
+
+ @td.skip_if_no("xlwt")
+ @td.skip_if_no("openpyxl")
+ def test_read_excel_parse_dates(self, ext):
+ # see gh-11544, gh-12051
+ df = DataFrame(
+ {"col": [1, 2, 3],
+ "date_strings": pd.date_range("2012-01-01", periods=3)})
+ df2 = df.copy()
+ df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y")
+
+ with ensure_clean(ext) as pth:
+ df2.to_excel(pth)
+
+ res = pd.read_excel(pth, index_col=0)
+ tm.assert_frame_equal(df2, res)
+
+ res = pd.read_excel(pth, parse_dates=["date_strings"], index_col=0)
+ tm.assert_frame_equal(df, res)
+
+ date_parser = lambda x: pd.datetime.strptime(x, "%m/%d/%Y")
+ res = pd.read_excel(pth, parse_dates=["date_strings"],
+ date_parser=date_parser, index_col=0)
+ tm.assert_frame_equal(df, res)
+
+
+class _WriterBase:
+
+ @pytest.fixture(autouse=True)
+ def set_engine_and_path(self, request, engine, ext):
+ """Fixture to set engine and open file for use in each test case
+
+ Rather than requiring `engine=...` to be provided explicitly as an
+ argument in each test, this fixture sets a global option to dictate
+ which engine should be used to write Excel files. After executing
+ the test it rolls back said change to the global option.
+
+ It also uses a context manager to open a temporary excel file for
+ the function to write to, accessible via `self.path`
+
+ Notes
+ -----
+ This fixture will run as part of each test method defined in the
+ class and any subclasses, on account of the `autouse=True`
+ argument
+ """
+ option_name = 'io.excel.{ext}.writer'.format(ext=ext.strip('.'))
+ prev_engine = get_option(option_name)
+ set_option(option_name, engine)
+ with ensure_clean(ext) as path:
+ self.path = path
+ yield
+ set_option(option_name, prev_engine) # Roll back option change
+
+
+@pytest.mark.parametrize("engine,ext", [
+ pytest.param('openpyxl', '.xlsx', marks=pytest.mark.skipif(
+ not td.safe_import('openpyxl'), reason='No openpyxl')),
+ pytest.param('openpyxl', '.xlsm', marks=pytest.mark.skipif(
+ not td.safe_import('openpyxl'), reason='No openpyxl')),
+ pytest.param('xlwt', '.xls', marks=pytest.mark.skipif(
+ not td.safe_import('xlwt'), reason='No xlwt')),
+ pytest.param('xlsxwriter', '.xlsx', marks=pytest.mark.skipif(
+ not td.safe_import('xlsxwriter'), reason='No xlsxwriter'))
+])
+class TestExcelWriter(_WriterBase):
+ # Base class for test cases to run with different Excel writers.
+
+ def test_excel_sheet_size(self, engine, ext):
+
+ # GH 26080
+ breaking_row_count = 2**20 + 1
+ breaking_col_count = 2**14 + 1
+ # purposely using two arrays to prevent memory issues while testing
+ row_arr = np.zeros(shape=(breaking_row_count, 1))
+ col_arr = np.zeros(shape=(1, breaking_col_count))
+ row_df = pd.DataFrame(row_arr)
+ col_df = pd.DataFrame(col_arr)
+
+ msg = "sheet is too large"
+ with pytest.raises(ValueError, match=msg):
+ row_df.to_excel(self.path)
+
+ with pytest.raises(ValueError, match=msg):
+ col_df.to_excel(self.path)
+
+ def test_excel_sheet_by_name_raise(self, engine, ext):
+ import xlrd
+
+ gt = DataFrame(np.random.randn(10, 2))
+ gt.to_excel(self.path)
+
+ xl = ExcelFile(self.path)
+ df = pd.read_excel(xl, 0, index_col=0)
+
+ tm.assert_frame_equal(gt, df)
+
+ with pytest.raises(xlrd.XLRDError):
+ pd.read_excel(xl, "0")
+
+ def test_excel_writer_context_manager(self, frame, engine, ext):
+ with ExcelWriter(self.path) as writer:
+ frame.to_excel(writer, "Data1")
+ frame2 = frame.copy()
+ frame2.columns = frame.columns[::-1]
+ frame2.to_excel(writer, "Data2")
+
+ with ExcelFile(self.path) as reader:
+ found_df = pd.read_excel(reader, "Data1", index_col=0)
+ found_df2 = pd.read_excel(reader, "Data2", index_col=0)
+
+ tm.assert_frame_equal(found_df, frame)
+ tm.assert_frame_equal(found_df2, frame2)
+
+ def test_roundtrip(self, engine, ext, frame):
+ frame = frame.copy()
+ frame['A'][:5] = nan
+
+ frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', index=False)
+
+ # test roundtrip
+ frame.to_excel(self.path, 'test1')
+ recons = pd.read_excel(self.path, 'test1', index_col=0)
+ tm.assert_frame_equal(frame, recons)
+
+ frame.to_excel(self.path, 'test1', index=False)
+ recons = pd.read_excel(self.path, 'test1', index_col=None)
+ recons.index = frame.index
+ tm.assert_frame_equal(frame, recons)
+
+ frame.to_excel(self.path, 'test1', na_rep='NA')
+ recons = pd.read_excel(
+ self.path, 'test1', index_col=0, na_values=['NA'])
+ tm.assert_frame_equal(frame, recons)
+
+ # GH 3611
+ frame.to_excel(self.path, 'test1', na_rep='88')
+ recons = pd.read_excel(
+ self.path, 'test1', index_col=0, na_values=['88'])
+ tm.assert_frame_equal(frame, recons)
+
+ frame.to_excel(self.path, 'test1', na_rep='88')
+ recons = pd.read_excel(
+ self.path, 'test1', index_col=0, na_values=[88, 88.0])
+ tm.assert_frame_equal(frame, recons)
+
+ # GH 6573
+ frame.to_excel(self.path, 'Sheet1')
+ recons = pd.read_excel(self.path, index_col=0)
+ tm.assert_frame_equal(frame, recons)
+
+ frame.to_excel(self.path, '0')
+ recons = pd.read_excel(self.path, index_col=0)
+ tm.assert_frame_equal(frame, recons)
+
+ # GH 8825 Pandas Series should provide to_excel method
+ s = frame["A"]
+ s.to_excel(self.path)
+ recons = pd.read_excel(self.path, index_col=0)
+ tm.assert_frame_equal(s.to_frame(), recons)
+
+ def test_mixed(self, engine, ext, frame):
+ mixed_frame = frame.copy()
+ mixed_frame['foo'] = 'bar'
+
+ mixed_frame.to_excel(self.path, 'test1')
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(reader, 'test1', index_col=0)
+ tm.assert_frame_equal(mixed_frame, recons)
+
+ def test_ts_frame(self, tsframe, engine, ext):
+ df = tsframe
+
+ df.to_excel(self.path, "test1")
+ reader = ExcelFile(self.path)
+
+ recons = pd.read_excel(reader, "test1", index_col=0)
+ tm.assert_frame_equal(df, recons)
+
+ def test_basics_with_nan(self, engine, ext, frame):
+ frame = frame.copy()
+ frame['A'][:5] = nan
+ frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', index=False)
+
+ @pytest.mark.parametrize("np_type", [
+ np.int8, np.int16, np.int32, np.int64])
+ def test_int_types(self, engine, ext, np_type):
+ # Test np.int values read come back as int
+ # (rather than float which is Excel's format).
+ df = DataFrame(np.random.randint(-10, 10, size=(10, 2)),
+ dtype=np_type)
+ df.to_excel(self.path, "test1")
+
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(reader, "test1", index_col=0)
+
+ int_frame = df.astype(np.int64)
+ tm.assert_frame_equal(int_frame, recons)
+
+ recons2 = pd.read_excel(self.path, "test1", index_col=0)
+ tm.assert_frame_equal(int_frame, recons2)
+
+ # Test with convert_float=False comes back as float.
+ float_frame = df.astype(float)
+ recons = pd.read_excel(self.path, "test1",
+ convert_float=False, index_col=0)
+ tm.assert_frame_equal(recons, float_frame,
+ check_index_type=False,
+ check_column_type=False)
+
+ @pytest.mark.parametrize("np_type", [
+ np.float16, np.float32, np.float64])
+ def test_float_types(self, engine, ext, np_type):
+ # Test np.float values read come back as float.
+ df = DataFrame(np.random.random_sample(10), dtype=np_type)
+ df.to_excel(self.path, "test1")
+
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(reader, "test1", index_col=0).astype(np_type)
+
+ tm.assert_frame_equal(df, recons, check_dtype=False)
+
+ @pytest.mark.parametrize("np_type", [np.bool8, np.bool_])
+ def test_bool_types(self, engine, ext, np_type):
+ # Test np.bool values read come back as float.
+ df = (DataFrame([1, 0, True, False], dtype=np_type))
+ df.to_excel(self.path, "test1")
+
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(reader, "test1", index_col=0).astype(np_type)
+
+ tm.assert_frame_equal(df, recons)
+
+ def test_inf_roundtrip(self, engine, ext):
+ df = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)])
+ df.to_excel(self.path, "test1")
+
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(reader, "test1", index_col=0)
+
+ tm.assert_frame_equal(df, recons)
+
+ def test_sheets(self, engine, ext, frame, tsframe):
+ frame = frame.copy()
+ frame['A'][:5] = nan
+
+ frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', index=False)
+
+ # Test writing to separate sheets
+ writer = ExcelWriter(self.path)
+ frame.to_excel(writer, 'test1')
+ tsframe.to_excel(writer, 'test2')
+ writer.save()
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(reader, 'test1', index_col=0)
+ tm.assert_frame_equal(frame, recons)
+ recons = pd.read_excel(reader, 'test2', index_col=0)
+ tm.assert_frame_equal(tsframe, recons)
+ assert 2 == len(reader.sheet_names)
+ assert 'test1' == reader.sheet_names[0]
+ assert 'test2' == reader.sheet_names[1]
+
+ def test_colaliases(self, engine, ext, frame):
+ frame = frame.copy()
+ frame['A'][:5] = nan
+
+ frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', index=False)
+
+ # column aliases
+ col_aliases = Index(['AA', 'X', 'Y', 'Z'])
+ frame.to_excel(self.path, 'test1', header=col_aliases)
+ reader = ExcelFile(self.path)
+ rs = pd.read_excel(reader, 'test1', index_col=0)
+ xp = frame.copy()
+ xp.columns = col_aliases
+ tm.assert_frame_equal(xp, rs)
+
+ def test_roundtrip_indexlabels(self, merge_cells, engine, ext, frame):
+ frame = frame.copy()
+ frame['A'][:5] = nan
+
+ frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', index=False)
+
+ # test index_label
+ df = (DataFrame(np.random.randn(10, 2)) >= 0)
+ df.to_excel(self.path, 'test1',
+ index_label=['test'],
+ merge_cells=merge_cells)
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(
+ reader, 'test1', index_col=0).astype(np.int64)
+ df.index.names = ['test']
+ assert df.index.names == recons.index.names
+
+ df = (DataFrame(np.random.randn(10, 2)) >= 0)
+ df.to_excel(self.path,
+ 'test1',
+ index_label=['test', 'dummy', 'dummy2'],
+ merge_cells=merge_cells)
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(
+ reader, 'test1', index_col=0).astype(np.int64)
+ df.index.names = ['test']
+ assert df.index.names == recons.index.names
+
+ df = (DataFrame(np.random.randn(10, 2)) >= 0)
+ df.to_excel(self.path,
+ 'test1',
+ index_label='test',
+ merge_cells=merge_cells)
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(
+ reader, 'test1', index_col=0).astype(np.int64)
+ df.index.names = ['test']
+ tm.assert_frame_equal(df, recons.astype(bool))
+
+ frame.to_excel(self.path,
+ 'test1',
+ columns=['A', 'B', 'C', 'D'],
+ index=False, merge_cells=merge_cells)
+ # take 'A' and 'B' as indexes (same row as cols 'C', 'D')
+ df = frame.copy()
+ df = df.set_index(['A', 'B'])
+
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(reader, 'test1', index_col=[0, 1])
+ tm.assert_frame_equal(df, recons, check_less_precise=True)
+
+ def test_excel_roundtrip_indexname(self, merge_cells, engine, ext):
+ df = DataFrame(np.random.randn(10, 4))
+ df.index.name = 'foo'
+
+ df.to_excel(self.path, merge_cells=merge_cells)
+
+ xf = ExcelFile(self.path)
+ result = pd.read_excel(xf, xf.sheet_names[0], index_col=0)
+
+ tm.assert_frame_equal(result, df)
+ assert result.index.name == 'foo'
+
+ def test_excel_roundtrip_datetime(self, merge_cells, tsframe, engine, ext):
+ # datetime.date, not sure what to test here exactly
+ tsf = tsframe.copy()
+
+ tsf.index = [x.date() for x in tsframe.index]
+ tsf.to_excel(self.path, "test1", merge_cells=merge_cells)
+
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(reader, "test1", index_col=0)
+
+ tm.assert_frame_equal(tsframe, recons)
+
+ def test_excel_date_datetime_format(self, engine, ext):
+ # see gh-4133
+ #
+ # Excel output format strings
+ df = DataFrame([[date(2014, 1, 31),
+ date(1999, 9, 24)],
+ [datetime(1998, 5, 26, 23, 33, 4),
+ datetime(2014, 2, 28, 13, 5, 13)]],
+ index=["DATE", "DATETIME"], columns=["X", "Y"])
+ df_expected = DataFrame([[datetime(2014, 1, 31),
+ datetime(1999, 9, 24)],
+ [datetime(1998, 5, 26, 23, 33, 4),
+ datetime(2014, 2, 28, 13, 5, 13)]],
+ index=["DATE", "DATETIME"], columns=["X", "Y"])
+
+ with ensure_clean(ext) as filename2:
+ writer1 = ExcelWriter(self.path)
+ writer2 = ExcelWriter(filename2,
+ date_format="DD.MM.YYYY",
+ datetime_format="DD.MM.YYYY HH-MM-SS")
+
+ df.to_excel(writer1, "test1")
+ df.to_excel(writer2, "test1")
+
+ writer1.close()
+ writer2.close()
+
+ reader1 = ExcelFile(self.path)
+ reader2 = ExcelFile(filename2)
+
+ rs1 = pd.read_excel(reader1, "test1", index_col=0)
+ rs2 = pd.read_excel(reader2, "test1", index_col=0)
+
+ tm.assert_frame_equal(rs1, rs2)
+
+ # Since the reader returns a datetime object for dates,
+ # we need to use df_expected to check the result.
+ tm.assert_frame_equal(rs2, df_expected)
+
+ def test_to_excel_interval_no_labels(self, engine, ext):
+ # see gh-19242
+ #
+ # Test writing Interval without labels.
+ df = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
+ dtype=np.int64)
+ expected = df.copy()
+
+ df["new"] = pd.cut(df[0], 10)
+ expected["new"] = pd.cut(expected[0], 10).astype(str)
+
+ df.to_excel(self.path, "test1")
+ reader = ExcelFile(self.path)
+
+ recons = pd.read_excel(reader, "test1", index_col=0)
+ tm.assert_frame_equal(expected, recons)
+
+ def test_to_excel_interval_labels(self, engine, ext):
+ # see gh-19242
+ #
+ # Test writing Interval with labels.
+ df = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
+ dtype=np.int64)
+ expected = df.copy()
+ intervals = pd.cut(df[0], 10, labels=["A", "B", "C", "D", "E",
+ "F", "G", "H", "I", "J"])
+ df["new"] = intervals
+ expected["new"] = pd.Series(list(intervals))
+
+ df.to_excel(self.path, "test1")
+ reader = ExcelFile(self.path)
+
+ recons = pd.read_excel(reader, "test1", index_col=0)
+ tm.assert_frame_equal(expected, recons)
+
+ def test_to_excel_timedelta(self, engine, ext):
+ # see gh-19242, gh-9155
+ #
+ # Test writing timedelta to xls.
+ df = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
+ columns=["A"], dtype=np.int64)
+ expected = df.copy()
+
+ df["new"] = df["A"].apply(lambda x: timedelta(seconds=x))
+ expected["new"] = expected["A"].apply(
+ lambda x: timedelta(seconds=x).total_seconds() / float(86400))
+
+ df.to_excel(self.path, "test1")
+ reader = ExcelFile(self.path)
+
+ recons = pd.read_excel(reader, "test1", index_col=0)
+ tm.assert_frame_equal(expected, recons)
+
+ def test_to_excel_periodindex(self, engine, ext, tsframe):
+ xp = tsframe.resample('M', kind='period').mean()
+
+ xp.to_excel(self.path, 'sht1')
+
+ reader = ExcelFile(self.path)
+ rs = pd.read_excel(reader, 'sht1', index_col=0)
+ tm.assert_frame_equal(xp, rs.to_period('M'))
+
+ def test_to_excel_multiindex(self, merge_cells, engine, ext, frame):
+ arrays = np.arange(len(frame.index) * 2).reshape(2, -1)
+ new_index = MultiIndex.from_arrays(arrays,
+ names=['first', 'second'])
+ frame.index = new_index
+
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+
+ # round trip
+ frame.to_excel(self.path, 'test1', merge_cells=merge_cells)
+ reader = ExcelFile(self.path)
+ df = pd.read_excel(reader, 'test1', index_col=[0, 1])
+ tm.assert_frame_equal(frame, df)
+
+ # GH13511
+ def test_to_excel_multiindex_nan_label(self, merge_cells, engine, ext):
+ df = pd.DataFrame({'A': [None, 2, 3],
+ 'B': [10, 20, 30],
+ 'C': np.random.sample(3)})
+ df = df.set_index(['A', 'B'])
+
+ df.to_excel(self.path, merge_cells=merge_cells)
+ df1 = pd.read_excel(self.path, index_col=[0, 1])
+ tm.assert_frame_equal(df, df1)
+
+ # Test for Issue 11328. If column indices are integers, make
+ # sure they are handled correctly for either setting of
+ # merge_cells
+ def test_to_excel_multiindex_cols(self, merge_cells, engine, ext, frame):
+ arrays = np.arange(len(frame.index) * 2).reshape(2, -1)
+ new_index = MultiIndex.from_arrays(arrays,
+ names=['first', 'second'])
+ frame.index = new_index
+
+ new_cols_index = MultiIndex.from_tuples([(40, 1), (40, 2),
+ (50, 1), (50, 2)])
+ frame.columns = new_cols_index
+ header = [0, 1]
+ if not merge_cells:
+ header = 0
+
+ # round trip
+ frame.to_excel(self.path, 'test1', merge_cells=merge_cells)
+ reader = ExcelFile(self.path)
+ df = pd.read_excel(reader, 'test1', header=header, index_col=[0, 1])
+ if not merge_cells:
+ fm = frame.columns.format(sparsify=False,
+ adjoin=False, names=False)
+ frame.columns = [".".join(map(str, q)) for q in zip(*fm)]
+ tm.assert_frame_equal(frame, df)
+
+ def test_to_excel_multiindex_dates(
+ self, merge_cells, engine, ext, tsframe):
+ # try multiindex with dates
+ new_index = [tsframe.index, np.arange(len(tsframe.index))]
+ tsframe.index = MultiIndex.from_arrays(new_index)
+
+ tsframe.index.names = ['time', 'foo']
+ tsframe.to_excel(self.path, 'test1', merge_cells=merge_cells)
+ reader = ExcelFile(self.path)
+ recons = pd.read_excel(reader, 'test1', index_col=[0, 1])
+
+ tm.assert_frame_equal(tsframe, recons)
+ assert recons.index.names == ('time', 'foo')
+
+ def test_to_excel_multiindex_no_write_index(self, engine, ext):
+ # Test writing and re-reading a MI witout the index. GH 5616.
+
+ # Initial non-MI frame.
+ frame1 = DataFrame({'a': [10, 20], 'b': [30, 40], 'c': [50, 60]})
+
+ # Add a MI.
+ frame2 = frame1.copy()
+ multi_index = MultiIndex.from_tuples([(70, 80), (90, 100)])
+ frame2.index = multi_index
+
+ # Write out to Excel without the index.
+ frame2.to_excel(self.path, 'test1', index=False)
+
+ # Read it back in.
+ reader = ExcelFile(self.path)
+ frame3 = pd.read_excel(reader, 'test1')
+
+ # Test that it is the same as the initial frame.
+ tm.assert_frame_equal(frame1, frame3)
+
+ def test_to_excel_float_format(self, engine, ext):
+ df = DataFrame([[0.123456, 0.234567, 0.567567],
+ [12.32112, 123123.2, 321321.2]],
+ index=["A", "B"], columns=["X", "Y", "Z"])
+ df.to_excel(self.path, "test1", float_format="%.2f")
+
+ reader = ExcelFile(self.path)
+ result = pd.read_excel(reader, "test1", index_col=0)
+
+ expected = DataFrame([[0.12, 0.23, 0.57],
+ [12.32, 123123.20, 321321.20]],
+ index=["A", "B"], columns=["X", "Y", "Z"])
+ tm.assert_frame_equal(result, expected)
+
+ def test_to_excel_output_encoding(self, engine, ext):
+ # Avoid mixed inferred_type.
+ df = DataFrame([["\u0192", "\u0193", "\u0194"],
+ ["\u0195", "\u0196", "\u0197"]],
+ index=["A\u0192", "B"],
+ columns=["X\u0193", "Y", "Z"])
+
+ with ensure_clean("__tmp_to_excel_float_format__." + ext) as filename:
+ df.to_excel(filename, sheet_name="TestSheet", encoding="utf8")
+ result = pd.read_excel(filename, "TestSheet",
+ encoding="utf8", index_col=0)
+ tm.assert_frame_equal(result, df)
+
+ def test_to_excel_unicode_filename(self, engine, ext):
+ with ensure_clean("\u0192u." + ext) as filename:
+ try:
+ f = open(filename, "wb")
+ except UnicodeEncodeError:
+ pytest.skip("No unicode file names on this system")
+ else:
+ f.close()
+
+ df = DataFrame([[0.123456, 0.234567, 0.567567],
+ [12.32112, 123123.2, 321321.2]],
+ index=["A", "B"], columns=["X", "Y", "Z"])
+ df.to_excel(filename, "test1", float_format="%.2f")
+
+ reader = ExcelFile(filename)
+ result = pd.read_excel(reader, "test1", index_col=0)
+
+ expected = DataFrame([[0.12, 0.23, 0.57],
+ [12.32, 123123.20, 321321.20]],
+ index=["A", "B"], columns=["X", "Y", "Z"])
+ tm.assert_frame_equal(result, expected)
+
+ # def test_to_excel_header_styling_xls(self, engine, ext):
+
+ # import StringIO
+ # s = StringIO(
+ # """Date,ticker,type,value
+ # 2001-01-01,x,close,12.2
+ # 2001-01-01,x,open ,12.1
+ # 2001-01-01,y,close,12.2
+ # 2001-01-01,y,open ,12.1
+ # 2001-02-01,x,close,12.2
+ # 2001-02-01,x,open ,12.1
+ # 2001-02-01,y,close,12.2
+ # 2001-02-01,y,open ,12.1
+ # 2001-03-01,x,close,12.2
+ # 2001-03-01,x,open ,12.1
+ # 2001-03-01,y,close,12.2
+ # 2001-03-01,y,open ,12.1""")
+ # df = read_csv(s, parse_dates=["Date"])
+ # pdf = df.pivot_table(values="value", rows=["ticker"],
+ # cols=["Date", "type"])
+
+ # try:
+ # import xlwt
+ # import xlrd
+ # except ImportError:
+ # pytest.skip
+
+ # filename = '__tmp_to_excel_header_styling_xls__.xls'
+ # pdf.to_excel(filename, 'test1')
+
+ # wbk = xlrd.open_workbook(filename,
+ # formatting_info=True)
+ # assert ["test1"] == wbk.sheet_names()
+ # ws = wbk.sheet_by_name('test1')
+ # assert [(0, 1, 5, 7), (0, 1, 3, 5), (0, 1, 1, 3)] == ws.merged_cells
+ # for i in range(0, 2):
+ # for j in range(0, 7):
+ # xfx = ws.cell_xf_index(0, 0)
+ # cell_xf = wbk.xf_list[xfx]
+ # font = wbk.font_list
+ # assert 1 == font[cell_xf.font_index].bold
+ # assert 1 == cell_xf.border.top_line_style
+ # assert 1 == cell_xf.border.right_line_style
+ # assert 1 == cell_xf.border.bottom_line_style
+ # assert 1 == cell_xf.border.left_line_style
+ # assert 2 == cell_xf.alignment.hor_align
+ # os.remove(filename)
+ # def test_to_excel_header_styling_xlsx(self, engine, ext):
+ # import StringIO
+ # s = StringIO(
+ # """Date,ticker,type,value
+ # 2001-01-01,x,close,12.2
+ # 2001-01-01,x,open ,12.1
+ # 2001-01-01,y,close,12.2
+ # 2001-01-01,y,open ,12.1
+ # 2001-02-01,x,close,12.2
+ # 2001-02-01,x,open ,12.1
+ # 2001-02-01,y,close,12.2
+ # 2001-02-01,y,open ,12.1
+ # 2001-03-01,x,close,12.2
+ # 2001-03-01,x,open ,12.1
+ # 2001-03-01,y,close,12.2
+ # 2001-03-01,y,open ,12.1""")
+ # df = read_csv(s, parse_dates=["Date"])
+ # pdf = df.pivot_table(values="value", rows=["ticker"],
+ # cols=["Date", "type"])
+ # try:
+ # import openpyxl
+ # from openpyxl.cell import get_column_letter
+ # except ImportError:
+ # pytest.skip
+ # if openpyxl.__version__ < '1.6.1':
+ # pytest.skip
+ # # test xlsx_styling
+ # filename = '__tmp_to_excel_header_styling_xlsx__.xlsx'
+ # pdf.to_excel(filename, 'test1')
+ # wbk = openpyxl.load_workbook(filename)
+ # assert ["test1"] == wbk.get_sheet_names()
+ # ws = wbk.get_sheet_by_name('test1')
+ # xlsaddrs = ["%s2" % chr(i) for i in range(ord('A'), ord('H'))]
+ # xlsaddrs += ["A%s" % i for i in range(1, 6)]
+ # xlsaddrs += ["B1", "D1", "F1"]
+ # for xlsaddr in xlsaddrs:
+ # cell = ws.cell(xlsaddr)
+ # assert cell.style.font.bold
+ # assert (openpyxl.style.Border.BORDER_THIN ==
+ # cell.style.borders.top.border_style)
+ # assert (openpyxl.style.Border.BORDER_THIN ==
+ # cell.style.borders.right.border_style)
+ # assert (openpyxl.style.Border.BORDER_THIN ==
+ # cell.style.borders.bottom.border_style)
+ # assert (openpyxl.style.Border.BORDER_THIN ==
+ # cell.style.borders.left.border_style)
+ # assert (openpyxl.style.Alignment.HORIZONTAL_CENTER ==
+ # cell.style.alignment.horizontal)
+ # mergedcells_addrs = ["C1", "E1", "G1"]
+ # for maddr in mergedcells_addrs:
+ # assert ws.cell(maddr).merged
+ # os.remove(filename)
+
+ @pytest.mark.parametrize("use_headers", [True, False])
+ @pytest.mark.parametrize("r_idx_nlevels", [1, 2, 3])
+ @pytest.mark.parametrize("c_idx_nlevels", [1, 2, 3])
+ def test_excel_010_hemstring(self, merge_cells, engine, ext,
+ c_idx_nlevels, r_idx_nlevels, use_headers):
+
+ def roundtrip(data, header=True, parser_hdr=0, index=True):
+ data.to_excel(self.path, header=header,
+ merge_cells=merge_cells, index=index)
+
+ xf = ExcelFile(self.path)
+ return pd.read_excel(xf, xf.sheet_names[0], header=parser_hdr)
+
+ # Basic test.
+ parser_header = 0 if use_headers else None
+ res = roundtrip(DataFrame([0]), use_headers, parser_header)
+
+ assert res.shape == (1, 2)
+ assert res.iloc[0, 0] is not np.nan
+
+ # More complex tests with multi-index.
+ nrows = 5
+ ncols = 3
+
+ from pandas.util.testing import makeCustomDataframe as mkdf
+ # ensure limited functionality in 0.10
+ # override of gh-2370 until sorted out in 0.11
+
+ df = mkdf(nrows, ncols, r_idx_nlevels=r_idx_nlevels,
+ c_idx_nlevels=c_idx_nlevels)
+
+ # This if will be removed once multi-column Excel writing
+ # is implemented. For now fixing gh-9794.
+ if c_idx_nlevels > 1:
+ with pytest.raises(NotImplementedError):
+ roundtrip(df, use_headers, index=False)
+ else:
+ res = roundtrip(df, use_headers)
+
+ if use_headers:
+ assert res.shape == (nrows, ncols + r_idx_nlevels)
+ else:
+ # First row taken as columns.
+ assert res.shape == (nrows - 1, ncols + r_idx_nlevels)
+
+ # No NaNs.
+ for r in range(len(res.index)):
+ for c in range(len(res.columns)):
+ assert res.iloc[r, c] is not np.nan
+
+ def test_duplicated_columns(self, engine, ext):
+ # see gh-5235
+ df = DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]],
+ columns=["A", "B", "B"])
+ df.to_excel(self.path, "test1")
+ expected = DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]],
+ columns=["A", "B", "B.1"])
+
+ # By default, we mangle.
+ result = pd.read_excel(self.path, "test1", index_col=0)
+ tm.assert_frame_equal(result, expected)
+
+ # Explicitly, we pass in the parameter.
+ result = pd.read_excel(self.path, "test1", index_col=0,
+ mangle_dupe_cols=True)
+ tm.assert_frame_equal(result, expected)
+
+ # see gh-11007, gh-10970
+ df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]],
+ columns=["A", "B", "A", "B"])
+ df.to_excel(self.path, "test1")
+
+ result = pd.read_excel(self.path, "test1", index_col=0)
+ expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]],
+ columns=["A", "B", "A.1", "B.1"])
+ tm.assert_frame_equal(result, expected)
+
+ # see gh-10982
+ df.to_excel(self.path, "test1", index=False, header=False)
+ result = pd.read_excel(self.path, "test1", header=None)
+
+ expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
+ tm.assert_frame_equal(result, expected)
+
+ msg = "Setting mangle_dupe_cols=False is not supported yet"
+ with pytest.raises(ValueError, match=msg):
+ pd.read_excel(
+ self.path, "test1", header=None, mangle_dupe_cols=False)
+
+ def test_swapped_columns(self, engine, ext):
+ # Test for issue #5427.
+ write_frame = DataFrame({'A': [1, 1, 1],
+ 'B': [2, 2, 2]})
+ write_frame.to_excel(self.path, 'test1', columns=['B', 'A'])
+
+ read_frame = pd.read_excel(self.path, 'test1', header=0)
+
+ tm.assert_series_equal(write_frame['A'], read_frame['A'])
+ tm.assert_series_equal(write_frame['B'], read_frame['B'])
+
+ def test_invalid_columns(self, engine, ext):
+ # see gh-10982
+ write_frame = DataFrame({"A": [1, 1, 1],
+ "B": [2, 2, 2]})
+
+ with tm.assert_produces_warning(FutureWarning,
+ check_stacklevel=False):
+ write_frame.to_excel(self.path, "test1", columns=["B", "C"])
+
+ expected = write_frame.reindex(columns=["B", "C"])
+ read_frame = pd.read_excel(self.path, "test1", index_col=0)
+ tm.assert_frame_equal(expected, read_frame)
+
+ with pytest.raises(KeyError):
+ write_frame.to_excel(self.path, "test1", columns=["C", "D"])
+
+ def test_comment_arg(self, engine, ext):
+ # see gh-18735
+ #
+ # Test the comment argument functionality to pd.read_excel.
+
+ # Create file to read in.
+ df = DataFrame({"A": ["one", "#one", "one"],
+ "B": ["two", "two", "#two"]})
+ df.to_excel(self.path, "test_c")
+
+ # Read file without comment arg.
+ result1 = pd.read_excel(self.path, "test_c", index_col=0)
+
+ result1.iloc[1, 0] = None
+ result1.iloc[1, 1] = None
+ result1.iloc[2, 1] = None
+
+ result2 = pd.read_excel(self.path, "test_c", comment="#", index_col=0)
+ tm.assert_frame_equal(result1, result2)
+
+ def test_comment_default(self, engine, ext):
+ # Re issue #18735
+ # Test the comment argument default to pd.read_excel
+
+ # Create file to read in
+ df = DataFrame({'A': ['one', '#one', 'one'],
+ 'B': ['two', 'two', '#two']})
+ df.to_excel(self.path, 'test_c')
+
+ # Read file with default and explicit comment=None
+ result1 = pd.read_excel(self.path, 'test_c')
+ result2 = pd.read_excel(self.path, 'test_c', comment=None)
+ tm.assert_frame_equal(result1, result2)
+
+ def test_comment_used(self, engine, ext):
+ # see gh-18735
+ #
+ # Test the comment argument is working as expected when used.
+
+ # Create file to read in.
+ df = DataFrame({"A": ["one", "#one", "one"],
+ "B": ["two", "two", "#two"]})
+ df.to_excel(self.path, "test_c")
+
+ # Test read_frame_comment against manually produced expected output.
+ expected = DataFrame({"A": ["one", None, "one"],
+ "B": ["two", None, None]})
+ result = pd.read_excel(self.path, "test_c", comment="#", index_col=0)
+ tm.assert_frame_equal(result, expected)
+
+ def test_comment_empty_line(self, engine, ext):
+ # Re issue #18735
+ # Test that pd.read_excel ignores commented lines at the end of file
+
+ df = DataFrame({'a': ['1', '#2'], 'b': ['2', '3']})
+ df.to_excel(self.path, index=False)
+
+ # Test that all-comment lines at EoF are ignored
+ expected = DataFrame({'a': [1], 'b': [2]})
+ result = pd.read_excel(self.path, comment='#')
+ tm.assert_frame_equal(result, expected)
+
+ def test_datetimes(self, engine, ext):
+
+ # Test writing and reading datetimes. For issue #9139. (xref #9185)
+ datetimes = [datetime(2013, 1, 13, 1, 2, 3),
+ datetime(2013, 1, 13, 2, 45, 56),
+ datetime(2013, 1, 13, 4, 29, 49),
+ datetime(2013, 1, 13, 6, 13, 42),
+ datetime(2013, 1, 13, 7, 57, 35),
+ datetime(2013, 1, 13, 9, 41, 28),
+ datetime(2013, 1, 13, 11, 25, 21),
+ datetime(2013, 1, 13, 13, 9, 14),
+ datetime(2013, 1, 13, 14, 53, 7),
+ datetime(2013, 1, 13, 16, 37, 0),
+ datetime(2013, 1, 13, 18, 20, 52)]
+
+ write_frame = DataFrame({'A': datetimes})
+ write_frame.to_excel(self.path, 'Sheet1')
+ read_frame = pd.read_excel(self.path, 'Sheet1', header=0)
+
+ tm.assert_series_equal(write_frame['A'], read_frame['A'])
+
+ def test_bytes_io(self, engine, ext):
+ # see gh-7074
+ bio = BytesIO()
+ df = DataFrame(np.random.randn(10, 2))
+
+ # Pass engine explicitly, as there is no file path to infer from.
+ writer = ExcelWriter(bio, engine=engine)
+ df.to_excel(writer)
+ writer.save()
+
+ bio.seek(0)
+ reread_df = pd.read_excel(bio, index_col=0)
+ tm.assert_frame_equal(df, reread_df)
+
+ def test_write_lists_dict(self, engine, ext):
+ # see gh-8188.
+ df = DataFrame({"mixed": ["a", ["b", "c"], {"d": "e", "f": 2}],
+ "numeric": [1, 2, 3.0],
+ "str": ["apple", "banana", "cherry"]})
+ df.to_excel(self.path, "Sheet1")
+ read = pd.read_excel(self.path, "Sheet1", header=0, index_col=0)
+
+ expected = df.copy()
+ expected.mixed = expected.mixed.apply(str)
+ expected.numeric = expected.numeric.astype("int64")
+
+ tm.assert_frame_equal(read, expected)
+
+ def test_true_and_false_value_options(self, engine, ext):
+ # see gh-13347
+ df = pd.DataFrame([["foo", "bar"]], columns=["col1", "col2"])
+ expected = df.replace({"foo": True, "bar": False})
+
+ df.to_excel(self.path)
+ read_frame = pd.read_excel(self.path, true_values=["foo"],
+ false_values=["bar"], index_col=0)
+ tm.assert_frame_equal(read_frame, expected)
+
+ def test_freeze_panes(self, engine, ext):
+ # see gh-15160
+ expected = DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"])
+ expected.to_excel(self.path, "Sheet1", freeze_panes=(1, 1))
+
+ result = pd.read_excel(self.path, index_col=0)
+ tm.assert_frame_equal(result, expected)
+
+ def test_path_path_lib(self, engine, ext):
+ df = tm.makeDataFrame()
+ writer = partial(df.to_excel, engine=engine)
+
+ reader = partial(pd.read_excel, index_col=0)
+ result = tm.round_trip_pathlib(writer, reader,
+ path="foo.{ext}".format(ext=ext))
+ tm.assert_frame_equal(result, df)
+
+ def test_path_local_path(self, engine, ext):
+ df = tm.makeDataFrame()
+ writer = partial(df.to_excel, engine=engine)
+
+ reader = partial(pd.read_excel, index_col=0)
+ result = tm.round_trip_pathlib(writer, reader,
+ path="foo.{ext}".format(ext=ext))
+ tm.assert_frame_equal(result, df)
+
+
+class TestExcelWriterEngineTests:
+
+ @pytest.mark.parametrize('klass,ext', [
+ pytest.param(_XlsxWriter, '.xlsx', marks=pytest.mark.skipif(
+ not td.safe_import('xlsxwriter'), reason='No xlsxwriter')),
+ pytest.param(_OpenpyxlWriter, '.xlsx', marks=pytest.mark.skipif(
+ not td.safe_import('openpyxl'), reason='No openpyxl')),
+ pytest.param(_XlwtWriter, '.xls', marks=pytest.mark.skipif(
+ not td.safe_import('xlwt'), reason='No xlwt'))
+ ])
+ def test_ExcelWriter_dispatch(self, klass, ext):
+ with ensure_clean(ext) as path:
+ writer = ExcelWriter(path)
+ if ext == '.xlsx' and td.safe_import('xlsxwriter'):
+ # xlsxwriter has preference over openpyxl if both installed
+ assert isinstance(writer, _XlsxWriter)
+ else:
+ assert isinstance(writer, klass)
+
+ def test_ExcelWriter_dispatch_raises(self):
+ with pytest.raises(ValueError, match='No engine'):
+ ExcelWriter('nothing')
+
+ def test_register_writer(self):
+ # some awkward mocking to test out dispatch and such actually works
+ called_save = []
+ called_write_cells = []
+
+ class DummyClass(ExcelWriter):
+ called_save = False
+ called_write_cells = False
+ supported_extensions = ['xlsx', 'xls']
+ engine = 'dummy'
+
+ def save(self):
+ called_save.append(True)
+
+ def write_cells(self, *args, **kwargs):
+ called_write_cells.append(True)
+
+ def check_called(func):
+ func()
+ assert len(called_save) >= 1
+ assert len(called_write_cells) >= 1
+ del called_save[:]
+ del called_write_cells[:]
+
+ with pd.option_context('io.excel.xlsx.writer', 'dummy'):
+ register_writer(DummyClass)
+ writer = ExcelWriter('something.xlsx')
+ assert isinstance(writer, DummyClass)
+ df = tm.makeCustomDataframe(1, 1)
+ check_called(lambda: df.to_excel('something.xlsx'))
+ check_called(
+ lambda: df.to_excel(
+ 'something.xls', engine='dummy'))
+
+
+@td.skip_if_no('openpyxl')
+@pytest.mark.skipif(not PY36, reason='requires fspath')
+class TestFSPath:
+
+ def test_excelfile_fspath(self):
+ with tm.ensure_clean('foo.xlsx') as path:
+ df = DataFrame({"A": [1, 2]})
+ df.to_excel(path)
+ xl = ExcelFile(path)
+ result = os.fspath(xl)
+ assert result == path
+
+ def test_excelwriter_fspath(self):
+ with tm.ensure_clean('foo.xlsx') as path:
+ writer = ExcelWriter(path)
+ assert os.fspath(writer) == str(path)
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
new file mode 100644
index 0000000000000..18eac830d447e
--- /dev/null
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -0,0 +1,35 @@
+import pandas.util._test_decorators as td
+
+import pandas as pd
+import pandas.util.testing as tm
+from pandas.util.testing import ensure_clean
+
+from pandas.io.excel import ExcelFile
+
+
+@td.skip_if_no('xlrd')
+class TestXlrdReader:
+ """
+ This is the base class for the xlrd tests, and 3 different file formats
+ are supported: xls, xlsx, xlsm
+ """
+
+ @td.skip_if_no("xlwt")
+ def test_read_xlrd_book(self, read_ext, frame):
+ import xlrd
+ df = frame
+
+ engine = "xlrd"
+ sheet_name = "SheetA"
+
+ with ensure_clean(read_ext) as pth:
+ df.to_excel(pth, sheet_name)
+ book = xlrd.open_workbook(pth)
+
+ with ExcelFile(book, engine=engine) as xl:
+ result = pd.read_excel(xl, sheet_name, index_col=0)
+ tm.assert_frame_equal(df, result)
+
+ result = pd.read_excel(book, sheet_name=sheet_name,
+ engine=engine, index_col=0)
+ tm.assert_frame_equal(df, result)
diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py
new file mode 100644
index 0000000000000..f8c78c57f44a7
--- /dev/null
+++ b/pandas/tests/io/excel/test_xlsxwriter.py
@@ -0,0 +1,67 @@
+import warnings
+
+import pytest
+
+import pandas.util._test_decorators as td
+
+from pandas import DataFrame
+from pandas.util.testing import ensure_clean
+
+from pandas.io.excel import ExcelWriter
+
+
+@td.skip_if_no('xlsxwriter')
+@pytest.mark.parametrize("ext", ['.xlsx'])
+class TestXlsxWriterTests:
+
+ @td.skip_if_no('openpyxl')
+ def test_column_format(self, ext):
+ # Test that column formats are applied to cells. Test for issue #9167.
+ # Applicable to xlsxwriter only.
+ with warnings.catch_warnings():
+ # Ignore the openpyxl lxml warning.
+ warnings.simplefilter("ignore")
+ import openpyxl
+
+ with ensure_clean(ext) as path:
+ frame = DataFrame({'A': [123456, 123456],
+ 'B': [123456, 123456]})
+
+ writer = ExcelWriter(path)
+ frame.to_excel(writer)
+
+ # Add a number format to col B and ensure it is applied to cells.
+ num_format = '#,##0'
+ write_workbook = writer.book
+ write_worksheet = write_workbook.worksheets()[0]
+ col_format = write_workbook.add_format({'num_format': num_format})
+ write_worksheet.set_column('B:B', None, col_format)
+ writer.save()
+
+ read_workbook = openpyxl.load_workbook(path)
+ try:
+ read_worksheet = read_workbook['Sheet1']
+ except TypeError:
+ # compat
+ read_worksheet = read_workbook.get_sheet_by_name(name='Sheet1')
+
+ # Get the number format from the cell.
+ try:
+ cell = read_worksheet['B2']
+ except TypeError:
+ # compat
+ cell = read_worksheet.cell('B2')
+
+ try:
+ read_num_format = cell.number_format
+ except Exception:
+ read_num_format = cell.style.number_format._format_code
+
+ assert read_num_format == num_format
+
+ def test_write_append_mode_raises(self, ext):
+ msg = "Append mode is not supported with xlsxwriter!"
+
+ with ensure_clean(ext) as f:
+ with pytest.raises(ValueError, match=msg):
+ ExcelWriter(f, engine='xlsxwriter', mode='a')
diff --git a/pandas/tests/io/excel/test_xlwt.py b/pandas/tests/io/excel/test_xlwt.py
new file mode 100644
index 0000000000000..bbed8a3d67ecf
--- /dev/null
+++ b/pandas/tests/io/excel/test_xlwt.py
@@ -0,0 +1,69 @@
+import numpy as np
+import pytest
+
+import pandas.util._test_decorators as td
+
+import pandas as pd
+from pandas import DataFrame, MultiIndex
+from pandas.util.testing import ensure_clean
+
+from pandas.io.excel import ExcelWriter, _XlwtWriter
+
+
+@td.skip_if_no('xlwt')
+@pytest.mark.parametrize("ext,", ['.xls'])
+class TestXlwtTests:
+
+ def test_excel_raise_error_on_multiindex_columns_and_no_index(
+ self, ext):
+ # MultiIndex as columns is not yet implemented 9794
+ cols = MultiIndex.from_tuples([('site', ''),
+ ('2014', 'height'),
+ ('2014', 'weight')])
+ df = DataFrame(np.random.randn(10, 3), columns=cols)
+ with pytest.raises(NotImplementedError):
+ with ensure_clean(ext) as path:
+ df.to_excel(path, index=False)
+
+ def test_excel_multiindex_columns_and_index_true(self, ext):
+ cols = MultiIndex.from_tuples([('site', ''),
+ ('2014', 'height'),
+ ('2014', 'weight')])
+ df = pd.DataFrame(np.random.randn(10, 3), columns=cols)
+ with ensure_clean(ext) as path:
+ df.to_excel(path, index=True)
+
+ def test_excel_multiindex_index(self, ext):
+ # MultiIndex as index works so assert no error #9794
+ cols = MultiIndex.from_tuples([('site', ''),
+ ('2014', 'height'),
+ ('2014', 'weight')])
+ df = DataFrame(np.random.randn(3, 10), index=cols)
+ with ensure_clean(ext) as path:
+ df.to_excel(path, index=False)
+
+ def test_to_excel_styleconverter(self, ext):
+ import xlwt
+
+ hstyle = {"font": {"bold": True},
+ "borders": {"top": "thin",
+ "right": "thin",
+ "bottom": "thin",
+ "left": "thin"},
+ "alignment": {"horizontal": "center", "vertical": "top"}}
+
+ xls_style = _XlwtWriter._convert_to_style(hstyle)
+ assert xls_style.font.bold
+ assert xlwt.Borders.THIN == xls_style.borders.top
+ assert xlwt.Borders.THIN == xls_style.borders.right
+ assert xlwt.Borders.THIN == xls_style.borders.bottom
+ assert xlwt.Borders.THIN == xls_style.borders.left
+ assert xlwt.Alignment.HORZ_CENTER == xls_style.alignment.horz
+ assert xlwt.Alignment.VERT_TOP == xls_style.alignment.vert
+
+ def test_write_append_mode_raises(self, ext):
+ msg = "Append mode is not supported with xlwt!"
+
+ with ensure_clean(ext) as f:
+ with pytest.raises(ValueError, match=msg):
+ ExcelWriter(f, engine='xlwt', mode='a')
diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py
deleted file mode 100644
index 1f6839fa5dc52..0000000000000
--- a/pandas/tests/io/test_excel.py
+++ /dev/null
@@ -1,2512 +0,0 @@
-from collections import OrderedDict
-import contextlib
-from datetime import date, datetime, time, timedelta
-from distutils.version import LooseVersion
-from functools import partial
-from io import BytesIO
-import os
-import warnings
-
-import numpy as np
-from numpy import nan
-import pytest
-
-from pandas.compat import PY36
-import pandas.util._test_decorators as td
-
-import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, get_option, set_option
-import pandas.util.testing as tm
-from pandas.util.testing import ensure_clean, makeCustomDataframe as mkdf
-
-from pandas.io.common import URLError
-from pandas.io.excel import (
- ExcelFile, ExcelWriter, _OpenpyxlWriter, _XlsxWriter, _XlwtWriter,
- register_writer)
-from pandas.io.formats.excel import ExcelFormatter
-from pandas.io.parsers import read_csv
-
-
-@pytest.fixture
-def frame(float_frame):
- return float_frame[:10]
-
-
-@pytest.fixture
-def tsframe():
- return tm.makeTimeDataFrame()[:5]
-
-
-@pytest.fixture(params=[True, False])
-def merge_cells(request):
- return request.param
-
-
-@contextlib.contextmanager
-def ignore_xlrd_time_clock_warning():
- """
- Context manager to ignore warnings raised by the xlrd library,
- regarding the deprecation of `time.clock` in Python 3.7.
- """
- with warnings.catch_warnings():
- warnings.filterwarnings(
- action='ignore',
- message='time.clock has been deprecated',
- category=DeprecationWarning)
- yield
-
-
-@pytest.fixture
-def df_ref():
- """
- Obtain the reference data from read_csv with the Python engine.
- """
- df_ref = read_csv('test1.csv', index_col=0,
- parse_dates=True, engine='python')
- return df_ref
-
-
-@pytest.fixture(params=['.xls', '.xlsx', '.xlsm'])
-def read_ext(request):
- """
- Valid extensions for reading Excel files.
- """
- return request.param
-
-
-class TestReaders:
-
- @pytest.fixture(autouse=True, params=[
- # Add any engines to test here
- pytest.param('xlrd', marks=pytest.mark.skipif(
- not td.safe_import("xlrd"), reason="no xlrd")),
- pytest.param(None, marks=pytest.mark.skipif(
- not td.safe_import("xlrd"), reason="no xlrd")),
- ])
- def cd_and_set_engine(self, request, datapath, monkeypatch):
- """
- Change directory and set engine for read_excel calls.
- """
- func = partial(pd.read_excel, engine=request.param)
- monkeypatch.chdir(datapath("io", "data"))
- monkeypatch.setattr(pd, 'read_excel', func)
-
- def test_usecols_int(self, read_ext, df_ref):
- df_ref = df_ref.reindex(columns=["A", "B", "C"])
-
- # usecols as int
- with tm.assert_produces_warning(FutureWarning,
- check_stacklevel=False):
- with ignore_xlrd_time_clock_warning():
- df1 = pd.read_excel("test1" + read_ext, "Sheet1",
- index_col=0, usecols=3)
-
- # usecols as int
- with tm.assert_produces_warning(FutureWarning,
- check_stacklevel=False):
- with ignore_xlrd_time_clock_warning():
- df2 = pd.read_excel("test1" + read_ext, "Sheet2", skiprows=[1],
- index_col=0, usecols=3)
-
- # TODO add index to xls file)
- tm.assert_frame_equal(df1, df_ref, check_names=False)
- tm.assert_frame_equal(df2, df_ref, check_names=False)
-
- def test_usecols_list(self, read_ext, df_ref):
-
- df_ref = df_ref.reindex(columns=['B', 'C'])
- df1 = pd.read_excel('test1' + read_ext, 'Sheet1', index_col=0,
- usecols=[0, 2, 3])
- df2 = pd.read_excel('test1' + read_ext, 'Sheet2', skiprows=[1],
- index_col=0, usecols=[0, 2, 3])
-
- # TODO add index to xls file)
- tm.assert_frame_equal(df1, df_ref, check_names=False)
- tm.assert_frame_equal(df2, df_ref, check_names=False)
-
- def test_usecols_str(self, read_ext, df_ref):
-
- df1 = df_ref.reindex(columns=['A', 'B', 'C'])
- df2 = pd.read_excel('test1' + read_ext, 'Sheet1', index_col=0,
- usecols='A:D')
- df3 = pd.read_excel('test1' + read_ext, 'Sheet2', skiprows=[1],
- index_col=0, usecols='A:D')
-
- # TODO add index to xls, read xls ignores index name ?
- tm.assert_frame_equal(df2, df1, check_names=False)
- tm.assert_frame_equal(df3, df1, check_names=False)
-
- df1 = df_ref.reindex(columns=['B', 'C'])
- df2 = pd.read_excel('test1' + read_ext, 'Sheet1', index_col=0,
- usecols='A,C,D')
- df3 = pd.read_excel('test1' + read_ext, 'Sheet2', skiprows=[1],
- index_col=0, usecols='A,C,D')
- # TODO add index to xls file
- tm.assert_frame_equal(df2, df1, check_names=False)
- tm.assert_frame_equal(df3, df1, check_names=False)
-
- df1 = df_ref.reindex(columns=['B', 'C'])
- df2 = pd.read_excel('test1' + read_ext, 'Sheet1', index_col=0,
- usecols='A,C:D')
- df3 = pd.read_excel('test1' + read_ext, 'Sheet2', skiprows=[1],
- index_col=0, usecols='A,C:D')
- tm.assert_frame_equal(df2, df1, check_names=False)
- tm.assert_frame_equal(df3, df1, check_names=False)
-
- @pytest.mark.parametrize("usecols", [
- [0, 1, 3], [0, 3, 1],
- [1, 0, 3], [1, 3, 0],
- [3, 0, 1], [3, 1, 0],
- ])
- def test_usecols_diff_positional_int_columns_order(
- self, read_ext, usecols, df_ref):
- expected = df_ref[["A", "C"]]
- result = pd.read_excel("test1" + read_ext, "Sheet1",
- index_col=0, usecols=usecols)
- tm.assert_frame_equal(result, expected, check_names=False)
-
- @pytest.mark.parametrize("usecols", [
- ["B", "D"], ["D", "B"]
- ])
- def test_usecols_diff_positional_str_columns_order(
- self, read_ext, usecols, df_ref):
- expected = df_ref[["B", "D"]]
- expected.index = range(len(expected))
-
- result = pd.read_excel("test1" + read_ext, "Sheet1", usecols=usecols)
- tm.assert_frame_equal(result, expected, check_names=False)
-
- def test_read_excel_without_slicing(self, read_ext, df_ref):
- expected = df_ref
- result = pd.read_excel("test1" + read_ext, "Sheet1", index_col=0)
- tm.assert_frame_equal(result, expected, check_names=False)
-
- def test_usecols_excel_range_str(self, read_ext, df_ref):
- expected = df_ref[["C", "D"]]
- result = pd.read_excel("test1" + read_ext, "Sheet1",
- index_col=0, usecols="A,D:E")
- tm.assert_frame_equal(result, expected, check_names=False)
-
- def test_usecols_excel_range_str_invalid(self, read_ext):
- msg = "Invalid column name: E1"
-
- with pytest.raises(ValueError, match=msg):
- pd.read_excel("test1" + read_ext, "Sheet1", usecols="D:E1")
-
- def test_index_col_label_error(self, read_ext):
- msg = "list indices must be integers.*, not str"
-
- with pytest.raises(TypeError, match=msg):
- pd.read_excel("test1" + read_ext, "Sheet1", index_col=["A"],
- usecols=["A", "C"])
-
- def test_index_col_empty(self, read_ext):
- # see gh-9208
- result = pd.read_excel("test1" + read_ext, "Sheet3",
- index_col=["A", "B", "C"])
- expected = DataFrame(columns=["D", "E", "F"],
- index=MultiIndex(levels=[[]] * 3,
- codes=[[]] * 3,
- names=["A", "B", "C"]))
- tm.assert_frame_equal(result, expected)
-
- @pytest.mark.parametrize("index_col", [None, 2])
- def test_index_col_with_unnamed(self, read_ext, index_col):
- # see gh-18792
- result = pd.read_excel(
- "test1" + read_ext, "Sheet4", index_col=index_col)
- expected = DataFrame([["i1", "a", "x"], ["i2", "b", "y"]],
- columns=["Unnamed: 0", "col1", "col2"])
- if index_col:
- expected = expected.set_index(expected.columns[index_col])
-
- tm.assert_frame_equal(result, expected)
-
- def test_usecols_pass_non_existent_column(self, read_ext):
- msg = ("Usecols do not match columns, "
- "columns expected but not found: " + r"\['E'\]")
-
- with pytest.raises(ValueError, match=msg):
- pd.read_excel("test1" + read_ext, usecols=["E"])
-
- def test_usecols_wrong_type(self, read_ext):
- msg = ("'usecols' must either be list-like of "
- "all strings, all unicode, all integers or a callable.")
-
- with pytest.raises(ValueError, match=msg):
- pd.read_excel("test1" + read_ext, usecols=["E1", 0])
-
- def test_excel_stop_iterator(self, read_ext):
-
- parsed = pd.read_excel('test2' + read_ext, 'Sheet1')
- expected = DataFrame([['aaaa', 'bbbbb']], columns=['Test', 'Test1'])
- tm.assert_frame_equal(parsed, expected)
-
- def test_excel_cell_error_na(self, read_ext):
-
- parsed = pd.read_excel('test3' + read_ext, 'Sheet1')
- expected = DataFrame([[np.nan]], columns=['Test'])
- tm.assert_frame_equal(parsed, expected)
-
- def test_excel_table(self, read_ext, df_ref):
-
- df1 = pd.read_excel('test1' + read_ext, 'Sheet1', index_col=0)
- df2 = pd.read_excel('test1' + read_ext, 'Sheet2', skiprows=[1],
- index_col=0)
- # TODO add index to file
- tm.assert_frame_equal(df1, df_ref, check_names=False)
- tm.assert_frame_equal(df2, df_ref, check_names=False)
-
- df3 = pd.read_excel(
- 'test1' + read_ext, 'Sheet1', index_col=0, skipfooter=1)
- tm.assert_frame_equal(df3, df1.iloc[:-1])
-
- def test_reader_special_dtypes(self, read_ext):
-
- expected = DataFrame.from_dict(OrderedDict([
- ("IntCol", [1, 2, -3, 4, 0]),
- ("FloatCol", [1.25, 2.25, 1.83, 1.92, 0.0000000005]),
- ("BoolCol", [True, False, True, True, False]),
- ("StrCol", [1, 2, 3, 4, 5]),
- # GH5394 - this is why convert_float isn't vectorized
- ("Str2Col", ["a", 3, "c", "d", "e"]),
- ("DateCol", [datetime(2013, 10, 30), datetime(2013, 10, 31),
- datetime(1905, 1, 1), datetime(2013, 12, 14),
- datetime(2015, 3, 14)])
- ]))
- basename = 'test_types'
-
- # should read in correctly and infer types
- actual = pd.read_excel(basename + read_ext, 'Sheet1')
- tm.assert_frame_equal(actual, expected)
-
- # if not coercing number, then int comes in as float
- float_expected = expected.copy()
- float_expected["IntCol"] = float_expected["IntCol"].astype(float)
- float_expected.loc[float_expected.index[1], "Str2Col"] = 3.0
- actual = pd.read_excel(
- basename + read_ext, 'Sheet1', convert_float=False)
- tm.assert_frame_equal(actual, float_expected)
-
- # check setting Index (assuming xls and xlsx are the same here)
- for icol, name in enumerate(expected.columns):
- actual = pd.read_excel(
- basename + read_ext, 'Sheet1', index_col=icol)
- exp = expected.set_index(name)
- tm.assert_frame_equal(actual, exp)
-
- # convert_float and converters should be different but both accepted
- expected["StrCol"] = expected["StrCol"].apply(str)
- actual = pd.read_excel(basename + read_ext, 'Sheet1',
- converters={"StrCol": str})
- tm.assert_frame_equal(actual, expected)
-
- no_convert_float = float_expected.copy()
- no_convert_float["StrCol"] = no_convert_float["StrCol"].apply(str)
- actual = pd.read_excel(
- basename + read_ext, 'Sheet1',
- convert_float=False, converters={"StrCol": str})
- tm.assert_frame_equal(actual, no_convert_float)
-
- # GH8212 - support for converters and missing values
- def test_reader_converters(self, read_ext):
-
- basename = 'test_converters'
-
- expected = DataFrame.from_dict(OrderedDict([
- ("IntCol", [1, 2, -3, -1000, 0]),
- ("FloatCol", [12.5, np.nan, 18.3, 19.2, 0.000000005]),
- ("BoolCol", ['Found', 'Found', 'Found', 'Not found', 'Found']),
- ("StrCol", ['1', np.nan, '3', '4', '5']),
- ]))
-
- converters = {'IntCol': lambda x: int(x) if x != '' else -1000,
- 'FloatCol': lambda x: 10 * x if x else np.nan,
- 2: lambda x: 'Found' if x != '' else 'Not found',
- 3: lambda x: str(x) if x else '',
- }
-
- # should read in correctly and set types of single cells (not array
- # dtypes)
- actual = pd.read_excel(
- basename + read_ext, 'Sheet1', converters=converters)
- tm.assert_frame_equal(actual, expected)
-
- def test_reader_dtype(self, read_ext):
- # GH 8212
- basename = 'testdtype'
- actual = pd.read_excel(basename + read_ext)
-
- expected = DataFrame({
- 'a': [1, 2, 3, 4],
- 'b': [2.5, 3.5, 4.5, 5.5],
- 'c': [1, 2, 3, 4],
- 'd': [1.0, 2.0, np.nan, 4.0]}).reindex(
- columns=['a', 'b', 'c', 'd'])
-
- tm.assert_frame_equal(actual, expected)
-
- actual = pd.read_excel(basename + read_ext,
- dtype={'a': 'float64',
- 'b': 'float32',
- 'c': str})
-
- expected['a'] = expected['a'].astype('float64')
- expected['b'] = expected['b'].astype('float32')
- expected['c'] = ['001', '002', '003', '004']
- tm.assert_frame_equal(actual, expected)
-
- with pytest.raises(ValueError):
- pd.read_excel(basename + read_ext, dtype={'d': 'int64'})
-
- @pytest.mark.parametrize("dtype,expected", [
- (None,
- DataFrame({
- "a": [1, 2, 3, 4],
- "b": [2.5, 3.5, 4.5, 5.5],
- "c": [1, 2, 3, 4],
- "d": [1.0, 2.0, np.nan, 4.0]
- })),
- ({"a": "float64",
- "b": "float32",
- "c": str,
- "d": str
- },
- DataFrame({
- "a": Series([1, 2, 3, 4], dtype="float64"),
- "b": Series([2.5, 3.5, 4.5, 5.5], dtype="float32"),
- "c": ["001", "002", "003", "004"],
- "d": ["1", "2", np.nan, "4"]
- })),
- ])
- def test_reader_dtype_str(self, read_ext, dtype, expected):
- # see gh-20377
- basename = "testdtype"
-
- actual = pd.read_excel(basename + read_ext, dtype=dtype)
- tm.assert_frame_equal(actual, expected)
-
- def test_reading_all_sheets(self, read_ext):
- # Test reading all sheetnames by setting sheetname to None,
- # Ensure a dict is returned.
- # See PR #9450
- basename = 'test_multisheet'
- dfs = pd.read_excel(basename + read_ext, sheet_name=None)
- # ensure this is not alphabetical to test order preservation
- expected_keys = ['Charlie', 'Alpha', 'Beta']
- tm.assert_contains_all(expected_keys, dfs.keys())
- # Issue 9930
- # Ensure sheet order is preserved
- assert expected_keys == list(dfs.keys())
-
- def test_reading_multiple_specific_sheets(self, read_ext):
- # Test reading specific sheetnames by specifying a mixed list
- # of integers and strings, and confirm that duplicated sheet
- # references (positions/names) are removed properly.
- # Ensure a dict is returned
- # See PR #9450
- basename = 'test_multisheet'
- # Explicitly request duplicates. Only the set should be returned.
- expected_keys = [2, 'Charlie', 'Charlie']
- dfs = pd.read_excel(basename + read_ext, sheet_name=expected_keys)
- expected_keys = list(set(expected_keys))
- tm.assert_contains_all(expected_keys, dfs.keys())
- assert len(expected_keys) == len(dfs.keys())
-
- def test_reading_all_sheets_with_blank(self, read_ext):
- # Test reading all sheetnames by setting sheetname to None,
- # In the case where some sheets are blank.
- # Issue #11711
- basename = 'blank_with_header'
- dfs = pd.read_excel(basename + read_ext, sheet_name=None)
- expected_keys = ['Sheet1', 'Sheet2', 'Sheet3']
- tm.assert_contains_all(expected_keys, dfs.keys())
-
- # GH6403
- def test_read_excel_blank(self, read_ext):
- actual = pd.read_excel('blank' + read_ext, 'Sheet1')
- tm.assert_frame_equal(actual, DataFrame())
-
- def test_read_excel_blank_with_header(self, read_ext):
- expected = DataFrame(columns=['col_1', 'col_2'])
- actual = pd.read_excel('blank_with_header' + read_ext, 'Sheet1')
- tm.assert_frame_equal(actual, expected)
-
- def test_date_conversion_overflow(self, read_ext):
- # GH 10001 : pandas.ExcelFile ignore parse_dates=False
- expected = pd.DataFrame([[pd.Timestamp('2016-03-12'), 'Marc Johnson'],
- [pd.Timestamp('2016-03-16'), 'Jack Black'],
- [1e+20, 'Timothy Brown']],
- columns=['DateColWithBigInt', 'StringCol'])
-
- result = pd.read_excel('testdateoverflow' + read_ext)
- tm.assert_frame_equal(result, expected)
-
- def test_sheet_name(self, read_ext, df_ref):
- filename = "test1"
- sheet_name = "Sheet1"
-
- df1 = pd.read_excel(filename + read_ext,
- sheet_name=sheet_name, index_col=0) # doc
- with ignore_xlrd_time_clock_warning():
- df2 = pd.read_excel(filename + read_ext, index_col=0,
- sheet_name=sheet_name)
-
- tm.assert_frame_equal(df1, df_ref, check_names=False)
- tm.assert_frame_equal(df2, df_ref, check_names=False)
-
- def test_excel_read_buffer(self, read_ext):
-
- pth = 'test1' + read_ext
- expected = pd.read_excel(pth, 'Sheet1', index_col=0)
- with open(pth, 'rb') as f:
- actual = pd.read_excel(f, 'Sheet1', index_col=0)
- tm.assert_frame_equal(expected, actual)
-
- def test_bad_engine_raises(self, read_ext):
- bad_engine = 'foo'
- with pytest.raises(ValueError, match="Unknown engine: foo"):
- pd.read_excel('', engine=bad_engine)
-
- @tm.network
- def test_read_from_http_url(self, read_ext):
- url = ('https://raw.github.com/pandas-dev/pandas/master/'
- 'pandas/tests/io/data/test1' + read_ext)
- url_table = pd.read_excel(url)
- local_table = pd.read_excel('test1' + read_ext)
- tm.assert_frame_equal(url_table, local_table)
-
- @td.skip_if_not_us_locale
- def test_read_from_s3_url(self, read_ext, s3_resource):
- # Bucket "pandas-test" created in tests/io/conftest.py
- with open('test1' + read_ext, "rb") as f:
- s3_resource.Bucket("pandas-test").put_object(
- Key="test1" + read_ext, Body=f)
-
- url = ('s3://pandas-test/test1' + read_ext)
- url_table = pd.read_excel(url)
- local_table = pd.read_excel('test1' + read_ext)
- tm.assert_frame_equal(url_table, local_table)
-
- @pytest.mark.slow
- # ignore warning from old xlrd
- @pytest.mark.filterwarnings("ignore:This metho:PendingDeprecationWarning")
- def test_read_from_file_url(self, read_ext, datapath):
-
- # FILE
- localtable = os.path.join(datapath("io", "data"), 'test1' + read_ext)
- local_table = pd.read_excel(localtable)
-
- try:
- url_table = pd.read_excel('file://localhost/' + localtable)
- except URLError:
- # fails on some systems
- import platform
- pytest.skip("failing on %s" %
- ' '.join(platform.uname()).strip())
-
- tm.assert_frame_equal(url_table, local_table)
-
- def test_read_from_pathlib_path(self, read_ext):
-
- # GH12655
- from pathlib import Path
-
- str_path = 'test1' + read_ext
- expected = pd.read_excel(str_path, 'Sheet1', index_col=0)
-
- path_obj = Path('test1' + read_ext)
- actual = pd.read_excel(path_obj, 'Sheet1', index_col=0)
-
- tm.assert_frame_equal(expected, actual)
-
- @td.skip_if_no('py.path')
- def test_read_from_py_localpath(self, read_ext):
-
- # GH12655
- from py.path import local as LocalPath
-
- str_path = os.path.join('test1' + read_ext)
- expected = pd.read_excel(str_path, 'Sheet1', index_col=0)
-
- path_obj = LocalPath().join('test1' + read_ext)
- actual = pd.read_excel(path_obj, 'Sheet1', index_col=0)
-
- tm.assert_frame_equal(expected, actual)
-
- def test_reader_seconds(self, read_ext):
-
- # Test reading times with and without milliseconds. GH5945.
- expected = DataFrame.from_dict({"Time": [time(1, 2, 3),
- time(2, 45, 56, 100000),
- time(4, 29, 49, 200000),
- time(6, 13, 42, 300000),
- time(7, 57, 35, 400000),
- time(9, 41, 28, 500000),
- time(11, 25, 21, 600000),
- time(13, 9, 14, 700000),
- time(14, 53, 7, 800000),
- time(16, 37, 0, 900000),
- time(18, 20, 54)]})
-
- actual = pd.read_excel('times_1900' + read_ext, 'Sheet1')
- tm.assert_frame_equal(actual, expected)
-
- actual = pd.read_excel('times_1904' + read_ext, 'Sheet1')
- tm.assert_frame_equal(actual, expected)
-
- def test_read_excel_multiindex(self, read_ext):
- # see gh-4679
- mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]])
- mi_file = "testmultiindex" + read_ext
-
- # "mi_column" sheet
- 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)
-
- actual = pd.read_excel(
- mi_file, "mi_column", header=[0, 1], index_col=0)
- tm.assert_frame_equal(actual, expected)
-
- # "mi_index" sheet
- expected.index = mi
- expected.columns = ["a", "b", "c", "d"]
-
- actual = pd.read_excel(mi_file, "mi_index", index_col=[0, 1])
- tm.assert_frame_equal(actual, expected, check_names=False)
-
- # "both" sheet
- expected.columns = mi
-
- actual = pd.read_excel(
- mi_file, "both", index_col=[0, 1], header=[0, 1])
- tm.assert_frame_equal(actual, expected, check_names=False)
-
- # "mi_index_name" sheet
- expected.columns = ["a", "b", "c", "d"]
- expected.index = mi.set_names(["ilvl1", "ilvl2"])
-
- actual = pd.read_excel(
- mi_file, "mi_index_name", index_col=[0, 1])
- tm.assert_frame_equal(actual, expected)
-
- # "mi_column_name" sheet
- expected.index = list(range(4))
- expected.columns = mi.set_names(["c1", "c2"])
- actual = pd.read_excel(mi_file, "mi_column_name",
- header=[0, 1], index_col=0)
- tm.assert_frame_equal(actual, expected)
-
- # see gh-11317
- # "name_with_int" sheet
- expected.columns = mi.set_levels(
- [1, 2], level=1).set_names(["c1", "c2"])
-
- actual = pd.read_excel(mi_file, "name_with_int",
- index_col=0, header=[0, 1])
- tm.assert_frame_equal(actual, expected)
-
- # "both_name" sheet
- expected.columns = mi.set_names(["c1", "c2"])
- expected.index = mi.set_names(["ilvl1", "ilvl2"])
-
- actual = pd.read_excel(mi_file, "both_name",
- index_col=[0, 1], header=[0, 1])
- tm.assert_frame_equal(actual, expected)
-
- # "both_skiprows" sheet
- actual = pd.read_excel(mi_file, "both_name_skiprows", index_col=[0, 1],
- header=[0, 1], skiprows=2)
- tm.assert_frame_equal(actual, expected)
-
- def test_read_excel_multiindex_header_only(self, read_ext):
- # see gh-11733.
- #
- # Don't try to parse a header name if there isn't one.
- mi_file = "testmultiindex" + read_ext
- result = pd.read_excel(mi_file, "index_col_none", header=[0, 1])
-
- exp_columns = MultiIndex.from_product([("A", "B"), ("key", "val")])
- expected = DataFrame([[1, 2, 3, 4]] * 2, columns=exp_columns)
- tm.assert_frame_equal(result, expected)
-
- def test_excel_old_index_format(self, read_ext):
- # see gh-4679
- filename = "test_index_name_pre17" + read_ext
-
- # We detect headers to determine if index names exist, so
- # that "index" name in the "names" version of the data will
- # now be interpreted as rows that include null data.
- data = np.array([[None, None, None, None, None],
- ["R0C0", "R0C1", "R0C2", "R0C3", "R0C4"],
- ["R1C0", "R1C1", "R1C2", "R1C3", "R1C4"],
- ["R2C0", "R2C1", "R2C2", "R2C3", "R2C4"],
- ["R3C0", "R3C1", "R3C2", "R3C3", "R3C4"],
- ["R4C0", "R4C1", "R4C2", "R4C3", "R4C4"]])
- columns = ["C_l0_g0", "C_l0_g1", "C_l0_g2", "C_l0_g3", "C_l0_g4"]
- mi = MultiIndex(levels=[["R0", "R_l0_g0", "R_l0_g1",
- "R_l0_g2", "R_l0_g3", "R_l0_g4"],
- ["R1", "R_l1_g0", "R_l1_g1",
- "R_l1_g2", "R_l1_g3", "R_l1_g4"]],
- codes=[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]],
- names=[None, None])
- si = Index(["R0", "R_l0_g0", "R_l0_g1", "R_l0_g2",
- "R_l0_g3", "R_l0_g4"], name=None)
-
- expected = pd.DataFrame(data, index=si, columns=columns)
-
- actual = pd.read_excel(filename, "single_names", index_col=0)
- tm.assert_frame_equal(actual, expected)
-
- expected.index = mi
-
- actual = pd.read_excel(filename, "multi_names", index_col=[0, 1])
- tm.assert_frame_equal(actual, expected)
-
- # The analogous versions of the "names" version data
- # where there are explicitly no names for the indices.
- data = np.array([["R0C0", "R0C1", "R0C2", "R0C3", "R0C4"],
- ["R1C0", "R1C1", "R1C2", "R1C3", "R1C4"],
- ["R2C0", "R2C1", "R2C2", "R2C3", "R2C4"],
- ["R3C0", "R3C1", "R3C2", "R3C3", "R3C4"],
- ["R4C0", "R4C1", "R4C2", "R4C3", "R4C4"]])
- columns = ["C_l0_g0", "C_l0_g1", "C_l0_g2", "C_l0_g3", "C_l0_g4"]
- mi = MultiIndex(levels=[["R_l0_g0", "R_l0_g1", "R_l0_g2",
- "R_l0_g3", "R_l0_g4"],
- ["R_l1_g0", "R_l1_g1", "R_l1_g2",
- "R_l1_g3", "R_l1_g4"]],
- codes=[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]],
- names=[None, None])
- si = Index(["R_l0_g0", "R_l0_g1", "R_l0_g2",
- "R_l0_g3", "R_l0_g4"], name=None)
-
- expected = pd.DataFrame(data, index=si, columns=columns)
-
- actual = pd.read_excel(filename, "single_no_names", index_col=0)
- tm.assert_frame_equal(actual, expected)
-
- expected.index = mi
-
- actual = pd.read_excel(filename, "multi_no_names", index_col=[0, 1])
- tm.assert_frame_equal(actual, expected, check_names=False)
-
- def test_read_excel_bool_header_arg(self, read_ext):
- # GH 6114
- for arg in [True, False]:
- with pytest.raises(TypeError):
- pd.read_excel('test1' + read_ext, header=arg)
-
- def test_read_excel_chunksize(self, read_ext):
- # GH 8011
- with pytest.raises(NotImplementedError):
- pd.read_excel('test1' + read_ext, chunksize=100)
-
- def test_read_excel_skiprows_list(self, read_ext):
- # GH 4903
- actual = pd.read_excel('testskiprows' + read_ext,
- 'skiprows_list', skiprows=[0, 2])
- 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=['a', 'b', 'c', 'd'])
- tm.assert_frame_equal(actual, expected)
-
- actual = pd.read_excel('testskiprows' + read_ext,
- 'skiprows_list', skiprows=np.array([0, 2]))
- tm.assert_frame_equal(actual, expected)
-
- def test_read_excel_nrows(self, read_ext):
- # GH 16645
- num_rows_to_pull = 5
- actual = pd.read_excel('test1' + read_ext, nrows=num_rows_to_pull)
- expected = pd.read_excel('test1' + read_ext)
- expected = expected[:num_rows_to_pull]
- tm.assert_frame_equal(actual, expected)
-
- def test_read_excel_nrows_greater_than_nrows_in_file(self, read_ext):
- # GH 16645
- expected = pd.read_excel('test1' + read_ext)
- num_records_in_file = len(expected)
- num_rows_to_pull = num_records_in_file + 10
- actual = pd.read_excel('test1' + read_ext, nrows=num_rows_to_pull)
- tm.assert_frame_equal(actual, expected)
-
- def test_read_excel_nrows_non_integer_parameter(self, read_ext):
- # GH 16645
- msg = "'nrows' must be an integer >=0"
- with pytest.raises(ValueError, match=msg):
- pd.read_excel('test1' + read_ext, nrows='5')
-
- def test_read_excel_squeeze(self, read_ext):
- # GH 12157
- f = 'test_squeeze' + read_ext
-
- actual = pd.read_excel(f, 'two_columns', index_col=0, squeeze=True)
- expected = pd.Series([2, 3, 4], [4, 5, 6], name='b')
- expected.index.name = 'a'
- tm.assert_series_equal(actual, expected)
-
- actual = pd.read_excel(f, 'two_columns', squeeze=True)
- expected = pd.DataFrame({'a': [4, 5, 6],
- 'b': [2, 3, 4]})
- tm.assert_frame_equal(actual, expected)
-
- actual = pd.read_excel(f, 'one_column', squeeze=True)
- expected = pd.Series([1, 2, 3], name='a')
- tm.assert_series_equal(actual, expected)
-
-
-class TestExcelFileRead:
-
- @pytest.fixture(autouse=True, params=[
- # Add any engines to test here
- pytest.param('xlrd', marks=pytest.mark.skipif(
- not td.safe_import("xlrd"), reason="no xlrd")),
- pytest.param(None, marks=pytest.mark.skipif(
- not td.safe_import("xlrd"), reason="no xlrd")),
- ])
- def cd_and_set_engine(self, request, datapath, monkeypatch):
- """
- Change directory and set engine for ExcelFile objects.
- """
- func = partial(pd.ExcelFile, engine=request.param)
- monkeypatch.chdir(datapath("io", "data"))
- monkeypatch.setattr(pd, 'ExcelFile', func)
-
- def test_excel_passes_na(self, read_ext):
-
- excel = ExcelFile('test4' + read_ext)
-
- parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=False,
- na_values=['apple'])
- expected = DataFrame([['NA'], [1], ['NA'], [np.nan], ['rabbit']],
- columns=['Test'])
- tm.assert_frame_equal(parsed, expected)
-
- parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=True,
- na_values=['apple'])
- expected = DataFrame([[np.nan], [1], [np.nan], [np.nan], ['rabbit']],
- columns=['Test'])
- tm.assert_frame_equal(parsed, expected)
-
- # 13967
- excel = ExcelFile('test5' + read_ext)
-
- parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=False,
- na_values=['apple'])
- expected = DataFrame([['1.#QNAN'], [1], ['nan'], [np.nan], ['rabbit']],
- columns=['Test'])
- tm.assert_frame_equal(parsed, expected)
-
- parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=True,
- na_values=['apple'])
- expected = DataFrame([[np.nan], [1], [np.nan], [np.nan], ['rabbit']],
- columns=['Test'])
- tm.assert_frame_equal(parsed, expected)
-
- @pytest.mark.parametrize('arg', ['sheet', 'sheetname', 'parse_cols'])
- def test_unexpected_kwargs_raises(self, read_ext, arg):
- # gh-17964
- excel = ExcelFile('test1' + read_ext)
-
- kwarg = {arg: 'Sheet1'}
- msg = "unexpected keyword argument `{}`".format(arg)
- with pytest.raises(TypeError, match=msg):
- pd.read_excel(excel, **kwarg)
-
- def test_excel_table_sheet_by_index(self, read_ext, df_ref):
-
- excel = ExcelFile('test1' + read_ext)
-
- df1 = pd.read_excel(excel, 0, index_col=0)
- df2 = pd.read_excel(excel, 1, skiprows=[1], index_col=0)
- tm.assert_frame_equal(df1, df_ref, check_names=False)
- tm.assert_frame_equal(df2, df_ref, check_names=False)
-
- df1 = excel.parse(0, index_col=0)
- df2 = excel.parse(1, skiprows=[1], index_col=0)
- tm.assert_frame_equal(df1, df_ref, check_names=False)
- tm.assert_frame_equal(df2, df_ref, check_names=False)
-
- df3 = pd.read_excel(excel, 0, index_col=0, skipfooter=1)
- tm.assert_frame_equal(df3, df1.iloc[:-1])
-
- with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
- df4 = pd.read_excel(excel, 0, index_col=0, skip_footer=1)
- tm.assert_frame_equal(df3, df4)
-
- df3 = excel.parse(0, index_col=0, skipfooter=1)
- tm.assert_frame_equal(df3, df1.iloc[:-1])
-
- import xlrd # will move to engine-specific tests as new ones are added
- with pytest.raises(xlrd.XLRDError):
- pd.read_excel(excel, 'asdf')
-
- def test_sheet_name(self, read_ext, df_ref):
- filename = "test1"
- sheet_name = "Sheet1"
-
- excel = ExcelFile(filename + read_ext)
- df1_parse = excel.parse(sheet_name=sheet_name, index_col=0) # doc
- df2_parse = excel.parse(index_col=0,
- sheet_name=sheet_name)
-
- tm.assert_frame_equal(df1_parse, df_ref, check_names=False)
- tm.assert_frame_equal(df2_parse, df_ref, check_names=False)
-
- def test_excel_read_buffer(self, read_ext):
-
- pth = 'test1' + read_ext
- expected = pd.read_excel(pth, 'Sheet1', index_col=0)
-
- with open(pth, 'rb') as f:
- xls = ExcelFile(f)
- actual = pd.read_excel(xls, 'Sheet1', index_col=0)
- tm.assert_frame_equal(expected, actual)
-
- def test_reader_closes_file(self, read_ext):
-
- f = open('test1' + read_ext, 'rb')
- with ExcelFile(f) as xlsx:
- # parses okay
- pd.read_excel(xlsx, 'Sheet1', index_col=0)
-
- assert f.closed
-
-
-@td.skip_if_no('xlrd')
-@pytest.mark.parametrize("ext", ['.xls', '.xlsx', '.xlsm'])
-class TestRoundTrip:
-
- @td.skip_if_no("xlwt")
- @td.skip_if_no("openpyxl")
- @pytest.mark.parametrize("header,expected", [
- (None, DataFrame([np.nan] * 4)),
- (0, DataFrame({"Unnamed: 0": [np.nan] * 3}))
- ])
- def test_read_one_empty_col_no_header(self, ext, header, expected):
- # xref gh-12292
- filename = "no_header"
- df = pd.DataFrame(
- [["", 1, 100],
- ["", 2, 200],
- ["", 3, 300],
- ["", 4, 400]]
- )
-
- with ensure_clean(ext) as path:
- df.to_excel(path, filename, index=False, header=False)
- result = pd.read_excel(path, filename, usecols=[0], header=header)
-
- tm.assert_frame_equal(result, expected)
-
- @td.skip_if_no("xlwt")
- @td.skip_if_no("openpyxl")
- @pytest.mark.parametrize("header,expected", [
- (None, DataFrame([0] + [np.nan] * 4)),
- (0, DataFrame([np.nan] * 4))
- ])
- def test_read_one_empty_col_with_header(self, ext, header, expected):
- filename = "with_header"
- df = pd.DataFrame(
- [["", 1, 100],
- ["", 2, 200],
- ["", 3, 300],
- ["", 4, 400]]
- )
-
- with ensure_clean(ext) as path:
- df.to_excel(path, 'with_header', index=False, header=True)
- result = pd.read_excel(path, filename, usecols=[0], header=header)
-
- tm.assert_frame_equal(result, expected)
-
- @td.skip_if_no('openpyxl')
- @td.skip_if_no('xlwt')
- def test_set_column_names_in_parameter(self, ext):
- # GH 12870 : pass down column names associated with
- # keyword argument names
- refdf = pd.DataFrame([[1, 'foo'], [2, 'bar'],
- [3, 'baz']], columns=['a', 'b'])
-
- with ensure_clean(ext) as pth:
- with ExcelWriter(pth) as writer:
- refdf.to_excel(writer, 'Data_no_head',
- header=False, index=False)
- refdf.to_excel(writer, 'Data_with_head', index=False)
-
- refdf.columns = ['A', 'B']
-
- with ExcelFile(pth) as reader:
- xlsdf_no_head = pd.read_excel(reader, 'Data_no_head',
- header=None, names=['A', 'B'])
- xlsdf_with_head = pd.read_excel(
- reader, 'Data_with_head', index_col=None, names=['A', 'B'])
-
- tm.assert_frame_equal(xlsdf_no_head, refdf)
- tm.assert_frame_equal(xlsdf_with_head, refdf)
-
- @td.skip_if_no("xlwt")
- @td.skip_if_no("openpyxl")
- def test_creating_and_reading_multiple_sheets(self, ext):
- # see gh-9450
- #
- # Test reading multiple sheets, from a runtime
- # created Excel file with multiple sheets.
- def tdf(col_sheet_name):
- d, i = [11, 22, 33], [1, 2, 3]
- return DataFrame(d, i, columns=[col_sheet_name])
-
- sheets = ["AAA", "BBB", "CCC"]
-
- dfs = [tdf(s) for s in sheets]
- dfs = dict(zip(sheets, dfs))
-
- with ensure_clean(ext) as pth:
- with ExcelWriter(pth) as ew:
- for sheetname, df in dfs.items():
- df.to_excel(ew, sheetname)
-
- dfs_returned = pd.read_excel(pth, sheet_name=sheets, index_col=0)
-
- for s in sheets:
- tm.assert_frame_equal(dfs[s], dfs_returned[s])
-
- @td.skip_if_no("xlsxwriter")
- def test_read_excel_multiindex_empty_level(self, ext):
- # see gh-12453
- with ensure_clean(ext) as path:
- df = DataFrame({
- ("One", "x"): {0: 1},
- ("Two", "X"): {0: 3},
- ("Two", "Y"): {0: 7},
- ("Zero", ""): {0: 0}
- })
-
- expected = DataFrame({
- ("One", "x"): {0: 1},
- ("Two", "X"): {0: 3},
- ("Two", "Y"): {0: 7},
- ("Zero", "Unnamed: 4_level_1"): {0: 0}
- })
-
- df.to_excel(path)
- actual = pd.read_excel(path, header=[0, 1], index_col=0)
- tm.assert_frame_equal(actual, expected)
-
- df = pd.DataFrame({
- ("Beg", ""): {0: 0},
- ("Middle", "x"): {0: 1},
- ("Tail", "X"): {0: 3},
- ("Tail", "Y"): {0: 7}
- })
-
- expected = pd.DataFrame({
- ("Beg", "Unnamed: 1_level_1"): {0: 0},
- ("Middle", "x"): {0: 1},
- ("Tail", "X"): {0: 3},
- ("Tail", "Y"): {0: 7}
- })
-
- df.to_excel(path)
- actual = pd.read_excel(path, header=[0, 1], index_col=0)
- tm.assert_frame_equal(actual, expected)
-
- @td.skip_if_no("xlsxwriter")
- @pytest.mark.parametrize("c_idx_names", [True, False])
- @pytest.mark.parametrize("r_idx_names", [True, False])
- @pytest.mark.parametrize("c_idx_levels", [1, 3])
- @pytest.mark.parametrize("r_idx_levels", [1, 3])
- def test_excel_multindex_roundtrip(self, ext, c_idx_names, r_idx_names,
- c_idx_levels, r_idx_levels):
- # see gh-4679
- with ensure_clean(ext) as pth:
- if c_idx_levels == 1 and c_idx_names:
- pytest.skip("Column index name cannot be "
- "serialized unless it's a MultiIndex")
-
- # Empty name case current read in as
- # unnamed levels, not Nones.
- check_names = r_idx_names or r_idx_levels <= 1
-
- df = mkdf(5, 5, c_idx_names, r_idx_names,
- c_idx_levels, r_idx_levels)
- df.to_excel(pth)
-
- act = pd.read_excel(pth, index_col=list(range(r_idx_levels)),
- header=list(range(c_idx_levels)))
- tm.assert_frame_equal(df, act, check_names=check_names)
-
- df.iloc[0, :] = np.nan
- df.to_excel(pth)
-
- act = pd.read_excel(pth, index_col=list(range(r_idx_levels)),
- header=list(range(c_idx_levels)))
- tm.assert_frame_equal(df, act, check_names=check_names)
-
- df.iloc[-1, :] = np.nan
- df.to_excel(pth)
- act = pd.read_excel(pth, index_col=list(range(r_idx_levels)),
- header=list(range(c_idx_levels)))
- tm.assert_frame_equal(df, act, check_names=check_names)
-
- @td.skip_if_no("xlwt")
- @td.skip_if_no("openpyxl")
- def test_read_excel_parse_dates(self, ext):
- # see gh-11544, gh-12051
- df = DataFrame(
- {"col": [1, 2, 3],
- "date_strings": pd.date_range("2012-01-01", periods=3)})
- df2 = df.copy()
- df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y")
-
- with ensure_clean(ext) as pth:
- df2.to_excel(pth)
-
- res = pd.read_excel(pth, index_col=0)
- tm.assert_frame_equal(df2, res)
-
- res = pd.read_excel(pth, parse_dates=["date_strings"], index_col=0)
- tm.assert_frame_equal(df, res)
-
- date_parser = lambda x: pd.datetime.strptime(x, "%m/%d/%Y")
- res = pd.read_excel(pth, parse_dates=["date_strings"],
- date_parser=date_parser, index_col=0)
- tm.assert_frame_equal(df, res)
-
-
-@td.skip_if_no('xlrd')
-class TestXlrdReader:
- """
- This is the base class for the xlrd tests, and 3 different file formats
- are supported: xls, xlsx, xlsm
- """
-
- @td.skip_if_no("xlwt")
- def test_read_xlrd_book(self, read_ext, frame):
- import xlrd
- df = frame
-
- engine = "xlrd"
- sheet_name = "SheetA"
-
- with ensure_clean(read_ext) as pth:
- df.to_excel(pth, sheet_name)
- book = xlrd.open_workbook(pth)
-
- with ExcelFile(book, engine=engine) as xl:
- result = pd.read_excel(xl, sheet_name, index_col=0)
- tm.assert_frame_equal(df, result)
-
- result = pd.read_excel(book, sheet_name=sheet_name,
- engine=engine, index_col=0)
- tm.assert_frame_equal(df, result)
-
-
-class _WriterBase:
-
- @pytest.fixture(autouse=True)
- def set_engine_and_path(self, request, engine, ext):
- """Fixture to set engine and open file for use in each test case
-
- Rather than requiring `engine=...` to be provided explicitly as an
- argument in each test, this fixture sets a global option to dictate
- which engine should be used to write Excel files. After executing
- the test it rolls back said change to the global option.
-
- It also uses a context manager to open a temporary excel file for
- the function to write to, accessible via `self.path`
-
- Notes
- -----
- This fixture will run as part of each test method defined in the
- class and any subclasses, on account of the `autouse=True`
- argument
- """
- option_name = 'io.excel.{ext}.writer'.format(ext=ext.strip('.'))
- prev_engine = get_option(option_name)
- set_option(option_name, engine)
- with ensure_clean(ext) as path:
- self.path = path
- yield
- set_option(option_name, prev_engine) # Roll back option change
-
-
-@pytest.mark.parametrize("engine,ext", [
- pytest.param('openpyxl', '.xlsx', marks=pytest.mark.skipif(
- not td.safe_import('openpyxl'), reason='No openpyxl')),
- pytest.param('openpyxl', '.xlsm', marks=pytest.mark.skipif(
- not td.safe_import('openpyxl'), reason='No openpyxl')),
- pytest.param('xlwt', '.xls', marks=pytest.mark.skipif(
- not td.safe_import('xlwt'), reason='No xlwt')),
- pytest.param('xlsxwriter', '.xlsx', marks=pytest.mark.skipif(
- not td.safe_import('xlsxwriter'), reason='No xlsxwriter'))
-])
-class TestExcelWriter(_WriterBase):
- # Base class for test cases to run with different Excel writers.
-
- def test_excel_sheet_size(self, engine, ext):
-
- # GH 26080
- breaking_row_count = 2**20 + 1
- breaking_col_count = 2**14 + 1
- # purposely using two arrays to prevent memory issues while testing
- row_arr = np.zeros(shape=(breaking_row_count, 1))
- col_arr = np.zeros(shape=(1, breaking_col_count))
- row_df = pd.DataFrame(row_arr)
- col_df = pd.DataFrame(col_arr)
-
- msg = "sheet is too large"
- with pytest.raises(ValueError, match=msg):
- row_df.to_excel(self.path)
-
- with pytest.raises(ValueError, match=msg):
- col_df.to_excel(self.path)
-
- def test_excel_sheet_by_name_raise(self, engine, ext):
- import xlrd
-
- gt = DataFrame(np.random.randn(10, 2))
- gt.to_excel(self.path)
-
- xl = ExcelFile(self.path)
- df = pd.read_excel(xl, 0, index_col=0)
-
- tm.assert_frame_equal(gt, df)
-
- with pytest.raises(xlrd.XLRDError):
- pd.read_excel(xl, "0")
-
- def test_excel_writer_context_manager(self, frame, engine, ext):
- with ExcelWriter(self.path) as writer:
- frame.to_excel(writer, "Data1")
- frame2 = frame.copy()
- frame2.columns = frame.columns[::-1]
- frame2.to_excel(writer, "Data2")
-
- with ExcelFile(self.path) as reader:
- found_df = pd.read_excel(reader, "Data1", index_col=0)
- found_df2 = pd.read_excel(reader, "Data2", index_col=0)
-
- tm.assert_frame_equal(found_df, frame)
- tm.assert_frame_equal(found_df2, frame2)
-
- def test_roundtrip(self, engine, ext, frame):
- frame = frame.copy()
- frame['A'][:5] = nan
-
- frame.to_excel(self.path, 'test1')
- frame.to_excel(self.path, 'test1', columns=['A', 'B'])
- frame.to_excel(self.path, 'test1', header=False)
- frame.to_excel(self.path, 'test1', index=False)
-
- # test roundtrip
- frame.to_excel(self.path, 'test1')
- recons = pd.read_excel(self.path, 'test1', index_col=0)
- tm.assert_frame_equal(frame, recons)
-
- frame.to_excel(self.path, 'test1', index=False)
- recons = pd.read_excel(self.path, 'test1', index_col=None)
- recons.index = frame.index
- tm.assert_frame_equal(frame, recons)
-
- frame.to_excel(self.path, 'test1', na_rep='NA')
- recons = pd.read_excel(
- self.path, 'test1', index_col=0, na_values=['NA'])
- tm.assert_frame_equal(frame, recons)
-
- # GH 3611
- frame.to_excel(self.path, 'test1', na_rep='88')
- recons = pd.read_excel(
- self.path, 'test1', index_col=0, na_values=['88'])
- tm.assert_frame_equal(frame, recons)
-
- frame.to_excel(self.path, 'test1', na_rep='88')
- recons = pd.read_excel(
- self.path, 'test1', index_col=0, na_values=[88, 88.0])
- tm.assert_frame_equal(frame, recons)
-
- # GH 6573
- frame.to_excel(self.path, 'Sheet1')
- recons = pd.read_excel(self.path, index_col=0)
- tm.assert_frame_equal(frame, recons)
-
- frame.to_excel(self.path, '0')
- recons = pd.read_excel(self.path, index_col=0)
- tm.assert_frame_equal(frame, recons)
-
- # GH 8825 Pandas Series should provide to_excel method
- s = frame["A"]
- s.to_excel(self.path)
- recons = pd.read_excel(self.path, index_col=0)
- tm.assert_frame_equal(s.to_frame(), recons)
-
- def test_mixed(self, engine, ext, frame):
- mixed_frame = frame.copy()
- mixed_frame['foo'] = 'bar'
-
- mixed_frame.to_excel(self.path, 'test1')
- reader = ExcelFile(self.path)
- recons = pd.read_excel(reader, 'test1', index_col=0)
- tm.assert_frame_equal(mixed_frame, recons)
-
- def test_ts_frame(self, tsframe, engine, ext):
- df = tsframe
-
- df.to_excel(self.path, "test1")
- reader = ExcelFile(self.path)
-
- recons = pd.read_excel(reader, "test1", index_col=0)
- tm.assert_frame_equal(df, recons)
-
- def test_basics_with_nan(self, engine, ext, frame):
- frame = frame.copy()
- frame['A'][:5] = nan
- frame.to_excel(self.path, 'test1')
- frame.to_excel(self.path, 'test1', columns=['A', 'B'])
- frame.to_excel(self.path, 'test1', header=False)
- frame.to_excel(self.path, 'test1', index=False)
-
- @pytest.mark.parametrize("np_type", [
- np.int8, np.int16, np.int32, np.int64])
- def test_int_types(self, engine, ext, np_type):
- # Test np.int values read come back as int
- # (rather than float which is Excel's format).
- df = DataFrame(np.random.randint(-10, 10, size=(10, 2)),
- dtype=np_type)
- df.to_excel(self.path, "test1")
-
- reader = ExcelFile(self.path)
- recons = pd.read_excel(reader, "test1", index_col=0)
-
- int_frame = df.astype(np.int64)
- tm.assert_frame_equal(int_frame, recons)
-
- recons2 = pd.read_excel(self.path, "test1", index_col=0)
- tm.assert_frame_equal(int_frame, recons2)
-
- # Test with convert_float=False comes back as float.
- float_frame = df.astype(float)
- recons = pd.read_excel(self.path, "test1",
- convert_float=False, index_col=0)
- tm.assert_frame_equal(recons, float_frame,
- check_index_type=False,
- check_column_type=False)
-
- @pytest.mark.parametrize("np_type", [
- np.float16, np.float32, np.float64])
- def test_float_types(self, engine, ext, np_type):
- # Test np.float values read come back as float.
- df = DataFrame(np.random.random_sample(10), dtype=np_type)
- df.to_excel(self.path, "test1")
-
- reader = ExcelFile(self.path)
- recons = pd.read_excel(reader, "test1", index_col=0).astype(np_type)
-
- tm.assert_frame_equal(df, recons, check_dtype=False)
-
- @pytest.mark.parametrize("np_type", [np.bool8, np.bool_])
- def test_bool_types(self, engine, ext, np_type):
- # Test np.bool values read come back as float.
- df = (DataFrame([1, 0, True, False], dtype=np_type))
- df.to_excel(self.path, "test1")
-
- reader = ExcelFile(self.path)
- recons = pd.read_excel(reader, "test1", index_col=0).astype(np_type)
-
- tm.assert_frame_equal(df, recons)
-
- def test_inf_roundtrip(self, engine, ext):
- df = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)])
- df.to_excel(self.path, "test1")
-
- reader = ExcelFile(self.path)
- recons = pd.read_excel(reader, "test1", index_col=0)
-
- tm.assert_frame_equal(df, recons)
-
- def test_sheets(self, engine, ext, frame, tsframe):
- frame = frame.copy()
- frame['A'][:5] = nan
-
- frame.to_excel(self.path, 'test1')
- frame.to_excel(self.path, 'test1', columns=['A', 'B'])
- frame.to_excel(self.path, 'test1', header=False)
- frame.to_excel(self.path, 'test1', index=False)
-
- # Test writing to separate sheets
- writer = ExcelWriter(self.path)
- frame.to_excel(writer, 'test1')
- tsframe.to_excel(writer, 'test2')
- writer.save()
- reader = ExcelFile(self.path)
- recons = pd.read_excel(reader, 'test1', index_col=0)
- tm.assert_frame_equal(frame, recons)
- recons = pd.read_excel(reader, 'test2', index_col=0)
- tm.assert_frame_equal(tsframe, recons)
- assert 2 == len(reader.sheet_names)
- assert 'test1' == reader.sheet_names[0]
- assert 'test2' == reader.sheet_names[1]
-
- def test_colaliases(self, engine, ext, frame):
- frame = frame.copy()
- frame['A'][:5] = nan
-
- frame.to_excel(self.path, 'test1')
- frame.to_excel(self.path, 'test1', columns=['A', 'B'])
- frame.to_excel(self.path, 'test1', header=False)
- frame.to_excel(self.path, 'test1', index=False)
-
- # column aliases
- col_aliases = Index(['AA', 'X', 'Y', 'Z'])
- frame.to_excel(self.path, 'test1', header=col_aliases)
- reader = ExcelFile(self.path)
- rs = pd.read_excel(reader, 'test1', index_col=0)
- xp = frame.copy()
- xp.columns = col_aliases
- tm.assert_frame_equal(xp, rs)
-
- def test_roundtrip_indexlabels(self, merge_cells, engine, ext, frame):
- frame = frame.copy()
- frame['A'][:5] = nan
-
- frame.to_excel(self.path, 'test1')
- frame.to_excel(self.path, 'test1', columns=['A', 'B'])
- frame.to_excel(self.path, 'test1', header=False)
- frame.to_excel(self.path, 'test1', index=False)
-
- # test index_label
- df = (DataFrame(np.random.randn(10, 2)) >= 0)
- df.to_excel(self.path, 'test1',
- index_label=['test'],
- merge_cells=merge_cells)
- reader = ExcelFile(self.path)
- recons = pd.read_excel(
- reader, 'test1', index_col=0).astype(np.int64)
- df.index.names = ['test']
- assert df.index.names == recons.index.names
-
- df = (DataFrame(np.random.randn(10, 2)) >= 0)
- df.to_excel(self.path,
- 'test1',
- index_label=['test', 'dummy', 'dummy2'],
- merge_cells=merge_cells)
- reader = ExcelFile(self.path)
- recons = pd.read_excel(
- reader, 'test1', index_col=0).astype(np.int64)
- df.index.names = ['test']
- assert df.index.names == recons.index.names
-
- df = (DataFrame(np.random.randn(10, 2)) >= 0)
- df.to_excel(self.path,
- 'test1',
- index_label='test',
- merge_cells=merge_cells)
- reader = ExcelFile(self.path)
- recons = pd.read_excel(
- reader, 'test1', index_col=0).astype(np.int64)
- df.index.names = ['test']
- tm.assert_frame_equal(df, recons.astype(bool))
-
- frame.to_excel(self.path,
- 'test1',
- columns=['A', 'B', 'C', 'D'],
- index=False, merge_cells=merge_cells)
- # take 'A' and 'B' as indexes (same row as cols 'C', 'D')
- df = frame.copy()
- df = df.set_index(['A', 'B'])
-
- reader = ExcelFile(self.path)
- recons = pd.read_excel(reader, 'test1', index_col=[0, 1])
- tm.assert_frame_equal(df, recons, check_less_precise=True)
-
- def test_excel_roundtrip_indexname(self, merge_cells, engine, ext):
- df = DataFrame(np.random.randn(10, 4))
- df.index.name = 'foo'
-
- df.to_excel(self.path, merge_cells=merge_cells)
-
- xf = ExcelFile(self.path)
- result = pd.read_excel(xf, xf.sheet_names[0], index_col=0)
-
- tm.assert_frame_equal(result, df)
- assert result.index.name == 'foo'
-
- def test_excel_roundtrip_datetime(self, merge_cells, tsframe, engine, ext):
- # datetime.date, not sure what to test here exactly
- tsf = tsframe.copy()
-
- tsf.index = [x.date() for x in tsframe.index]
- tsf.to_excel(self.path, "test1", merge_cells=merge_cells)
-
- reader = ExcelFile(self.path)
- recons = pd.read_excel(reader, "test1", index_col=0)
-
- tm.assert_frame_equal(tsframe, recons)
-
- def test_excel_date_datetime_format(self, engine, ext):
- # see gh-4133
- #
- # Excel output format strings
- df = DataFrame([[date(2014, 1, 31),
- date(1999, 9, 24)],
- [datetime(1998, 5, 26, 23, 33, 4),
- datetime(2014, 2, 28, 13, 5, 13)]],
- index=["DATE", "DATETIME"], columns=["X", "Y"])
- df_expected = DataFrame([[datetime(2014, 1, 31),
- datetime(1999, 9, 24)],
- [datetime(1998, 5, 26, 23, 33, 4),
- datetime(2014, 2, 28, 13, 5, 13)]],
- index=["DATE", "DATETIME"], columns=["X", "Y"])
-
- with ensure_clean(ext) as filename2:
- writer1 = ExcelWriter(self.path)
- writer2 = ExcelWriter(filename2,
- date_format="DD.MM.YYYY",
- datetime_format="DD.MM.YYYY HH-MM-SS")
-
- df.to_excel(writer1, "test1")
- df.to_excel(writer2, "test1")
-
- writer1.close()
- writer2.close()
-
- reader1 = ExcelFile(self.path)
- reader2 = ExcelFile(filename2)
-
- rs1 = pd.read_excel(reader1, "test1", index_col=0)
- rs2 = pd.read_excel(reader2, "test1", index_col=0)
-
- tm.assert_frame_equal(rs1, rs2)
-
- # Since the reader returns a datetime object for dates,
- # we need to use df_expected to check the result.
- tm.assert_frame_equal(rs2, df_expected)
-
- def test_to_excel_interval_no_labels(self, engine, ext):
- # see gh-19242
- #
- # Test writing Interval without labels.
- df = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
- dtype=np.int64)
- expected = df.copy()
-
- df["new"] = pd.cut(df[0], 10)
- expected["new"] = pd.cut(expected[0], 10).astype(str)
-
- df.to_excel(self.path, "test1")
- reader = ExcelFile(self.path)
-
- recons = pd.read_excel(reader, "test1", index_col=0)
- tm.assert_frame_equal(expected, recons)
-
- def test_to_excel_interval_labels(self, engine, ext):
- # see gh-19242
- #
- # Test writing Interval with labels.
- df = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
- dtype=np.int64)
- expected = df.copy()
- intervals = pd.cut(df[0], 10, labels=["A", "B", "C", "D", "E",
- "F", "G", "H", "I", "J"])
- df["new"] = intervals
- expected["new"] = pd.Series(list(intervals))
-
- df.to_excel(self.path, "test1")
- reader = ExcelFile(self.path)
-
- recons = pd.read_excel(reader, "test1", index_col=0)
- tm.assert_frame_equal(expected, recons)
-
- def test_to_excel_timedelta(self, engine, ext):
- # see gh-19242, gh-9155
- #
- # Test writing timedelta to xls.
- df = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
- columns=["A"], dtype=np.int64)
- expected = df.copy()
-
- df["new"] = df["A"].apply(lambda x: timedelta(seconds=x))
- expected["new"] = expected["A"].apply(
- lambda x: timedelta(seconds=x).total_seconds() / float(86400))
-
- df.to_excel(self.path, "test1")
- reader = ExcelFile(self.path)
-
- recons = pd.read_excel(reader, "test1", index_col=0)
- tm.assert_frame_equal(expected, recons)
-
- def test_to_excel_periodindex(self, engine, ext, tsframe):
- xp = tsframe.resample('M', kind='period').mean()
-
- xp.to_excel(self.path, 'sht1')
-
- reader = ExcelFile(self.path)
- rs = pd.read_excel(reader, 'sht1', index_col=0)
- tm.assert_frame_equal(xp, rs.to_period('M'))
-
- def test_to_excel_multiindex(self, merge_cells, engine, ext, frame):
- arrays = np.arange(len(frame.index) * 2).reshape(2, -1)
- new_index = MultiIndex.from_arrays(arrays,
- names=['first', 'second'])
- frame.index = new_index
-
- frame.to_excel(self.path, 'test1', header=False)
- frame.to_excel(self.path, 'test1', columns=['A', 'B'])
-
- # round trip
- frame.to_excel(self.path, 'test1', merge_cells=merge_cells)
- reader = ExcelFile(self.path)
- df = pd.read_excel(reader, 'test1', index_col=[0, 1])
- tm.assert_frame_equal(frame, df)
-
- # GH13511
- def test_to_excel_multiindex_nan_label(self, merge_cells, engine, ext):
- df = pd.DataFrame({'A': [None, 2, 3],
- 'B': [10, 20, 30],
- 'C': np.random.sample(3)})
- df = df.set_index(['A', 'B'])
-
- df.to_excel(self.path, merge_cells=merge_cells)
- df1 = pd.read_excel(self.path, index_col=[0, 1])
- tm.assert_frame_equal(df, df1)
-
- # Test for Issue 11328. If column indices are integers, make
- # sure they are handled correctly for either setting of
- # merge_cells
- def test_to_excel_multiindex_cols(self, merge_cells, engine, ext, frame):
- arrays = np.arange(len(frame.index) * 2).reshape(2, -1)
- new_index = MultiIndex.from_arrays(arrays,
- names=['first', 'second'])
- frame.index = new_index
-
- new_cols_index = MultiIndex.from_tuples([(40, 1), (40, 2),
- (50, 1), (50, 2)])
- frame.columns = new_cols_index
- header = [0, 1]
- if not merge_cells:
- header = 0
-
- # round trip
- frame.to_excel(self.path, 'test1', merge_cells=merge_cells)
- reader = ExcelFile(self.path)
- df = pd.read_excel(reader, 'test1', header=header, index_col=[0, 1])
- if not merge_cells:
- fm = frame.columns.format(sparsify=False,
- adjoin=False, names=False)
- frame.columns = [".".join(map(str, q)) for q in zip(*fm)]
- tm.assert_frame_equal(frame, df)
-
- def test_to_excel_multiindex_dates(
- self, merge_cells, engine, ext, tsframe):
- # try multiindex with dates
- new_index = [tsframe.index, np.arange(len(tsframe.index))]
- tsframe.index = MultiIndex.from_arrays(new_index)
-
- tsframe.index.names = ['time', 'foo']
- tsframe.to_excel(self.path, 'test1', merge_cells=merge_cells)
- reader = ExcelFile(self.path)
- recons = pd.read_excel(reader, 'test1', index_col=[0, 1])
-
- tm.assert_frame_equal(tsframe, recons)
- assert recons.index.names == ('time', 'foo')
-
- def test_to_excel_multiindex_no_write_index(self, engine, ext):
- # Test writing and re-reading a MI witout the index. GH 5616.
-
- # Initial non-MI frame.
- frame1 = DataFrame({'a': [10, 20], 'b': [30, 40], 'c': [50, 60]})
-
- # Add a MI.
- frame2 = frame1.copy()
- multi_index = MultiIndex.from_tuples([(70, 80), (90, 100)])
- frame2.index = multi_index
-
- # Write out to Excel without the index.
- frame2.to_excel(self.path, 'test1', index=False)
-
- # Read it back in.
- reader = ExcelFile(self.path)
- frame3 = pd.read_excel(reader, 'test1')
-
- # Test that it is the same as the initial frame.
- tm.assert_frame_equal(frame1, frame3)
-
- def test_to_excel_float_format(self, engine, ext):
- df = DataFrame([[0.123456, 0.234567, 0.567567],
- [12.32112, 123123.2, 321321.2]],
- index=["A", "B"], columns=["X", "Y", "Z"])
- df.to_excel(self.path, "test1", float_format="%.2f")
-
- reader = ExcelFile(self.path)
- result = pd.read_excel(reader, "test1", index_col=0)
-
- expected = DataFrame([[0.12, 0.23, 0.57],
- [12.32, 123123.20, 321321.20]],
- index=["A", "B"], columns=["X", "Y", "Z"])
- tm.assert_frame_equal(result, expected)
-
- def test_to_excel_output_encoding(self, engine, ext):
- # Avoid mixed inferred_type.
- df = DataFrame([["\u0192", "\u0193", "\u0194"],
- ["\u0195", "\u0196", "\u0197"]],
- index=["A\u0192", "B"],
- columns=["X\u0193", "Y", "Z"])
-
- with ensure_clean("__tmp_to_excel_float_format__." + ext) as filename:
- df.to_excel(filename, sheet_name="TestSheet", encoding="utf8")
- result = pd.read_excel(filename, "TestSheet",
- encoding="utf8", index_col=0)
- tm.assert_frame_equal(result, df)
-
- def test_to_excel_unicode_filename(self, engine, ext):
- with ensure_clean("\u0192u." + ext) as filename:
- try:
- f = open(filename, "wb")
- except UnicodeEncodeError:
- pytest.skip("No unicode file names on this system")
- else:
- f.close()
-
- df = DataFrame([[0.123456, 0.234567, 0.567567],
- [12.32112, 123123.2, 321321.2]],
- index=["A", "B"], columns=["X", "Y", "Z"])
- df.to_excel(filename, "test1", float_format="%.2f")
-
- reader = ExcelFile(filename)
- result = pd.read_excel(reader, "test1", index_col=0)
-
- expected = DataFrame([[0.12, 0.23, 0.57],
- [12.32, 123123.20, 321321.20]],
- index=["A", "B"], columns=["X", "Y", "Z"])
- tm.assert_frame_equal(result, expected)
-
- # def test_to_excel_header_styling_xls(self, engine, ext):
-
- # import StringIO
- # s = StringIO(
- # """Date,ticker,type,value
- # 2001-01-01,x,close,12.2
- # 2001-01-01,x,open ,12.1
- # 2001-01-01,y,close,12.2
- # 2001-01-01,y,open ,12.1
- # 2001-02-01,x,close,12.2
- # 2001-02-01,x,open ,12.1
- # 2001-02-01,y,close,12.2
- # 2001-02-01,y,open ,12.1
- # 2001-03-01,x,close,12.2
- # 2001-03-01,x,open ,12.1
- # 2001-03-01,y,close,12.2
- # 2001-03-01,y,open ,12.1""")
- # df = read_csv(s, parse_dates=["Date"])
- # pdf = df.pivot_table(values="value", rows=["ticker"],
- # cols=["Date", "type"])
-
- # try:
- # import xlwt
- # import xlrd
- # except ImportError:
- # pytest.skip
-
- # filename = '__tmp_to_excel_header_styling_xls__.xls'
- # pdf.to_excel(filename, 'test1')
-
- # wbk = xlrd.open_workbook(filename,
- # formatting_info=True)
- # assert ["test1"] == wbk.sheet_names()
- # ws = wbk.sheet_by_name('test1')
- # assert [(0, 1, 5, 7), (0, 1, 3, 5), (0, 1, 1, 3)] == ws.merged_cells
- # for i in range(0, 2):
- # for j in range(0, 7):
- # xfx = ws.cell_xf_index(0, 0)
- # cell_xf = wbk.xf_list[xfx]
- # font = wbk.font_list
- # assert 1 == font[cell_xf.font_index].bold
- # assert 1 == cell_xf.border.top_line_style
- # assert 1 == cell_xf.border.right_line_style
- # assert 1 == cell_xf.border.bottom_line_style
- # assert 1 == cell_xf.border.left_line_style
- # assert 2 == cell_xf.alignment.hor_align
- # os.remove(filename)
- # def test_to_excel_header_styling_xlsx(self, engine, ext):
- # import StringIO
- # s = StringIO(
- # """Date,ticker,type,value
- # 2001-01-01,x,close,12.2
- # 2001-01-01,x,open ,12.1
- # 2001-01-01,y,close,12.2
- # 2001-01-01,y,open ,12.1
- # 2001-02-01,x,close,12.2
- # 2001-02-01,x,open ,12.1
- # 2001-02-01,y,close,12.2
- # 2001-02-01,y,open ,12.1
- # 2001-03-01,x,close,12.2
- # 2001-03-01,x,open ,12.1
- # 2001-03-01,y,close,12.2
- # 2001-03-01,y,open ,12.1""")
- # df = read_csv(s, parse_dates=["Date"])
- # pdf = df.pivot_table(values="value", rows=["ticker"],
- # cols=["Date", "type"])
- # try:
- # import openpyxl
- # from openpyxl.cell import get_column_letter
- # except ImportError:
- # pytest.skip
- # if openpyxl.__version__ < '1.6.1':
- # pytest.skip
- # # test xlsx_styling
- # filename = '__tmp_to_excel_header_styling_xlsx__.xlsx'
- # pdf.to_excel(filename, 'test1')
- # wbk = openpyxl.load_workbook(filename)
- # assert ["test1"] == wbk.get_sheet_names()
- # ws = wbk.get_sheet_by_name('test1')
- # xlsaddrs = ["%s2" % chr(i) for i in range(ord('A'), ord('H'))]
- # xlsaddrs += ["A%s" % i for i in range(1, 6)]
- # xlsaddrs += ["B1", "D1", "F1"]
- # for xlsaddr in xlsaddrs:
- # cell = ws.cell(xlsaddr)
- # assert cell.style.font.bold
- # assert (openpyxl.style.Border.BORDER_THIN ==
- # cell.style.borders.top.border_style)
- # assert (openpyxl.style.Border.BORDER_THIN ==
- # cell.style.borders.right.border_style)
- # assert (openpyxl.style.Border.BORDER_THIN ==
- # cell.style.borders.bottom.border_style)
- # assert (openpyxl.style.Border.BORDER_THIN ==
- # cell.style.borders.left.border_style)
- # assert (openpyxl.style.Alignment.HORIZONTAL_CENTER ==
- # cell.style.alignment.horizontal)
- # mergedcells_addrs = ["C1", "E1", "G1"]
- # for maddr in mergedcells_addrs:
- # assert ws.cell(maddr).merged
- # os.remove(filename)
-
- @pytest.mark.parametrize("use_headers", [True, False])
- @pytest.mark.parametrize("r_idx_nlevels", [1, 2, 3])
- @pytest.mark.parametrize("c_idx_nlevels", [1, 2, 3])
- def test_excel_010_hemstring(self, merge_cells, engine, ext,
- c_idx_nlevels, r_idx_nlevels, use_headers):
-
- def roundtrip(data, header=True, parser_hdr=0, index=True):
- data.to_excel(self.path, header=header,
- merge_cells=merge_cells, index=index)
-
- xf = ExcelFile(self.path)
- return pd.read_excel(xf, xf.sheet_names[0], header=parser_hdr)
-
- # Basic test.
- parser_header = 0 if use_headers else None
- res = roundtrip(DataFrame([0]), use_headers, parser_header)
-
- assert res.shape == (1, 2)
- assert res.iloc[0, 0] is not np.nan
-
- # More complex tests with multi-index.
- nrows = 5
- ncols = 3
-
- from pandas.util.testing import makeCustomDataframe as mkdf
- # ensure limited functionality in 0.10
- # override of gh-2370 until sorted out in 0.11
-
- df = mkdf(nrows, ncols, r_idx_nlevels=r_idx_nlevels,
- c_idx_nlevels=c_idx_nlevels)
-
- # This if will be removed once multi-column Excel writing
- # is implemented. For now fixing gh-9794.
- if c_idx_nlevels > 1:
- with pytest.raises(NotImplementedError):
- roundtrip(df, use_headers, index=False)
- else:
- res = roundtrip(df, use_headers)
-
- if use_headers:
- assert res.shape == (nrows, ncols + r_idx_nlevels)
- else:
- # First row taken as columns.
- assert res.shape == (nrows - 1, ncols + r_idx_nlevels)
-
- # No NaNs.
- for r in range(len(res.index)):
- for c in range(len(res.columns)):
- assert res.iloc[r, c] is not np.nan
-
- def test_duplicated_columns(self, engine, ext):
- # see gh-5235
- df = DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]],
- columns=["A", "B", "B"])
- df.to_excel(self.path, "test1")
- expected = DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]],
- columns=["A", "B", "B.1"])
-
- # By default, we mangle.
- result = pd.read_excel(self.path, "test1", index_col=0)
- tm.assert_frame_equal(result, expected)
-
- # Explicitly, we pass in the parameter.
- result = pd.read_excel(self.path, "test1", index_col=0,
- mangle_dupe_cols=True)
- tm.assert_frame_equal(result, expected)
-
- # see gh-11007, gh-10970
- df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]],
- columns=["A", "B", "A", "B"])
- df.to_excel(self.path, "test1")
-
- result = pd.read_excel(self.path, "test1", index_col=0)
- expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]],
- columns=["A", "B", "A.1", "B.1"])
- tm.assert_frame_equal(result, expected)
-
- # see gh-10982
- df.to_excel(self.path, "test1", index=False, header=False)
- result = pd.read_excel(self.path, "test1", header=None)
-
- expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
- tm.assert_frame_equal(result, expected)
-
- msg = "Setting mangle_dupe_cols=False is not supported yet"
- with pytest.raises(ValueError, match=msg):
- pd.read_excel(
- self.path, "test1", header=None, mangle_dupe_cols=False)
-
- def test_swapped_columns(self, engine, ext):
- # Test for issue #5427.
- write_frame = DataFrame({'A': [1, 1, 1],
- 'B': [2, 2, 2]})
- write_frame.to_excel(self.path, 'test1', columns=['B', 'A'])
-
- read_frame = pd.read_excel(self.path, 'test1', header=0)
-
- tm.assert_series_equal(write_frame['A'], read_frame['A'])
- tm.assert_series_equal(write_frame['B'], read_frame['B'])
-
- def test_invalid_columns(self, engine, ext):
- # see gh-10982
- write_frame = DataFrame({"A": [1, 1, 1],
- "B": [2, 2, 2]})
-
- with tm.assert_produces_warning(FutureWarning,
- check_stacklevel=False):
- write_frame.to_excel(self.path, "test1", columns=["B", "C"])
-
- expected = write_frame.reindex(columns=["B", "C"])
- read_frame = pd.read_excel(self.path, "test1", index_col=0)
- tm.assert_frame_equal(expected, read_frame)
-
- with pytest.raises(KeyError):
- write_frame.to_excel(self.path, "test1", columns=["C", "D"])
-
- def test_comment_arg(self, engine, ext):
- # see gh-18735
- #
- # Test the comment argument functionality to pd.read_excel.
-
- # Create file to read in.
- df = DataFrame({"A": ["one", "#one", "one"],
- "B": ["two", "two", "#two"]})
- df.to_excel(self.path, "test_c")
-
- # Read file without comment arg.
- result1 = pd.read_excel(self.path, "test_c", index_col=0)
-
- result1.iloc[1, 0] = None
- result1.iloc[1, 1] = None
- result1.iloc[2, 1] = None
-
- result2 = pd.read_excel(self.path, "test_c", comment="#", index_col=0)
- tm.assert_frame_equal(result1, result2)
-
- def test_comment_default(self, engine, ext):
- # Re issue #18735
- # Test the comment argument default to pd.read_excel
-
- # Create file to read in
- df = DataFrame({'A': ['one', '#one', 'one'],
- 'B': ['two', 'two', '#two']})
- df.to_excel(self.path, 'test_c')
-
- # Read file with default and explicit comment=None
- result1 = pd.read_excel(self.path, 'test_c')
- result2 = pd.read_excel(self.path, 'test_c', comment=None)
- tm.assert_frame_equal(result1, result2)
-
- def test_comment_used(self, engine, ext):
- # see gh-18735
- #
- # Test the comment argument is working as expected when used.
-
- # Create file to read in.
- df = DataFrame({"A": ["one", "#one", "one"],
- "B": ["two", "two", "#two"]})
- df.to_excel(self.path, "test_c")
-
- # Test read_frame_comment against manually produced expected output.
- expected = DataFrame({"A": ["one", None, "one"],
- "B": ["two", None, None]})
- result = pd.read_excel(self.path, "test_c", comment="#", index_col=0)
- tm.assert_frame_equal(result, expected)
-
- def test_comment_empty_line(self, engine, ext):
- # Re issue #18735
- # Test that pd.read_excel ignores commented lines at the end of file
-
- df = DataFrame({'a': ['1', '#2'], 'b': ['2', '3']})
- df.to_excel(self.path, index=False)
-
- # Test that all-comment lines at EoF are ignored
- expected = DataFrame({'a': [1], 'b': [2]})
- result = pd.read_excel(self.path, comment='#')
- tm.assert_frame_equal(result, expected)
-
- def test_datetimes(self, engine, ext):
-
- # Test writing and reading datetimes. For issue #9139. (xref #9185)
- datetimes = [datetime(2013, 1, 13, 1, 2, 3),
- datetime(2013, 1, 13, 2, 45, 56),
- datetime(2013, 1, 13, 4, 29, 49),
- datetime(2013, 1, 13, 6, 13, 42),
- datetime(2013, 1, 13, 7, 57, 35),
- datetime(2013, 1, 13, 9, 41, 28),
- datetime(2013, 1, 13, 11, 25, 21),
- datetime(2013, 1, 13, 13, 9, 14),
- datetime(2013, 1, 13, 14, 53, 7),
- datetime(2013, 1, 13, 16, 37, 0),
- datetime(2013, 1, 13, 18, 20, 52)]
-
- write_frame = DataFrame({'A': datetimes})
- write_frame.to_excel(self.path, 'Sheet1')
- read_frame = pd.read_excel(self.path, 'Sheet1', header=0)
-
- tm.assert_series_equal(write_frame['A'], read_frame['A'])
-
- def test_bytes_io(self, engine, ext):
- # see gh-7074
- bio = BytesIO()
- df = DataFrame(np.random.randn(10, 2))
-
- # Pass engine explicitly, as there is no file path to infer from.
- writer = ExcelWriter(bio, engine=engine)
- df.to_excel(writer)
- writer.save()
-
- bio.seek(0)
- reread_df = pd.read_excel(bio, index_col=0)
- tm.assert_frame_equal(df, reread_df)
-
- def test_write_lists_dict(self, engine, ext):
- # see gh-8188.
- df = DataFrame({"mixed": ["a", ["b", "c"], {"d": "e", "f": 2}],
- "numeric": [1, 2, 3.0],
- "str": ["apple", "banana", "cherry"]})
- df.to_excel(self.path, "Sheet1")
- read = pd.read_excel(self.path, "Sheet1", header=0, index_col=0)
-
- expected = df.copy()
- expected.mixed = expected.mixed.apply(str)
- expected.numeric = expected.numeric.astype("int64")
-
- tm.assert_frame_equal(read, expected)
-
- def test_true_and_false_value_options(self, engine, ext):
- # see gh-13347
- df = pd.DataFrame([["foo", "bar"]], columns=["col1", "col2"])
- expected = df.replace({"foo": True, "bar": False})
-
- df.to_excel(self.path)
- read_frame = pd.read_excel(self.path, true_values=["foo"],
- false_values=["bar"], index_col=0)
- tm.assert_frame_equal(read_frame, expected)
-
- def test_freeze_panes(self, engine, ext):
- # see gh-15160
- expected = DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"])
- expected.to_excel(self.path, "Sheet1", freeze_panes=(1, 1))
-
- result = pd.read_excel(self.path, index_col=0)
- tm.assert_frame_equal(result, expected)
-
- def test_path_path_lib(self, engine, ext):
- df = tm.makeDataFrame()
- writer = partial(df.to_excel, engine=engine)
-
- reader = partial(pd.read_excel, index_col=0)
- result = tm.round_trip_pathlib(writer, reader,
- path="foo.{ext}".format(ext=ext))
- tm.assert_frame_equal(result, df)
-
- def test_path_local_path(self, engine, ext):
- df = tm.makeDataFrame()
- writer = partial(df.to_excel, engine=engine)
-
- reader = partial(pd.read_excel, index_col=0)
- result = tm.round_trip_pathlib(writer, reader,
- path="foo.{ext}".format(ext=ext))
- tm.assert_frame_equal(result, df)
-
-
-@td.skip_if_no('openpyxl')
-@pytest.mark.parametrize("ext", ['.xlsx'])
-class TestOpenpyxlTests:
-
- def test_to_excel_styleconverter(self, ext):
- from openpyxl import styles
-
- hstyle = {
- "font": {
- "color": '00FF0000',
- "bold": True,
- },
- "borders": {
- "top": "thin",
- "right": "thin",
- "bottom": "thin",
- "left": "thin",
- },
- "alignment": {
- "horizontal": "center",
- "vertical": "top",
- },
- "fill": {
- "patternType": 'solid',
- 'fgColor': {
- 'rgb': '006666FF',
- 'tint': 0.3,
- },
- },
- "number_format": {
- "format_code": "0.00"
- },
- "protection": {
- "locked": True,
- "hidden": False,
- },
- }
-
- font_color = styles.Color('00FF0000')
- font = styles.Font(bold=True, color=font_color)
- side = styles.Side(style=styles.borders.BORDER_THIN)
- border = styles.Border(top=side, right=side, bottom=side, left=side)
- alignment = styles.Alignment(horizontal='center', vertical='top')
- fill_color = styles.Color(rgb='006666FF', tint=0.3)
- fill = styles.PatternFill(patternType='solid', fgColor=fill_color)
-
- number_format = '0.00'
-
- protection = styles.Protection(locked=True, hidden=False)
-
- kw = _OpenpyxlWriter._convert_to_style_kwargs(hstyle)
- assert kw['font'] == font
- assert kw['border'] == border
- assert kw['alignment'] == alignment
- assert kw['fill'] == fill
- assert kw['number_format'] == number_format
- assert kw['protection'] == protection
-
- def test_write_cells_merge_styled(self, ext):
- from pandas.io.formats.excel import ExcelCell
-
- sheet_name = 'merge_styled'
-
- sty_b1 = {'font': {'color': '00FF0000'}}
- sty_a2 = {'font': {'color': '0000FF00'}}
-
- initial_cells = [
- ExcelCell(col=1, row=0, val=42, style=sty_b1),
- ExcelCell(col=0, row=1, val=99, style=sty_a2),
- ]
-
- sty_merged = {'font': {'color': '000000FF', 'bold': True}}
- sty_kwargs = _OpenpyxlWriter._convert_to_style_kwargs(sty_merged)
- openpyxl_sty_merged = sty_kwargs['font']
- merge_cells = [
- ExcelCell(col=0, row=0, val='pandas',
- mergestart=1, mergeend=1, style=sty_merged),
- ]
-
- with ensure_clean(ext) as path:
- writer = _OpenpyxlWriter(path)
- writer.write_cells(initial_cells, sheet_name=sheet_name)
- writer.write_cells(merge_cells, sheet_name=sheet_name)
-
- wks = writer.sheets[sheet_name]
- xcell_b1 = wks['B1']
- xcell_a2 = wks['A2']
- assert xcell_b1.font == openpyxl_sty_merged
- assert xcell_a2.font == openpyxl_sty_merged
-
- @pytest.mark.parametrize("mode,expected", [
- ('w', ['baz']), ('a', ['foo', 'bar', 'baz'])])
- def test_write_append_mode(self, ext, mode, expected):
- import openpyxl
- df = DataFrame([1], columns=['baz'])
-
- with ensure_clean(ext) as f:
- wb = openpyxl.Workbook()
- wb.worksheets[0].title = 'foo'
- wb.worksheets[0]['A1'].value = 'foo'
- wb.create_sheet('bar')
- wb.worksheets[1]['A1'].value = 'bar'
- wb.save(f)
-
- writer = ExcelWriter(f, engine='openpyxl', mode=mode)
- df.to_excel(writer, sheet_name='baz', index=False)
- writer.save()
-
- wb2 = openpyxl.load_workbook(f)
- result = [sheet.title for sheet in wb2.worksheets]
- assert result == expected
-
- for index, cell_value in enumerate(expected):
- assert wb2.worksheets[index]['A1'].value == cell_value
-
-
-@td.skip_if_no('xlwt')
-@pytest.mark.parametrize("ext,", ['.xls'])
-class TestXlwtTests:
-
- def test_excel_raise_error_on_multiindex_columns_and_no_index(
- self, ext):
- # MultiIndex as columns is not yet implemented 9794
- cols = MultiIndex.from_tuples([('site', ''),
- ('2014', 'height'),
- ('2014', 'weight')])
- df = DataFrame(np.random.randn(10, 3), columns=cols)
- with pytest.raises(NotImplementedError):
- with ensure_clean(ext) as path:
- df.to_excel(path, index=False)
-
- def test_excel_multiindex_columns_and_index_true(self, ext):
- cols = MultiIndex.from_tuples([('site', ''),
- ('2014', 'height'),
- ('2014', 'weight')])
- df = pd.DataFrame(np.random.randn(10, 3), columns=cols)
- with ensure_clean(ext) as path:
- df.to_excel(path, index=True)
-
- def test_excel_multiindex_index(self, ext):
- # MultiIndex as index works so assert no error #9794
- cols = MultiIndex.from_tuples([('site', ''),
- ('2014', 'height'),
- ('2014', 'weight')])
- df = DataFrame(np.random.randn(3, 10), index=cols)
- with ensure_clean(ext) as path:
- df.to_excel(path, index=False)
-
- def test_to_excel_styleconverter(self, ext):
- import xlwt
-
- hstyle = {"font": {"bold": True},
- "borders": {"top": "thin",
- "right": "thin",
- "bottom": "thin",
- "left": "thin"},
- "alignment": {"horizontal": "center", "vertical": "top"}}
-
- xls_style = _XlwtWriter._convert_to_style(hstyle)
- assert xls_style.font.bold
- assert xlwt.Borders.THIN == xls_style.borders.top
- assert xlwt.Borders.THIN == xls_style.borders.right
- assert xlwt.Borders.THIN == xls_style.borders.bottom
- assert xlwt.Borders.THIN == xls_style.borders.left
- assert xlwt.Alignment.HORZ_CENTER == xls_style.alignment.horz
- assert xlwt.Alignment.VERT_TOP == xls_style.alignment.vert
-
- def test_write_append_mode_raises(self, ext):
- msg = "Append mode is not supported with xlwt!"
-
- with ensure_clean(ext) as f:
- with pytest.raises(ValueError, match=msg):
- ExcelWriter(f, engine='xlwt', mode='a')
-
-
-@td.skip_if_no('xlsxwriter')
-@pytest.mark.parametrize("ext", ['.xlsx'])
-class TestXlsxWriterTests:
-
- @td.skip_if_no('openpyxl')
- def test_column_format(self, ext):
- # Test that column formats are applied to cells. Test for issue #9167.
- # Applicable to xlsxwriter only.
- with warnings.catch_warnings():
- # Ignore the openpyxl lxml warning.
- warnings.simplefilter("ignore")
- import openpyxl
-
- with ensure_clean(ext) as path:
- frame = DataFrame({'A': [123456, 123456],
- 'B': [123456, 123456]})
-
- writer = ExcelWriter(path)
- frame.to_excel(writer)
-
- # Add a number format to col B and ensure it is applied to cells.
- num_format = '#,##0'
- write_workbook = writer.book
- write_worksheet = write_workbook.worksheets()[0]
- col_format = write_workbook.add_format({'num_format': num_format})
- write_worksheet.set_column('B:B', None, col_format)
- writer.save()
-
- read_workbook = openpyxl.load_workbook(path)
- try:
- read_worksheet = read_workbook['Sheet1']
- except TypeError:
- # compat
- read_worksheet = read_workbook.get_sheet_by_name(name='Sheet1')
-
- # Get the number format from the cell.
- try:
- cell = read_worksheet['B2']
- except TypeError:
- # compat
- cell = read_worksheet.cell('B2')
-
- try:
- read_num_format = cell.number_format
- except Exception:
- read_num_format = cell.style.number_format._format_code
-
- assert read_num_format == num_format
-
- def test_write_append_mode_raises(self, ext):
- msg = "Append mode is not supported with xlsxwriter!"
-
- with ensure_clean(ext) as f:
- with pytest.raises(ValueError, match=msg):
- ExcelWriter(f, engine='xlsxwriter', mode='a')
-
-
-class TestExcelWriterEngineTests:
-
- @pytest.mark.parametrize('klass,ext', [
- pytest.param(_XlsxWriter, '.xlsx', marks=pytest.mark.skipif(
- not td.safe_import('xlsxwriter'), reason='No xlsxwriter')),
- pytest.param(_OpenpyxlWriter, '.xlsx', marks=pytest.mark.skipif(
- not td.safe_import('openpyxl'), reason='No openpyxl')),
- pytest.param(_XlwtWriter, '.xls', marks=pytest.mark.skipif(
- not td.safe_import('xlwt'), reason='No xlwt'))
- ])
- def test_ExcelWriter_dispatch(self, klass, ext):
- with ensure_clean(ext) as path:
- writer = ExcelWriter(path)
- if ext == '.xlsx' and td.safe_import('xlsxwriter'):
- # xlsxwriter has preference over openpyxl if both installed
- assert isinstance(writer, _XlsxWriter)
- else:
- assert isinstance(writer, klass)
-
- def test_ExcelWriter_dispatch_raises(self):
- with pytest.raises(ValueError, match='No engine'):
- ExcelWriter('nothing')
-
- def test_register_writer(self):
- # some awkward mocking to test out dispatch and such actually works
- called_save = []
- called_write_cells = []
-
- class DummyClass(ExcelWriter):
- called_save = False
- called_write_cells = False
- supported_extensions = ['xlsx', 'xls']
- engine = 'dummy'
-
- def save(self):
- called_save.append(True)
-
- def write_cells(self, *args, **kwargs):
- called_write_cells.append(True)
-
- def check_called(func):
- func()
- assert len(called_save) >= 1
- assert len(called_write_cells) >= 1
- del called_save[:]
- del called_write_cells[:]
-
- with pd.option_context('io.excel.xlsx.writer', 'dummy'):
- register_writer(DummyClass)
- writer = ExcelWriter('something.xlsx')
- assert isinstance(writer, DummyClass)
- df = tm.makeCustomDataframe(1, 1)
- check_called(lambda: df.to_excel('something.xlsx'))
- check_called(
- lambda: df.to_excel(
- 'something.xls', engine='dummy'))
-
-
-@pytest.mark.parametrize('engine', [
- pytest.param('xlwt',
- marks=pytest.mark.xfail(reason='xlwt does not support '
- 'openpyxl-compatible '
- 'style dicts')),
- 'xlsxwriter',
- 'openpyxl',
-])
-def test_styler_to_excel(engine):
- def style(df):
- # XXX: RGB colors not supported in xlwt
- return DataFrame([['font-weight: bold', '', ''],
- ['', 'color: blue', ''],
- ['', '', 'text-decoration: underline'],
- ['border-style: solid', '', ''],
- ['', 'font-style: italic', ''],
- ['', '', 'text-align: right'],
- ['background-color: red', '', ''],
- ['number-format: 0%', '', ''],
- ['', '', ''],
- ['', '', ''],
- ['', '', '']],
- index=df.index, columns=df.columns)
-
- def assert_equal_style(cell1, cell2, engine):
- if engine in ['xlsxwriter', 'openpyxl']:
- pytest.xfail(reason=("GH25351: failing on some attribute "
- "comparisons in {}".format(engine)))
- # XXX: should find a better way to check equality
- assert cell1.alignment.__dict__ == cell2.alignment.__dict__
- assert cell1.border.__dict__ == cell2.border.__dict__
- assert cell1.fill.__dict__ == cell2.fill.__dict__
- assert cell1.font.__dict__ == cell2.font.__dict__
- assert cell1.number_format == cell2.number_format
- assert cell1.protection.__dict__ == cell2.protection.__dict__
-
- def custom_converter(css):
- # use bold iff there is custom style attached to the cell
- if css.strip(' \n;'):
- return {'font': {'bold': True}}
- return {}
-
- pytest.importorskip('jinja2')
- pytest.importorskip(engine)
-
- # Prepare spreadsheets
-
- df = DataFrame(np.random.randn(11, 3))
- with ensure_clean('.xlsx' if engine != 'xlwt' else '.xls') as path:
- writer = ExcelWriter(path, engine=engine)
- df.to_excel(writer, sheet_name='frame')
- df.style.to_excel(writer, sheet_name='unstyled')
- styled = df.style.apply(style, axis=None)
- styled.to_excel(writer, sheet_name='styled')
- ExcelFormatter(styled, style_converter=custom_converter).write(
- writer, sheet_name='custom')
- writer.save()
-
- if engine not in ('openpyxl', 'xlsxwriter'):
- # For other engines, we only smoke test
- return
- openpyxl = pytest.importorskip('openpyxl')
- wb = openpyxl.load_workbook(path)
-
- # (1) compare DataFrame.to_excel and Styler.to_excel when unstyled
- n_cells = 0
- for col1, col2 in zip(wb['frame'].columns,
- wb['unstyled'].columns):
- assert len(col1) == len(col2)
- for cell1, cell2 in zip(col1, col2):
- assert cell1.value == cell2.value
- assert_equal_style(cell1, cell2, engine)
- n_cells += 1
-
- # ensure iteration actually happened:
- assert n_cells == (11 + 1) * (3 + 1)
-
- # (2) check styling with default converter
-
- # XXX: openpyxl (as at 2.4) prefixes colors with 00, xlsxwriter with FF
- alpha = '00' if engine == 'openpyxl' else 'FF'
-
- n_cells = 0
- for col1, col2 in zip(wb['frame'].columns,
- wb['styled'].columns):
- assert len(col1) == len(col2)
- for cell1, cell2 in zip(col1, col2):
- ref = '%s%d' % (cell2.column, cell2.row)
- # XXX: this isn't as strong a test as ideal; we should
- # confirm that differences are exclusive
- if ref == 'B2':
- assert not cell1.font.bold
- assert cell2.font.bold
- elif ref == 'C3':
- assert cell1.font.color.rgb != cell2.font.color.rgb
- assert cell2.font.color.rgb == alpha + '0000FF'
- elif ref == 'D4':
- # This fails with engine=xlsxwriter due to
- # https://bitbucket.org/openpyxl/openpyxl/issues/800
- if engine == 'xlsxwriter' \
- and (LooseVersion(openpyxl.__version__) <
- LooseVersion('2.4.6')):
- pass
- else:
- assert cell1.font.underline != cell2.font.underline
- assert cell2.font.underline == 'single'
- elif ref == 'B5':
- assert not cell1.border.left.style
- assert (cell2.border.top.style ==
- cell2.border.right.style ==
- cell2.border.bottom.style ==
- cell2.border.left.style ==
- 'medium')
- elif ref == 'C6':
- assert not cell1.font.italic
- assert cell2.font.italic
- elif ref == 'D7':
- assert (cell1.alignment.horizontal !=
- cell2.alignment.horizontal)
- assert cell2.alignment.horizontal == 'right'
- elif ref == 'B8':
- assert cell1.fill.fgColor.rgb != cell2.fill.fgColor.rgb
- assert cell1.fill.patternType != cell2.fill.patternType
- assert cell2.fill.fgColor.rgb == alpha + 'FF0000'
- assert cell2.fill.patternType == 'solid'
- elif ref == 'B9':
- assert cell1.number_format == 'General'
- assert cell2.number_format == '0%'
- else:
- assert_equal_style(cell1, cell2, engine)
-
- assert cell1.value == cell2.value
- n_cells += 1
-
- assert n_cells == (11 + 1) * (3 + 1)
-
- # (3) check styling with custom converter
- n_cells = 0
- for col1, col2 in zip(wb['frame'].columns,
- wb['custom'].columns):
- assert len(col1) == len(col2)
- for cell1, cell2 in zip(col1, col2):
- ref = '%s%d' % (cell2.column, cell2.row)
- if ref in ('B2', 'C3', 'D4', 'B5', 'C6', 'D7', 'B8', 'B9'):
- assert not cell1.font.bold
- assert cell2.font.bold
- else:
- assert_equal_style(cell1, cell2, engine)
-
- assert cell1.value == cell2.value
- n_cells += 1
-
- assert n_cells == (11 + 1) * (3 + 1)
-
-
-@td.skip_if_no('openpyxl')
-@pytest.mark.skipif(not PY36, reason='requires fspath')
-class TestFSPath:
-
- def test_excelfile_fspath(self):
- with tm.ensure_clean('foo.xlsx') as path:
- df = DataFrame({"A": [1, 2]})
- df.to_excel(path)
- xl = ExcelFile(path)
- result = os.fspath(xl)
- assert result == path
-
- def test_excelwriter_fspath(self):
- with tm.ensure_clean('foo.xlsx') as path:
- writer = ExcelWriter(path)
- assert os.fspath(writer) == str(path)
| - [X] closes #24472
@simonjayhawkins
Just moved everything as is. Some of the class structures are unnecessary now but leaving for follow ups | https://api.github.com/repos/pandas-dev/pandas/pulls/26755 | 2019-06-09T15:18:50Z | 2019-06-09T21:51:12Z | 2019-06-09T21:51:12Z | 2019-06-10T02:27:44Z |
DOC: warning on look-ahead bias with resampling | diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst
index f559b0d073320..f27e9c677d925 100644
--- a/doc/source/user_guide/timeseries.rst
+++ b/doc/source/user_guide/timeseries.rst
@@ -761,34 +761,6 @@ regularity will result in a ``DatetimeIndex``, although frequency is lost:
ts2[[0, 2, 6]].index
-.. _timeseries.iterating-label:
-
-Iterating through groups
-------------------------
-
-With the ``Resampler`` object in hand, iterating through the grouped data is very
-natural and functions similarly to :py:func:`itertools.groupby`:
-
-.. ipython:: python
-
- small = pd.Series(
- range(6),
- index=pd.to_datetime(['2017-01-01T00:00:00',
- '2017-01-01T00:30:00',
- '2017-01-01T00:31:00',
- '2017-01-01T01:00:00',
- '2017-01-01T03:00:00',
- '2017-01-01T03:05:00'])
- )
- resampled = small.resample('H')
-
- for name, group in resampled:
- print("Group: ", name)
- print("-" * 27)
- print(group, end="\n\n")
-
-See :ref:`groupby.iterating-label` or :class:`Resampler.__iter__` for more.
-
.. _timeseries.components:
Time/Date Components
@@ -1628,24 +1600,32 @@ labels.
ts.resample('5Min', label='left', loffset='1s').mean()
-.. note::
+.. warning::
- The default values for ``label`` and ``closed`` is 'left' for all
+ The default values for ``label`` and ``closed`` is '**left**' for all
frequency offsets except for 'M', 'A', 'Q', 'BM', 'BA', 'BQ', and 'W'
which all have a default of 'right'.
+ This might unintendedly lead to looking ahead, where the value for a later
+ time is pulled back to a previous time as in the following example with
+ the :class:`~pandas.tseries.offsets.BusinessDay` frequency:
+
.. ipython:: python
- rng2 = pd.date_range('1/1/2012', end='3/31/2012', freq='D')
- ts2 = pd.Series(range(len(rng2)), index=rng2)
+ s = pd.date_range('2000-01-01', '2000-01-05').to_series()
+ s.iloc[2] = pd.NaT
+ s.dt.weekday_name
- # default: label='right', closed='right'
- ts2.resample('M').max()
+ # default: label='left', closed='left'
+ s.resample('B').last().dt.weekday_name
- # default: label='left', closed='left'
- ts2.resample('SM').max()
+ Notice how the value for Sunday got pulled back to the previous Friday.
+ To get the behavior where the value for Sunday is pushed to Monday, use
+ instead
- ts2.resample('SM', label='right', closed='right').max()
+ .. ipython:: python
+
+ s.resample('B', label='right', closed='right').last().dt.weekday_name
The ``axis`` parameter can be set to 0 or 1 and allows you to resample the
specified axis for a ``DataFrame``.
@@ -1796,6 +1776,34 @@ level of ``MultiIndex``, its name or location can be passed to the
df.resample('M', level='d').sum()
+.. _timeseries.iterating-label:
+
+Iterating through groups
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+With the ``Resampler`` object in hand, iterating through the grouped data is very
+natural and functions similarly to :py:func:`itertools.groupby`:
+
+.. ipython:: python
+
+ small = pd.Series(
+ range(6),
+ index=pd.to_datetime(['2017-01-01T00:00:00',
+ '2017-01-01T00:30:00',
+ '2017-01-01T00:31:00',
+ '2017-01-01T01:00:00',
+ '2017-01-01T03:00:00',
+ '2017-01-01T03:05:00'])
+ )
+ resampled = small.resample('H')
+
+ for name, group in resampled:
+ print("Group: ", name)
+ print("-" * 27)
+ print(group, end="\n\n")
+
+See :ref:`groupby.iterating-label` or :class:`Resampler.__iter__` for more.
+
.. _timeseries.periods:
| - [x] closes #11123
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26754 | 2019-06-09T14:03:32Z | 2019-06-12T18:52:30Z | 2019-06-12T18:52:30Z | 2019-06-12T18:52:34Z |
PLOT: Add option to specify the plotting backend | diff --git a/doc/source/user_guide/options.rst b/doc/source/user_guide/options.rst
index 4b466c2c44d49..4d0def435cb1e 100644
--- a/doc/source/user_guide/options.rst
+++ b/doc/source/user_guide/options.rst
@@ -431,6 +431,12 @@ compute.use_bottleneck True Use the bottleneck library
computation if it is installed.
compute.use_numexpr True Use the numexpr library to accelerate
computation if it is installed.
+plotting.backend matplotlib Change the plotting backend to a different
+ backend than the current matplotlib one.
+ Backends can be implemented as third-party
+ libraries implementing the pandas plotting
+ API. They can use other plotting libraries
+ like Bokeh, Altair, etc.
plotting.matplotlib.register_converters True Register custom converters with
matplotlib. Set to False to de-register.
======================================= ============ ==================================
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index a897f364d8066..77b689569d57f 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -132,6 +132,7 @@ Other Enhancements
- :class:`DatetimeIndex` and :class:`TimedeltaIndex` now have a ``mean`` method (:issue:`24757`)
- :meth:`DataFrame.describe` now formats integer percentiles without decimal point (:issue:`26660`)
- Added support for reading SPSS .sav files using :func:`read_spss` (:issue:`26537`)
+- Added new option ``plotting.backend`` to be able to select a plotting backend different than the existing ``matplotlib`` one. Use ``pandas.set_option('plotting.backend', '<backend-module>')`` where ``<backend-module`` is a library implementing the pandas plotting API (:issue:`14130`)
.. _whatsnew_0250.api_breaking:
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index 7eb2b413822d9..4409267147b65 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -9,6 +9,8 @@
module is imported, register them here rather then in the module.
"""
+import importlib
+
import pandas._config.config as cf
from pandas._config.config import (
is_bool, is_callable, is_instance_factory, is_int, is_one_of_factory,
@@ -460,6 +462,40 @@ def use_inf_as_na_cb(key):
# Plotting
# ---------
+plotting_backend_doc = """
+: str
+ The plotting backend to use. The default value is "matplotlib", the
+ backend provided with pandas. Other backends can be specified by
+ prodiving the name of the module that implements the backend.
+"""
+
+
+def register_plotting_backend_cb(key):
+ backend_str = cf.get_option(key)
+ if backend_str == 'matplotlib':
+ try:
+ import pandas.plotting._matplotlib # noqa
+ except ImportError:
+ raise ImportError('matplotlib is required for plotting when the '
+ 'default backend "matplotlib" is selected.')
+ else:
+ return
+
+ try:
+ importlib.import_module(backend_str)
+ except ImportError:
+ raise ValueError('"{}" does not seem to be an installed module. '
+ 'A pandas plotting backend must be a module that '
+ 'can be imported'.format(backend_str))
+
+
+with cf.config_prefix('plotting'):
+ cf.register_option('backend', defval='matplotlib',
+ doc=plotting_backend_doc,
+ validator=str,
+ cb=register_plotting_backend_cb)
+
+
register_converter_doc = """
: bool
Whether to register converters with matplotlib's units registry for
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index 78c7082c69b6b..b0e928fa8022b 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -1,3 +1,4 @@
+import importlib
from typing import List, Type # noqa
from pandas.util._decorators import Appender
@@ -5,6 +6,7 @@
from pandas.core.dtypes.common import is_integer, is_list_like
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+import pandas
from pandas.core.base import PandasObject
from pandas.core.generic import _shared_doc_kwargs, _shared_docs
@@ -622,11 +624,10 @@ def _get_plot_backend():
The backend is imported lazily, as matplotlib is a soft dependency, and
pandas can be used without it being installed.
"""
- try:
- import pandas.plotting._matplotlib as plot_backend
- except ImportError:
- raise ImportError("matplotlib is required for plotting.")
- return plot_backend
+ backend_str = pandas.get_option('plotting.backend')
+ if backend_str == 'matplotlib':
+ backend_str = 'pandas.plotting._matplotlib'
+ return importlib.import_module(backend_str)
def _plot_classes():
diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py
index a3f3f354690df..f240faf45dfce 100644
--- a/pandas/plotting/_misc.py
+++ b/pandas/plotting/_misc.py
@@ -3,14 +3,7 @@
from pandas.util._decorators import deprecate_kwarg
-
-def _get_plot_backend():
- # TODO unify with the same function in `_core.py`
- try:
- import pandas.plotting._matplotlib as plot_backend
- except ImportError:
- raise ImportError("matplotlib is required for plotting.")
- return plot_backend
+from pandas.plotting._core import _get_plot_backend
def table(ax, data, rowLabels=None, colLabels=None, **kwargs):
diff --git a/pandas/tests/plotting/test_backend.py b/pandas/tests/plotting/test_backend.py
new file mode 100644
index 0000000000000..65e1d690d5f8f
--- /dev/null
+++ b/pandas/tests/plotting/test_backend.py
@@ -0,0 +1,33 @@
+import pytest
+
+import pandas
+
+
+def test_matplotlib_backend_error():
+ msg = ('matplotlib is required for plotting when the default backend '
+ '"matplotlib" is selected.')
+ try:
+ import matplotlib # noqa
+ except ImportError:
+ with pytest.raises(ImportError, match=msg):
+ pandas.set_option('plotting.backend', 'matplotlib')
+
+
+def test_backend_is_not_module():
+ msg = ('"not_an_existing_module" does not seem to be an installed module. '
+ 'A pandas plotting backend must be a module that can be imported')
+ with pytest.raises(ValueError, match=msg):
+ pandas.set_option('plotting.backend', 'not_an_existing_module')
+
+
+def test_backend_is_correct(monkeypatch):
+ monkeypatch.setattr('pandas.core.config_init.importlib.import_module',
+ lambda name: None)
+ pandas.set_option('plotting.backend', 'correct_backend')
+ assert pandas.get_option('plotting.backend') == 'correct_backend'
+
+ # Restore backend for other tests (matplotlib can be not installed)
+ try:
+ pandas.set_option('plotting.backend', 'matplotlib')
+ except ImportError:
+ pass
diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py
index a1c12fc73362a..b58854743a42d 100644
--- a/pandas/tests/plotting/test_misc.py
+++ b/pandas/tests/plotting/test_misc.py
@@ -21,7 +21,7 @@ def test_import_error_message():
# GH-19810
df = DataFrame({"A": [1, 2]})
- with pytest.raises(ImportError, match='matplotlib is required'):
+ with pytest.raises(ImportError, match="No module named 'matplotlib'"):
df.plot()
| - [x] closes #14130
- [x] tets added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Adding option to specify the plotting backend. This does not change the plotting API, so for now backends are expected to implement the existing methods in the matplotlib API. This API is expected to change as a result of the discussions in #26747.
| https://api.github.com/repos/pandas-dev/pandas/pulls/26753 | 2019-06-09T11:33:34Z | 2019-06-21T09:37:18Z | 2019-06-21T09:37:18Z | 2019-06-21T09:37:18Z |
DOC: Skip creating redirects if docs build fails | diff --git a/doc/make.py b/doc/make.py
index 6ffbd3ef86e68..496b3cfd4ee45 100755
--- a/doc/make.py
+++ b/doc/make.py
@@ -220,10 +220,11 @@ def html(self):
if os.path.exists(zip_fname):
os.remove(zip_fname)
- if self.single_doc_html is not None:
- self._open_browser(self.single_doc_html)
- else:
- self._add_redirects()
+ if ret_code == 0:
+ if self.single_doc_html is not None:
+ self._open_browser(self.single_doc_html)
+ else:
+ self._add_redirects()
return ret_code
def latex(self, force=False):
| When the doc build fails, we still try to create the redirected pages, which fails, and adds to the log a misleading error (it looks in the logs like the problem is not the original error but that something is failing in the redirects).
See for example https://travis-ci.org/pandas-dev/pandas/jobs/542714631:
```
Recursion error:
maximum recursion depth exceeded while calling a Python object
This can happen with very large or deeply nested source files. You can carefully increase the default Python recursion limit of 1000 in conf.py with e.g.:
import sys; sys.setrecursionlimit(1500)
Traceback (most recent call last):
File "./make.py", line 341, in <module>
sys.exit(main())
File "./make.py", line 337, in main
return getattr(builder, args.command)()
File "./make.py", line 226, in html
self._add_redirects()
File "./make.py", line 209, in _add_redirects
with open(path, 'w') as moved_page_fd:
FileNotFoundError: [Errno 2] No such file or directory: '/home/travis/build/pandas-dev/pandas/doc/build/html/generated/pandas.api.extensions.ExtensionArray.argsort.html'
```
Here I make the redirects be created only if the doc build succeeded. Also opening the browser if we're building a single page. | https://api.github.com/repos/pandas-dev/pandas/pulls/26752 | 2019-06-09T10:00:01Z | 2019-06-09T21:51:39Z | 2019-06-09T21:51:39Z | 2019-06-09T21:51:58Z |
move late imports to top | diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py
index c1a48ad5ca08b..b8a7da5270fc0 100644
--- a/pandas/plotting/_matplotlib/boxplot.py
+++ b/pandas/plotting/_matplotlib/boxplot.py
@@ -2,11 +2,14 @@
import warnings
from matplotlib import pyplot as plt
+from matplotlib.artist import setp
import numpy as np
from pandas.core.dtypes.generic import ABCSeries
from pandas.core.dtypes.missing import remove_na_arraylike
+import pandas as pd
+
from pandas.io.formats.printing import pprint_thing
from pandas.plotting._matplotlib.core import LinePlot, MPLPlot
from pandas.plotting._matplotlib.style import _get_standard_colors
@@ -105,7 +108,6 @@ def maybe_color_bp(self, bp):
medians = self.color or self._medians_c
caps = self.color or self._caps_c
- from matplotlib.artist import setp
setp(bp['boxes'], color=boxes, alpha=1)
setp(bp['whiskers'], color=whiskers, alpha=1)
setp(bp['medians'], color=medians, alpha=1)
@@ -113,8 +115,7 @@ def maybe_color_bp(self, bp):
def _make_plot(self):
if self.subplots:
- from pandas.core.series import Series
- self._return_obj = Series()
+ self._return_obj = pd.Series()
for i, (label, y) in enumerate(self._iter_data()):
ax = self._get_ax(i)
@@ -197,8 +198,7 @@ def _grouped_plot_by_column(plotf, data, columns=None, by=None,
ax_values.append(re_plotf)
ax.grid(grid)
- from pandas.core.series import Series
- result = Series(ax_values, index=columns)
+ result = pd.Series(ax_values, index=columns)
# Return axes in multiplot case, maybe revisit later # 985
if return_type is None:
@@ -230,7 +230,6 @@ def _get_colors():
def maybe_color_bp(bp):
if 'color' not in kwds:
- from matplotlib.artist import setp
setp(bp['boxes'], color=colors[0], alpha=1)
setp(bp['whiskers'], color=colors[0], alpha=1)
setp(bp['medians'], color=colors[2], alpha=1)
@@ -314,8 +313,7 @@ def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None,
figsize=figsize, layout=layout)
axes = _flatten(axes)
- from pandas.core.series import Series
- ret = Series()
+ ret = pd.Series()
for (key, group), ax in zip(grouped, axes):
d = group.boxplot(ax=ax, column=column, fontsize=fontsize,
rot=rot, grid=grid, **kwds)
@@ -324,10 +322,9 @@ def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None,
fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1,
right=0.9, wspace=0.2)
else:
- from pandas.core.reshape.concat import concat
keys, frames = zip(*grouped)
if grouped.axis == 0:
- df = concat(frames, keys=keys, axis=1)
+ df = pd.concat(frames, keys=keys, axis=1)
else:
if len(frames) > 1:
df = frames[0].join(frames[1::])
diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py
index 7a04d48da434d..dacc9ef04f819 100644
--- a/pandas/plotting/_matplotlib/misc.py
+++ b/pandas/plotting/_matplotlib/misc.py
@@ -1,4 +1,7 @@
-# being a bit too dynamic
+import random
+
+import matplotlib.lines as mlines
+import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
@@ -96,14 +99,12 @@ def scatter_matrix(frame, alpha=0.5, figsize=None, ax=None, grid=False,
def _get_marker_compat(marker):
- import matplotlib.lines as mlines
if marker not in mlines.lineMarkers:
return 'o'
return marker
def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds):
- import matplotlib.patches as patches
def normalize(series):
a = min(series)
@@ -168,12 +169,11 @@ def normalize(series):
def andrews_curves(frame, class_column, ax=None, samples=200, color=None,
colormap=None, **kwds):
- from math import sqrt, pi
def function(amplitudes):
def f(t):
x1 = amplitudes[0]
- result = x1 / sqrt(2.0)
+ result = x1 / np.sqrt(2.0)
# Take the rest of the coefficients and resize them
# appropriately. Take a copy of amplitudes as otherwise numpy
@@ -196,7 +196,7 @@ def f(t):
class_col = frame[class_column]
classes = frame[class_column].drop_duplicates()
df = frame.drop(class_column, axis=1)
- t = np.linspace(-pi, pi, samples)
+ t = np.linspace(-np.pi, np.pi, samples)
used_legends = set()
color_values = _get_standard_colors(num_colors=len(classes),
@@ -204,7 +204,7 @@ def f(t):
color=color)
colors = dict(zip(classes, color_values))
if ax is None:
- ax = plt.gca(xlim=(-pi, pi))
+ ax = plt.gca(xlim=(-np.pi, np.pi))
for i in range(n):
row = df.iloc[i].values
f = function(row)
@@ -223,7 +223,6 @@ def f(t):
def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds):
- import random
# random.sample(ndarray, int) fails on python 3.3, sigh
data = list(series.values)
diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py
index ef7bbd2f05703..80a15942a2867 100644
--- a/pandas/plotting/_matplotlib/style.py
+++ b/pandas/plotting/_matplotlib/style.py
@@ -1,17 +1,20 @@
# being a bit too dynamic
import warnings
+import matplotlib.cm as cm
+import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np
from pandas.core.dtypes.common import is_list_like
+import pandas.core.common as com
+
def _get_standard_colors(num_colors=None, colormap=None, color_type='default',
color=None):
if color is None and colormap is not None:
if isinstance(colormap, str):
- import matplotlib.cm as cm
cmap = colormap
colormap = cm.get_cmap(colormap)
if colormap is None:
@@ -37,7 +40,6 @@ def _get_standard_colors(num_colors=None, colormap=None, color_type='default',
colors = colors[0:num_colors]
elif color_type == 'random':
- import pandas.core.common as com
def random_color(column):
""" Returns a random color represented as a list of length 3"""
@@ -50,7 +52,6 @@ def random_color(column):
raise ValueError("color_type must be either 'default' or 'random'")
if isinstance(colors, str):
- import matplotlib.colors
conv = matplotlib.colors.ColorConverter()
def _maybe_valid_colors(colors):
diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py
index 37e025b594ef2..30038b599a386 100644
--- a/pandas/plotting/_matplotlib/timeseries.py
+++ b/pandas/plotting/_matplotlib/timeseries.py
@@ -1,6 +1,7 @@
# TODO: Use the fact that axis can have units to simplify the process
import functools
+import warnings
from matplotlib import pylab
import matplotlib.pyplot as plt
@@ -25,7 +26,6 @@
def tsplot(series, plotf, ax=None, **kwargs):
- import warnings
"""
Plots a Series on the given Matplotlib axes or the current axes
diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py
index e0caab6211ce3..f6393fc76892f 100644
--- a/pandas/plotting/_matplotlib/tools.py
+++ b/pandas/plotting/_matplotlib/tools.py
@@ -3,6 +3,8 @@
import warnings
import matplotlib.pyplot as plt
+import matplotlib.table
+import matplotlib.ticker as ticker
import numpy as np
from pandas.core.dtypes.common import is_list_like
@@ -37,7 +39,6 @@ def table(ax, data, rowLabels=None, colLabels=None, **kwargs):
cellText = data.values
- import matplotlib.table
table = matplotlib.table.table(ax, cellText=cellText,
rowLabels=rowLabels,
colLabels=colLabels, **kwargs)
@@ -260,7 +261,6 @@ def _remove_labels_from_axis(axis):
try:
# set_visible will not be effective if
# minor axis has NullLocator and NullFormattor (default)
- import matplotlib.ticker as ticker
if isinstance(axis.get_minor_locator(), ticker.NullLocator):
axis.set_minor_locator(ticker.AutoLocator())
if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
| - [x] closes #26748
- [ ] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26750 | 2019-06-09T01:09:33Z | 2019-06-11T18:46:38Z | 2019-06-11T18:46:38Z | 2019-06-11T18:46:45Z |
STYLE: Isort __init__ files | diff --git a/pandas/_libs/__init__.py b/pandas/_libs/__init__.py
index 1f6042389416e..fcf5ffbfcad92 100644
--- a/pandas/_libs/__init__.py
+++ b/pandas/_libs/__init__.py
@@ -1,4 +1,4 @@
# flake8: noqa
from .tslibs import (
- iNaT, NaT, NaTType, Timestamp, Timedelta, OutOfBoundsDatetime, Period)
+ NaT, NaTType, OutOfBoundsDatetime, Period, Timedelta, Timestamp, iNaT)
diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py
index 21ba0ae06a036..67a323782a836 100644
--- a/pandas/_libs/tslibs/__init__.py
+++ b/pandas/_libs/tslibs/__init__.py
@@ -1,9 +1,9 @@
# flake8: noqa
-from .conversion import normalize_date, localize_pydatetime
+from .conversion import localize_pydatetime, normalize_date
from .nattype import NaT, NaTType, iNaT, is_null_datetimelike
from .np_datetime import OutOfBoundsDatetime
-from .period import Period, IncompatibleFrequency
+from .period import IncompatibleFrequency, Period
+from .timedeltas import Timedelta, delta_to_nanoseconds, ints_to_pytimedelta
from .timestamps import Timestamp
-from .timedeltas import delta_to_nanoseconds, ints_to_pytimedelta, Timedelta
from .tzconversion import tz_convert_single
diff --git a/pandas/api/__init__.py b/pandas/api/__init__.py
index afff059e7b601..58422811990c4 100644
--- a/pandas/api/__init__.py
+++ b/pandas/api/__init__.py
@@ -1,2 +1,2 @@
""" public toolkit API """
-from . import types, extensions # noqa
+from . import extensions, types # noqa
diff --git a/pandas/api/extensions/__init__.py b/pandas/api/extensions/__init__.py
index cb6241016d82f..0bd2733cb494c 100644
--- a/pandas/api/extensions/__init__.py
+++ b/pandas/api/extensions/__init__.py
@@ -1,10 +1,12 @@
"""Public API for extending pandas objects."""
-from pandas.core.accessor import (register_dataframe_accessor, # noqa
- register_index_accessor,
- register_series_accessor)
-from pandas.core.algorithms import take # noqa
-from pandas.core.arrays import (ExtensionArray, # noqa
- ExtensionScalarOpsMixin)
-from pandas.core.dtypes.dtypes import ( # noqa
- ExtensionDtype, register_extension_dtype
-)
+from pandas.core.dtypes.dtypes import ( # noqa: F401
+ ExtensionDtype, register_extension_dtype)
+
+from pandas.core.accessor import ( # noqa: F401
+ register_index_accessor, register_series_accessor)
+from pandas.core.algorithms import take # noqa: F401
+from pandas.core.arrays import ( # noqa: F401
+ ExtensionArray, ExtensionScalarOpsMixin)
+
+from pandas.core.accessor import ( # noqa: F401; noqa: F401
+ register_dataframe_accessor)
diff --git a/pandas/api/types/__init__.py b/pandas/api/types/__init__.py
index 438e4afa3f580..668f79921d8e6 100644
--- a/pandas/api/types/__init__.py
+++ b/pandas/api/types/__init__.py
@@ -1,9 +1,8 @@
""" public toolkit API """
-from pandas.core.dtypes.api import * # noqa
-from pandas.core.dtypes.dtypes import (CategoricalDtype, # noqa
- DatetimeTZDtype,
- PeriodDtype,
- IntervalDtype)
-from pandas.core.dtypes.concat import union_categoricals # noqa
-from pandas._libs.lib import infer_dtype # noqa
+from pandas._libs.lib import infer_dtype # noqa: F401
+
+from pandas.core.dtypes.api import * # noqa: F403, F401
+from pandas.core.dtypes.concat import union_categoricals # noqa: F401
+from pandas.core.dtypes.dtypes import ( # noqa: F401
+ CategoricalDtype, DatetimeTZDtype, IntervalDtype, PeriodDtype)
diff --git a/pandas/arrays/__init__.py b/pandas/arrays/__init__.py
index 7d9b1b7c7a659..ab014d49236b3 100644
--- a/pandas/arrays/__init__.py
+++ b/pandas/arrays/__init__.py
@@ -4,12 +4,8 @@
See :ref:`extending.extension-types` for more.
"""
from pandas.core.arrays import (
- IntervalArray, PeriodArray, Categorical, SparseArray, IntegerArray,
- PandasArray,
- DatetimeArray,
- TimedeltaArray,
-)
-
+ Categorical, DatetimeArray, IntegerArray, IntervalArray, PandasArray,
+ PeriodArray, SparseArray, TimedeltaArray)
__all__ = [
'Categorical',
diff --git a/pandas/core/arrays/__init__.py b/pandas/core/arrays/__init__.py
index 1033ce784046e..2d09a9eac6eab 100644
--- a/pandas/core/arrays/__init__.py
+++ b/pandas/core/arrays/__init__.py
@@ -1,13 +1,11 @@
-from .array_ import array # noqa
-from .base import (ExtensionArray, # noqa
- ExtensionOpsMixin,
- ExtensionScalarOpsMixin)
-from .categorical import Categorical # noqa
-from .datetimes import DatetimeArray # noqa
-from .interval import IntervalArray # noqa
-from .period import PeriodArray, period_array # noqa
-from .timedeltas import TimedeltaArray # noqa
-from .integer import ( # noqa
- IntegerArray, integer_array)
-from .sparse import SparseArray # noqa
-from .numpy_ import PandasArray, PandasDtype # noqa
+from .array_ import array # noqa: F401
+from .base import ( # noqa: F401
+ ExtensionArray, ExtensionOpsMixin, ExtensionScalarOpsMixin)
+from .categorical import Categorical # noqa: F401
+from .datetimes import DatetimeArray # noqa: F401
+from .integer import IntegerArray, integer_array # noqa: F401
+from .interval import IntervalArray # noqa: F401
+from .numpy_ import PandasArray, PandasDtype # noqa: F401
+from .period import PeriodArray, period_array # noqa: F401
+from .sparse import SparseArray # noqa: F401
+from .timedeltas import TimedeltaArray # noqa: F401
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index fd2e1e3e41ced..df7003ecf000e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -14,93 +14,61 @@
from io import StringIO
import itertools
import sys
-import warnings
from textwrap import dedent
from typing import FrozenSet, List, Optional, Set, Type, Union
+import warnings
import numpy as np
import numpy.ma as ma
from pandas._config import get_option
-from pandas._libs import lib, algos as libalgos
-
-from pandas.util._decorators import (Appender, Substitution,
- rewrite_axis_style_signature,
- deprecate_kwarg)
-from pandas.util._validators import (validate_bool_kwarg,
- validate_axis_style_args)
-
+from pandas._libs import algos as libalgos, lib
from pandas.compat import PY36, raise_with_traceback
from pandas.compat.numpy import function as nv
-from pandas.core.arrays.sparse import SparseFrameAccessor
+from pandas.util._decorators import (
+ Appender, Substitution, deprecate_kwarg, rewrite_axis_style_signature)
+from pandas.util._validators import (
+ validate_axis_style_args, validate_bool_kwarg)
+
from pandas.core.dtypes.cast import (
- maybe_upcast,
- cast_scalar_to_array,
- infer_dtype_from_scalar,
- maybe_cast_to_datetime,
- maybe_infer_to_datetimelike,
- maybe_convert_platform,
- maybe_downcast_to_dtype,
- invalidate_string_dtypes,
- coerce_to_dtypes,
- maybe_upcast_putmask,
- find_common_type)
+ cast_scalar_to_array, coerce_to_dtypes, find_common_type,
+ infer_dtype_from_scalar, invalidate_string_dtypes, maybe_cast_to_datetime,
+ maybe_convert_platform, maybe_downcast_to_dtype,
+ maybe_infer_to_datetimelike, maybe_upcast, maybe_upcast_putmask)
from pandas.core.dtypes.common import (
- is_dict_like,
- is_datetime64tz_dtype,
- is_object_dtype,
- is_extension_type,
- is_extension_array_dtype,
- is_datetime64_any_dtype,
- is_bool_dtype,
- is_integer_dtype,
- is_float_dtype,
- is_integer,
- is_scalar,
- is_dtype_equal,
- needs_i8_conversion,
- infer_dtype_from_object,
- ensure_float64,
- ensure_int64,
- ensure_platform_int,
- is_list_like,
- is_nested_list_like,
- is_iterator,
- is_sequence,
- is_named_tuple)
+ ensure_float64, ensure_int64, ensure_platform_int, infer_dtype_from_object,
+ is_bool_dtype, is_datetime64_any_dtype, is_datetime64tz_dtype,
+ is_dict_like, is_dtype_equal, is_extension_array_dtype, is_extension_type,
+ is_float_dtype, is_integer, is_integer_dtype, is_iterator, is_list_like,
+ is_named_tuple, is_nested_list_like, is_object_dtype, is_scalar,
+ is_sequence, needs_i8_conversion)
from pandas.core.dtypes.generic import (
- ABCSeries, ABCDataFrame, ABCIndexClass, ABCMultiIndex)
+ ABCDataFrame, ABCIndexClass, ABCMultiIndex, ABCSeries)
from pandas.core.dtypes.missing import isna, notna
-from pandas.core import algorithms
-from pandas.core import common as com
-from pandas.core import nanops
-from pandas.core import ops
+from pandas.core import algorithms, common as com, nanops, ops
from pandas.core.accessor import CachedAccessor
from pandas.core.arrays import Categorical, ExtensionArray
from pandas.core.arrays.datetimelike import (
- DatetimeLikeArrayMixin as DatetimeLikeArray
-)
+ DatetimeLikeArrayMixin as DatetimeLikeArray)
+from pandas.core.arrays.sparse import SparseFrameAccessor
from pandas.core.generic import NDFrame, _shared_docs
-from pandas.core.index import (Index, MultiIndex, ensure_index,
- ensure_index_from_sequences)
+from pandas.core.index import (
+ Index, MultiIndex, ensure_index, ensure_index_from_sequences)
from pandas.core.indexes import base as ibase
from pandas.core.indexes.datetimes import DatetimeIndex
from pandas.core.indexes.period import PeriodIndex
-from pandas.core.indexing import (maybe_droplevels, convert_to_index_sliceable,
- check_bool_indexer)
+from pandas.core.indexing import (
+ check_bool_indexer, convert_to_index_sliceable, maybe_droplevels)
from pandas.core.internals import BlockManager
from pandas.core.internals.construction import (
- masked_rec_array_to_mgr, get_names_from_index, to_arrays,
- reorder_arrays, init_ndarray, init_dict,
- arrays_to_mgr, sanitize_index)
+ arrays_to_mgr, get_names_from_index, init_dict, init_ndarray,
+ masked_rec_array_to_mgr, reorder_arrays, sanitize_index, to_arrays)
from pandas.core.series import Series
-from pandas.io.formats import console
-from pandas.io.formats import format as fmt
+from pandas.io.formats import console, format as fmt
from pandas.io.formats.printing import pprint_thing
-
import pandas.plotting
# ---------------------------------------------------------------------
diff --git a/pandas/core/internals/__init__.py b/pandas/core/internals/__init__.py
index d24dd2edd4e1d..b9530e15f71e2 100644
--- a/pandas/core/internals/__init__.py
+++ b/pandas/core/internals/__init__.py
@@ -1,12 +1,15 @@
-from .blocks import ( # noqa:F401
- _block_shape, # io.pytables
- _safe_reshape, # io.packers
- make_block, # io.pytables, io.packers
- FloatBlock, IntBlock, ComplexBlock, BoolBlock, ObjectBlock,
- TimeDeltaBlock, DatetimeBlock, DatetimeTZBlock,
- CategoricalBlock, ExtensionBlock, Block)
-from .managers import ( # noqa:F401
- BlockManager, SingleBlockManager,
- create_block_manager_from_arrays, create_block_manager_from_blocks,
- items_overlap_with_suffix, # reshape.merge
- concatenate_block_managers) # reshape.concat, reshape.merge
+from .blocks import ( # noqa: F401
+ Block, BoolBlock, CategoricalBlock, ComplexBlock, DatetimeBlock,
+ DatetimeTZBlock, ExtensionBlock, FloatBlock, IntBlock, ObjectBlock,
+ TimeDeltaBlock)
+from .managers import ( # noqa: F401
+ BlockManager, SingleBlockManager, create_block_manager_from_arrays,
+ create_block_manager_from_blocks)
+
+from .blocks import _safe_reshape # noqa: F401; io.packers
+from .blocks import make_block # noqa: F401; io.pytables, io.packers
+from .managers import ( # noqa: F401; reshape.concat, reshape.merge
+ concatenate_block_managers)
+from .managers import items_overlap_with_suffix # noqa: F401; reshape.merge
+
+from .blocks import _block_shape # noqa:F401; io.pytables
diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py
index 2063978c76c5a..e033d882a73f7 100644
--- a/pandas/io/clipboard/__init__.py
+++ b/pandas/io/clipboard/__init__.py
@@ -25,12 +25,13 @@
"""
__version__ = '1.5.27'
-import platform
import os
+import platform
import subprocess
+
from .clipboards import (
- init_osx_clipboard, init_qt_clipboard, init_xclip_clipboard,
- init_xsel_clipboard, init_klipper_clipboard, init_no_clipboard)
+ init_klipper_clipboard, init_no_clipboard, init_osx_clipboard,
+ init_qt_clipboard, init_xclip_clipboard, init_xsel_clipboard)
from .windows import init_windows_clipboard
# `import qtpy` sys.exit()s if DISPLAY is not in the environment.
diff --git a/pandas/io/excel/__init__.py b/pandas/io/excel/__init__.py
index 704789cb6061e..455abaa7fb589 100644
--- a/pandas/io/excel/__init__.py
+++ b/pandas/io/excel/__init__.py
@@ -1,4 +1,4 @@
-from pandas.io.excel._base import read_excel, ExcelWriter, ExcelFile
+from pandas.io.excel._base import ExcelFile, ExcelWriter, read_excel
from pandas.io.excel._openpyxl import _OpenpyxlWriter
from pandas.io.excel._util import register_writer
from pandas.io.excel._xlsxwriter import _XlsxWriter
diff --git a/pandas/io/json/__init__.py b/pandas/io/json/__init__.py
index 32d110b3404a9..cbb4e37fae6a1 100644
--- a/pandas/io/json/__init__.py
+++ b/pandas/io/json/__init__.py
@@ -1,4 +1,4 @@
-from .json import to_json, read_json, loads, dumps # noqa
+from .json import dumps, loads, read_json, to_json # noqa
from .normalize import json_normalize # noqa
from .table_schema import build_table_schema # noqa
diff --git a/pandas/tests/extension/base/__init__.py b/pandas/tests/extension/base/__init__.py
index 1f7ee2ae17e4a..0b3f2b860c127 100644
--- a/pandas/tests/extension/base/__init__.py
+++ b/pandas/tests/extension/base/__init__.py
@@ -46,11 +46,13 @@ class TestMyDtype(BaseDtypeTests):
from .getitem import BaseGetitemTests # noqa
from .groupby import BaseGroupbyTests # noqa
from .interface import BaseInterfaceTests # noqa
+from .io import BaseParsingTests # noqa
from .methods import BaseMethodsTests # noqa
-from .ops import BaseArithmeticOpsTests, BaseComparisonOpsTests, BaseOpsUtil # noqa
-from .printing import BasePrintingTests # noqa
-from .reduce import BaseNoReduceTests, BaseNumericReduceTests, BaseBooleanReduceTests # noqa
from .missing import BaseMissingTests # noqa
+from .ops import ( # noqa
+ BaseArithmeticOpsTests, BaseComparisonOpsTests, BaseOpsUtil)
+from .printing import BasePrintingTests # noqa
+from .reduce import ( # noqa
+ BaseBooleanReduceTests, BaseNoReduceTests, BaseNumericReduceTests)
from .reshaping import BaseReshapingTests # noqa
from .setitem import BaseSetitemTests # noqa
-from .io import BaseParsingTests # noqa
diff --git a/pandas/tests/extension/decimal/__init__.py b/pandas/tests/extension/decimal/__init__.py
index c37aad0af8407..7c48e7e71503e 100644
--- a/pandas/tests/extension/decimal/__init__.py
+++ b/pandas/tests/extension/decimal/__init__.py
@@ -1,4 +1,3 @@
-from .array import DecimalArray, DecimalDtype, to_decimal, make_data
-
+from .array import DecimalArray, DecimalDtype, make_data, to_decimal
__all__ = ['DecimalArray', 'DecimalDtype', 'to_decimal', 'make_data']
diff --git a/pandas/util/__init__.py b/pandas/util/__init__.py
index 202e58c916e47..9600109f01534 100644
--- a/pandas/util/__init__.py
+++ b/pandas/util/__init__.py
@@ -1,2 +1,4 @@
-from pandas.util._decorators import Appender, Substitution, cache_readonly # noqa
-from pandas.core.util.hashing import hash_pandas_object, hash_array # noqa
+from pandas.util._decorators import ( # noqa
+ Appender, Substitution, cache_readonly)
+
+from pandas.core.util.hashing import hash_array, hash_pandas_object # noqa
diff --git a/setup.cfg b/setup.cfg
index eb687c1f546d4..77dc043042f79 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -119,8 +119,9 @@ combine_as_imports=True
force_sort_within_sections=True
skip_glob=env,
skip=
+ pandas/__init__.py
pandas/core/api.py,
- pandas/core/frame.py,
+ pandas/io/msgpack/__init__.py
asv_bench/benchmarks/attrs_caching.py,
asv_bench/benchmarks/binary_ops.py,
asv_bench/benchmarks/categoricals.py,
@@ -159,23 +160,3 @@ skip=
asv_bench/benchmarks/dtypes.py
asv_bench/benchmarks/strings.py
asv_bench/benchmarks/period.py
- pandas/__init__.py
- pandas/plotting/__init__.py
- pandas/tests/extension/decimal/__init__.py
- pandas/tests/extension/base/__init__.py
- pandas/io/msgpack/__init__.py
- pandas/io/json/__init__.py
- pandas/io/clipboard/__init__.py
- pandas/io/excel/__init__.py
- pandas/compat/__init__.py
- pandas/compat/numpy/__init__.py
- pandas/core/arrays/__init__.py
- pandas/core/groupby/__init__.py
- pandas/core/internals/__init__.py
- pandas/api/__init__.py
- pandas/api/extensions/__init__.py
- pandas/api/types/__init__.py
- pandas/_libs/__init__.py
- pandas/_libs/tslibs/__init__.py
- pandas/util/__init__.py
- pandas/arrays/__init__.py
| - [x] related to #23334
- [x] passes git diff upstream/master -u -- "*.py" | flake8 --diff | https://api.github.com/repos/pandas-dev/pandas/pulls/26749 | 2019-06-09T00:33:27Z | 2019-06-28T15:37:40Z | 2019-06-28T15:37:40Z | 2019-12-25T20:35:28Z |
Read from HDF with empty `where` throws an error | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 7c7112bae0ff3..0f716dad9a2f2 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -666,6 +666,7 @@ I/O
- Added ``cache_dates=True`` parameter to :meth:`read_csv`, which allows to cache unique dates when they are parsed (:issue:`25990`)
- :meth:`DataFrame.to_excel` now raises a ``ValueError`` when the caller's dimensions exceed the limitations of Excel (:issue:`26051`)
- :func:`read_excel` now raises a ``ValueError`` when input is of type :class:`pandas.io.excel.ExcelFile` and ``engine`` param is passed since :class:`pandas.io.excel.ExcelFile` has an engine defined (:issue:`26566`)
+- Bug while selecting from :class:`HDFStore` with ``where=''`` specified (:issue:`26610`).
Plotting
^^^^^^^^
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 53ef2395a302a..983b1286eec91 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -98,7 +98,7 @@ def _ensure_term(where, scope_level):
where = wlist
elif maybe_expression(where):
where = Term(where, scope_level=level)
- return where
+ return where if where is None or len(where) else None
class PossibleDataLossError(Exception):
diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py
index 8b5907b920cca..5c9c3ae46df23 100644
--- a/pandas/tests/io/test_pytables.py
+++ b/pandas/tests/io/test_pytables.py
@@ -4731,6 +4731,21 @@ def test_read_py2_hdf_file_in_py3(self, datapath):
result = store['p']
assert_frame_equal(result, expected)
+ @pytest.mark.parametrize("where", ["", (), (None, ), [], [None]])
+ def test_select_empty_where(self, where):
+ # GH26610
+
+ # Using keyword `where` as '' or (), or [None], etc
+ # while reading from HDF store raises
+ # "SyntaxError: only a single expression is allowed"
+
+ df = pd.DataFrame([1, 2, 3])
+ with ensure_clean_path("empty_where.h5") as path:
+ with pd.HDFStore(path) as store:
+ store.put("df", df, "t")
+ result = pd.read_hdf(store, "df", where=where)
+ assert_frame_equal(result, df)
+
class TestHDFComplexValues(Base):
# GH10447
| - [x] closes #26610
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26746 | 2019-06-09T00:05:52Z | 2019-06-11T00:14:59Z | 2019-06-11T00:14:59Z | 2019-06-11T12:20:37Z |
Deprecated Series.ftype, Series.ftypes and DataFrame.ftypes features | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index a21e9773243da..8a8f0594f0d3e 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -478,6 +478,8 @@ Other Deprecations
- The :meth:`DataFrame.compound` and :meth:`Series.compound` methods are deprecated and will be removed in a future version (:issue:`26405`).
- The internal attributes ``_start``, ``_stop`` and ``_step`` attributes of :class:`RangeIndex` have been deprecated.
Use the public attributes :attr:`~RangeIndex.start`, :attr:`~RangeIndex.stop` and :attr:`~RangeIndex.step` instead (:issue:`26581`).
+- The :meth:`Series.ftype`, :meth:`Series.ftypes` and :meth:`DataFrame.ftypes` methods are deprecated and will be removed in a future version.
+ Instead, use :meth:`Series.dtype` and :meth:`DataFrame.dtypes` (:issue:`26705`).
.. _whatsnew_0250.prior_deprecations:
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 19d093dd29457..dcfbdf842dc80 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5525,6 +5525,9 @@ def ftypes(self):
"""
Return the ftypes (indication of sparse/dense and dtype) in DataFrame.
+ .. deprecated:: 0.25.0
+ Use :func:`dtypes` instead.
+
This returns a Series with the data type of each column.
The result's index is the original DataFrame's columns. Columns
with mixed types are stored with the ``object`` dtype. See
@@ -5562,6 +5565,11 @@ def ftypes(self):
3 float64:sparse
dtype: object
"""
+ warnings.warn("DataFrame.ftypes is deprecated and will "
+ "be removed in a future version. "
+ "Use DataFrame.dtypes instead.",
+ FutureWarning, stacklevel=2)
+
from pandas import Series
return Series(self._data.get_ftypes(), index=self._info_axis,
dtype=np.object_)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 472d984234275..cc4a9b84dc863 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -419,14 +419,30 @@ def dtypes(self):
def ftype(self):
"""
Return if the data is sparse|dense.
+
+ .. deprecated:: 0.25.0
+ Use :func:`dtype` instead.
"""
+ warnings.warn("Series.ftype is deprecated and will "
+ "be removed in a future version. "
+ "Use Series.dtype instead.",
+ FutureWarning, stacklevel=2)
+
return self._data.ftype
@property
def ftypes(self):
"""
Return if the data is sparse|dense.
+
+ .. deprecated:: 0.25.0
+ Use :func:`dtypes` instead.
"""
+ warnings.warn("Series.ftypes is deprecated and will "
+ "be removed in a future version. "
+ "Use Series.dtype instead.",
+ FutureWarning, stacklevel=2)
+
return self._data.ftype
@property
diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py
index 575eac68b111b..96cf70483d4e7 100644
--- a/pandas/tests/frame/test_dtypes.py
+++ b/pandas/tests/frame/test_dtypes.py
@@ -38,23 +38,34 @@ def test_concat_empty_dataframe_dtypes(self):
def test_empty_frame_dtypes_ftypes(self):
empty_df = pd.DataFrame()
assert_series_equal(empty_df.dtypes, pd.Series(dtype=np.object))
- assert_series_equal(empty_df.ftypes, pd.Series(dtype=np.object))
+
+ # GH 26705 - Assert .ftypes is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert_series_equal(empty_df.ftypes, pd.Series(dtype=np.object))
nocols_df = pd.DataFrame(index=[1, 2, 3])
assert_series_equal(nocols_df.dtypes, pd.Series(dtype=np.object))
- assert_series_equal(nocols_df.ftypes, pd.Series(dtype=np.object))
+
+ # GH 26705 - Assert .ftypes is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert_series_equal(nocols_df.ftypes, pd.Series(dtype=np.object))
norows_df = pd.DataFrame(columns=list("abc"))
assert_series_equal(norows_df.dtypes, pd.Series(
np.object, index=list("abc")))
- assert_series_equal(norows_df.ftypes, pd.Series(
- 'object:dense', index=list("abc")))
+
+ # GH 26705 - Assert .ftypes is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert_series_equal(norows_df.ftypes, pd.Series(
+ 'object:dense', index=list("abc")))
norows_int_df = pd.DataFrame(columns=list("abc")).astype(np.int32)
assert_series_equal(norows_int_df.dtypes, pd.Series(
np.dtype('int32'), index=list("abc")))
- assert_series_equal(norows_int_df.ftypes, pd.Series(
- 'int32:dense', index=list("abc")))
+ # GH 26705 - Assert .ftypes is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert_series_equal(norows_int_df.ftypes, pd.Series(
+ 'int32:dense', index=list("abc")))
odict = OrderedDict
df = pd.DataFrame(odict([('a', 1), ('b', True), ('c', 1.0)]),
@@ -66,11 +77,17 @@ def test_empty_frame_dtypes_ftypes(self):
('b', 'bool:dense'),
('c', 'float64:dense')]))
assert_series_equal(df.dtypes, ex_dtypes)
- assert_series_equal(df.ftypes, ex_ftypes)
+
+ # GH 26705 - Assert .ftypes is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert_series_equal(df.ftypes, ex_ftypes)
# same but for empty slice of df
assert_series_equal(df[:0].dtypes, ex_dtypes)
- assert_series_equal(df[:0].ftypes, ex_ftypes)
+
+ # GH 26705 - Assert .ftypes is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert_series_equal(df[:0].ftypes, ex_ftypes)
def test_datetime_with_tz_dtypes(self):
tzframe = DataFrame({'A': date_range('20130101', periods=3),
@@ -402,7 +419,10 @@ def test_ftypes(self):
B='float32:dense',
C='float16:dense',
D='float64:dense')).sort_values()
- result = frame.ftypes.sort_values()
+
+ # GH 26705 - Assert .ftypes is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ result = frame.ftypes.sort_values()
assert_series_equal(result, expected)
def test_astype(self):
diff --git a/pandas/tests/series/test_combine_concat.py b/pandas/tests/series/test_combine_concat.py
index f11595febf6ed..e9e87e5bb07a7 100644
--- a/pandas/tests/series/test_combine_concat.py
+++ b/pandas/tests/series/test_combine_concat.py
@@ -247,21 +247,30 @@ def test_concat_empty_series_dtypes(self):
result = pd.concat([Series(dtype='float64').to_sparse(), Series(
dtype='float64').to_sparse()])
assert result.dtype == 'Sparse[float64]'
- assert result.ftype == 'float64:sparse'
+
+ # GH 26705 - Assert .ftype is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert result.ftype == 'float64:sparse'
result = pd.concat([Series(dtype='float64').to_sparse(), Series(
dtype='float64')])
# TODO: release-note: concat sparse dtype
expected = pd.core.sparse.api.SparseDtype(np.float64)
assert result.dtype == expected
- assert result.ftype == 'float64:sparse'
+
+ # GH 26705 - Assert .ftype is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert result.ftype == 'float64:sparse'
result = pd.concat([Series(dtype='float64').to_sparse(), Series(
dtype='object')])
# TODO: release-note: concat sparse dtype
expected = pd.core.sparse.api.SparseDtype('object')
assert result.dtype == expected
- assert result.ftype == 'object:sparse'
+
+ # GH 26705 - Assert .ftype is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert result.ftype == 'object:sparse'
def test_combine_first_dt64(self):
from pandas.core.tools.datetimes import to_datetime
diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py
index 51334557fa403..392163228398b 100644
--- a/pandas/tests/series/test_dtypes.py
+++ b/pandas/tests/series/test_dtypes.py
@@ -48,8 +48,14 @@ def test_dtype(self, datetime_series):
assert datetime_series.dtype == np.dtype('float64')
assert datetime_series.dtypes == np.dtype('float64')
- assert datetime_series.ftype == 'float64:dense'
- assert datetime_series.ftypes == 'float64:dense'
+
+ # GH 26705 - Assert .ftype is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert datetime_series.ftype == 'float64:dense'
+
+ # GH 26705 - Assert .ftypes is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ assert datetime_series.ftypes == 'float64:dense'
tm.assert_series_equal(datetime_series.get_dtype_counts(),
Series(1, ['float64']))
# GH18243 - Assert .get_ftype_counts is deprecated
diff --git a/pandas/tests/sparse/series/test_series.py b/pandas/tests/sparse/series/test_series.py
index b8d0fab1debbd..f7c8a84720d0a 100644
--- a/pandas/tests/sparse/series/test_series.py
+++ b/pandas/tests/sparse/series/test_series.py
@@ -164,7 +164,10 @@ def test_construct_DataFrame_with_sp_series(self):
# blocking
expected = Series({'col': 'float64:sparse'})
- result = df.ftypes
+
+ # GH 26705 - Assert .ftypes is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ result = df.ftypes
tm.assert_series_equal(expected, result)
def test_constructor_preserve_attr(self):
| Deprecation of `Series.ftype`, `Series.ftypes` and `DataFrame.ftypes`
closes #26705
- [x] Updated the docstrings for the sphinx documentation
- [x] Updated the unit tests for testing deprecation warnings | https://api.github.com/repos/pandas-dev/pandas/pulls/26744 | 2019-06-08T22:21:44Z | 2019-06-11T00:18:58Z | 2019-06-11T00:18:58Z | 2019-06-11T00:19:03Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.