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
Replaced void pointers with Types in JSON Datetime Conversions
diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c index 5d17d3a2d7bcb..9abcb8333b435 100644 --- a/pandas/_libs/src/ujson/python/objToJSON.c +++ b/pandas/_libs/src/ujson/python/objToJSON.c @@ -59,8 +59,8 @@ PyObject *cls_timedelta; npy_int64 get_nat(void) { return NPY_MIN_INT64; } -typedef void *(*PFN_PyTypeToJSON)(JSOBJ obj, JSONTypeContext *ti, - void *outValue, size_t *_outLen); +typedef char *(*PFN_PyTypeToUTF8)(JSOBJ obj, JSONTypeContext *ti, + size_t *_outLen); typedef struct __NpyArrContext { PyObject *array; @@ -94,7 +94,7 @@ typedef struct __TypeContext { JSPFN_ITERNEXT iterNext; JSPFN_ITERGETNAME iterGetName; JSPFN_ITERGETVALUE iterGetValue; - PFN_PyTypeToJSON PyTypeToJSON; + PFN_PyTypeToUTF8 PyTypeToUTF8; PyObject *newObj; PyObject *dictObj; Py_ssize_t index; @@ -396,96 +396,116 @@ static PyObject *get_item(PyObject *obj, Py_ssize_t i) { return ret; } -static void *PyBytesToUTF8(JSOBJ _obj, JSONTypeContext *tc, void *outValue, - size_t *_outLen) { +static char *PyBytesToUTF8(JSOBJ _obj, JSONTypeContext *tc, size_t *_outLen) { PyObject *obj = (PyObject *)_obj; *_outLen = PyBytes_GET_SIZE(obj); return PyBytes_AS_STRING(obj); } -static void *PyUnicodeToUTF8(JSOBJ _obj, JSONTypeContext *tc, void *outValue, - size_t *_outLen) { - return PyUnicode_AsUTF8AndSize(_obj, _outLen); +static char *PyUnicodeToUTF8(JSOBJ _obj, JSONTypeContext *tc, size_t *_outLen) { + return (char *)PyUnicode_AsUTF8AndSize(_obj, (Py_ssize_t *)_outLen); } -static void *PandasDateTimeStructToJSON(npy_datetimestruct *dts, - JSONTypeContext *tc, void *outValue, - size_t *_outLen) { - NPY_DATETIMEUNIT base = ((PyObjectEncoder *)tc->encoder)->datetimeUnit; +/* returns a char* and mutates the pointer to *len */ +static char *NpyDateTimeToIso(JSOBJ unused, JSONTypeContext *tc, size_t *len) { + npy_datetimestruct dts; + int ret_code; + int64_t longVal = GET_TC(tc)->longValue; - if (((PyObjectEncoder *)tc->encoder)->datetimeIso) { - PRINTMARK(); - *_outLen = (size_t)get_datetime_iso_8601_strlen(0, base); - GET_TC(tc)->cStr = PyObject_Malloc(sizeof(char) * (*_outLen)); - if (!GET_TC(tc)->cStr) { - PyErr_NoMemory(); - ((JSONObjectEncoder *)tc->encoder)->errorMsg = ""; - return NULL; - } + pandas_datetime_to_datetimestruct(longVal, NPY_FR_ns, &dts); - if (!make_iso_8601_datetime(dts, GET_TC(tc)->cStr, *_outLen, base)) { - PRINTMARK(); - *_outLen = strlen(GET_TC(tc)->cStr); - return GET_TC(tc)->cStr; - } else { - PRINTMARK(); - PyErr_SetString(PyExc_ValueError, - "Could not convert datetime value to string"); - ((JSONObjectEncoder *)tc->encoder)->errorMsg = ""; - PyObject_Free(GET_TC(tc)->cStr); - return NULL; - } - } else { - PRINTMARK(); - *((JSINT64 *)outValue) = npy_datetimestruct_to_datetime(base, dts); + NPY_DATETIMEUNIT base = ((PyObjectEncoder *)tc->encoder)->datetimeUnit; + *len = (size_t)get_datetime_iso_8601_strlen(0, base); + char *result = PyObject_Malloc(*len); + + if (result == NULL) { + PyErr_NoMemory(); + ((JSONObjectEncoder *)tc->encoder)->errorMsg = ""; return NULL; } -} -static void *NpyDateTimeScalarToJSON(JSOBJ _obj, JSONTypeContext *tc, - void *outValue, size_t *_outLen) { - npy_datetimestruct dts; - PyDatetimeScalarObject *obj = (PyDatetimeScalarObject *)_obj; - PRINTMARK(); - // TODO(anyone): Does not appear to be reached in tests. + ret_code = make_iso_8601_datetime(&dts, result, *len, base); + if (ret_code != 0) { + PyErr_SetString(PyExc_ValueError, + "Could not convert datetime value to string"); + ((JSONObjectEncoder *)tc->encoder)->errorMsg = ""; + PyObject_Free(result); + } - pandas_datetime_to_datetimestruct(obj->obval, - (NPY_DATETIMEUNIT)obj->obmeta.base, &dts); - return PandasDateTimeStructToJSON(&dts, tc, outValue, _outLen); + // Note that get_datetime_iso_8601_strlen just gives a generic size + // for ISO string conversion, not the actual size used + *len = strlen(result); + return result; } -static void *PyDateTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue, - size_t *_outLen) { +static npy_datetime NpyDateTimeToEpoch(npy_datetime dt, NPY_DATETIMEUNIT base) { + scaleNanosecToUnit(&dt, base); + return dt; +} + +static char *PyDateTimeToIso(JSOBJ obj, JSONTypeContext *tc, size_t *len) { npy_datetimestruct dts; - PyDateTime_Date *obj = (PyDateTime_Date *)_obj; + int ret; - PRINTMARK(); + if (!PyDateTime_Check(obj)) { + // TODO: raise TypeError + } - if (!convert_pydatetime_to_datetimestruct(obj, &dts)) { - PRINTMARK(); - return PandasDateTimeStructToJSON(&dts, tc, outValue, _outLen); - } else { + ret = convert_pydatetime_to_datetimestruct(obj, &dts); + if (ret != 0) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ValueError, - "Could not convert datetime value to string"); + "Could not convert PyDateTime to numpy datetime"); } ((JSONObjectEncoder *)tc->encoder)->errorMsg = ""; return NULL; } + + NPY_DATETIMEUNIT base = ((PyObjectEncoder *)tc->encoder)->datetimeUnit; + *len = (size_t)get_datetime_iso_8601_strlen(0, base); + char *result = PyObject_Malloc(*len); + ret = make_iso_8601_datetime(&dts, result, *len, base); + + if (ret != 0) { + PRINTMARK(); + PyErr_SetString(PyExc_ValueError, + "Could not convert datetime value to string"); + ((JSONObjectEncoder *)tc->encoder)->errorMsg = ""; + PyObject_Free(result); + return NULL; + } + + // Note that get_datetime_iso_8601_strlen just gives a generic size + // for ISO string conversion, not the actual size used + *len = strlen(result); + return result; } -static void *NpyDatetime64ToJSON(JSOBJ _obj, JSONTypeContext *tc, - void *outValue, size_t *_outLen) { +static npy_datetime PyDateTimeToEpoch(PyObject *obj, NPY_DATETIMEUNIT base) { npy_datetimestruct dts; - PRINTMARK(); + int ret; + + if (!PyDateTime_Check(obj)) { + // TODO: raise TypeError + } + PyDateTime_Date *dt = (PyDateTime_Date *)obj; - pandas_datetime_to_datetimestruct((npy_datetime)GET_TC(tc)->longValue, - NPY_FR_ns, &dts); - return PandasDateTimeStructToJSON(&dts, tc, outValue, _outLen); + ret = convert_pydatetime_to_datetimestruct(dt, &dts); + if (ret != 0) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "Could not convert PyDateTime to numpy datetime"); + } + // TODO: is setting errMsg required? + //((JSONObjectEncoder *)tc->encoder)->errorMsg = ""; + // return NULL; + } + + npy_datetime npy_dt = npy_datetimestruct_to_datetime(NPY_FR_ns, &dts); + return NpyDateTimeToEpoch(npy_dt, base); } -static void *PyTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue, - size_t *outLen) { +static char *PyTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, size_t *outLen) { PyObject *obj = (PyObject *)_obj; PyObject *str; PyObject *tmp; @@ -509,49 +529,10 @@ static void *PyTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue, GET_TC(tc)->newObj = str; *outLen = PyBytes_GET_SIZE(str); - outValue = (void *)PyBytes_AS_STRING(str); + char *outValue = PyBytes_AS_STRING(str); return outValue; } -static int NpyTypeToJSONType(PyObject *obj, JSONTypeContext *tc, int npyType, - void *value) { - PyArray_VectorUnaryFunc *castfunc; - npy_int64 longVal; - - if (PyTypeNum_ISDATETIME(npyType)) { - PRINTMARK(); - castfunc = - PyArray_GetCastFunc(PyArray_DescrFromType(npyType), NPY_INT64); - if (!castfunc) { - PyErr_Format(PyExc_ValueError, "Cannot cast numpy dtype %d to long", - npyType); - } - castfunc(value, &longVal, 1, NULL, NULL); - if (longVal == get_nat()) { - PRINTMARK(); - return JT_NULL; - } - - if (((PyObjectEncoder *)tc->encoder)->datetimeIso) { - GET_TC(tc)->longValue = (JSINT64)longVal; - GET_TC(tc)->PyTypeToJSON = NpyDatetime64ToJSON; - return JT_UTF8; - } else { - NPY_DATETIMEUNIT unit = - ((PyObjectEncoder *)tc->encoder)->datetimeUnit; - if (!scaleNanosecToUnit(&longVal, unit)) { - GET_TC(tc)->longValue = longVal; - return JT_LONG; - } else { - // TODO: some kind of error handling - } - } - } - - PRINTMARK(); - return JT_INVALID; -} - //============================================================================= // Numpy array iteration functions //============================================================================= @@ -1705,29 +1686,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { obj = (PyObject *)_obj; enc = (PyObjectEncoder *)tc->encoder; - if (enc->npyType >= 0) { - PRINTMARK(); - tc->prv = &(enc->basicTypeContext); - tc->type = NpyTypeToJSONType(obj, tc, enc->npyType, enc->npyValue); - - if (tc->type == JT_INVALID) { - if (enc->defaultHandler) { - enc->npyType = -1; - PRINTMARK(); - Object_invokeDefaultHandler( - enc->npyCtxtPassthru->getitem(enc->npyValue, - enc->npyCtxtPassthru->array), - enc); - } else { - PyErr_Format(PyExc_RuntimeError, "Unhandled numpy dtype %d", - enc->npyType); - } - } - enc->npyCtxtPassthru = NULL; - enc->npyType = -1; - return; - } - if (PyBool_Check(obj)) { PRINTMARK(); tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE; @@ -1745,6 +1703,44 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } tc->prv = pc; + if (PyTypeNum_ISDATETIME(enc->npyType)) { + PRINTMARK(); + int64_t longVal; + PyArray_VectorUnaryFunc *castfunc = + PyArray_GetCastFunc(PyArray_DescrFromType(enc->npyType), NPY_INT64); + if (!castfunc) { + PyErr_Format(PyExc_ValueError, "Cannot cast numpy dtype %d to long", + enc->npyType); + } + castfunc(enc->npyValue, &longVal, 1, NULL, NULL); + if (longVal == get_nat()) { + PRINTMARK(); + tc->type = JT_NULL; + } else { + + if (enc->datetimeIso) { + PRINTMARK(); + pc->PyTypeToUTF8 = NpyDateTimeToIso; + // Currently no way to pass longVal to iso function, so use + // state management + GET_TC(tc)->longValue = longVal; + tc->type = JT_UTF8; + } else { + PRINTMARK(); + NPY_DATETIMEUNIT base = + ((PyObjectEncoder *)tc->encoder)->datetimeUnit; + GET_TC(tc)->longValue = NpyDateTimeToEpoch(longVal, base); + tc->type = JT_LONG; + } + } + + // TODO: this prevents infinite loop with mixed-type DataFrames; + // refactor + enc->npyCtxtPassthru = NULL; + enc->npyType = -1; + return; + } + if (PyIter_Check(obj) || (PyArray_Check(obj) && !PyArray_CheckScalar(obj))) { PRINTMARK(); @@ -1776,12 +1772,12 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } else if (PyBytes_Check(obj)) { PRINTMARK(); - pc->PyTypeToJSON = PyBytesToUTF8; + pc->PyTypeToUTF8 = PyBytesToUTF8; tc->type = JT_UTF8; return; } else if (PyUnicode_Check(obj)) { PRINTMARK(); - pc->PyTypeToJSON = PyUnicodeToUTF8; + pc->PyTypeToUTF8 = PyUnicodeToUTF8; tc->type = JT_UTF8; return; } else if (PyObject_TypeCheck(obj, type_decimal)) { @@ -1799,19 +1795,19 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { PRINTMARK(); if (enc->datetimeIso) { PRINTMARK(); - pc->PyTypeToJSON = PyDateTimeToJSON; + pc->PyTypeToUTF8 = PyDateTimeToIso; tc->type = JT_UTF8; } else { PRINTMARK(); - // TODO: last argument here is unused; should decouple string - // from long datetimelike conversion routines - PyDateTimeToJSON(obj, tc, &(GET_TC(tc)->longValue), 0); + NPY_DATETIMEUNIT base = + ((PyObjectEncoder *)tc->encoder)->datetimeUnit; + GET_TC(tc)->longValue = PyDateTimeToEpoch(obj, base); tc->type = JT_LONG; } return; } else if (PyTime_Check(obj)) { PRINTMARK(); - pc->PyTypeToJSON = PyTimeToJSON; + pc->PyTypeToUTF8 = PyTimeToJSON; tc->type = JT_UTF8; return; } else if (PyArray_IsScalar(obj, Datetime)) { @@ -1823,8 +1819,17 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } PRINTMARK(); - pc->PyTypeToJSON = NpyDateTimeScalarToJSON; - tc->type = enc->datetimeIso ? JT_UTF8 : JT_LONG; + if (enc->datetimeIso) { + PRINTMARK(); + pc->PyTypeToUTF8 = PyDateTimeToIso; + tc->type = JT_UTF8; + } else { + PRINTMARK(); + NPY_DATETIMEUNIT base = + ((PyObjectEncoder *)tc->encoder)->datetimeUnit; + GET_TC(tc)->longValue = PyDateTimeToEpoch(obj, base); + tc->type = JT_LONG; + } return; } else if (PyDelta_Check(obj)) { if (PyObject_HasAttrString(obj, "value")) { @@ -2226,7 +2231,7 @@ void Object_endTypeContext(JSOBJ obj, JSONTypeContext *tc) { const char *Object_getStringValue(JSOBJ obj, JSONTypeContext *tc, size_t *_outLen) { - return GET_TC(tc)->PyTypeToJSON(obj, tc, NULL, _outLen); + return GET_TC(tc)->PyTypeToUTF8(obj, tc, _outLen); } JSINT64 Object_getLongValue(JSOBJ obj, JSONTypeContext *tc) {
This also incorporates the clean up from #30271 Benchmarks show the following benefit, though most likely just noise: ```sh . before after ratio [04fce81f] [f8ed75d0] <stash~6^2> <json-dates> - 336±9ms 302±4ms 0.90 io.json.ToJSON.time_to_json('columns', 'df_int_floats') SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. PERFORMANCE INCREASED. ``` One follow up to this can drastically speed up datetime index handling - right now these are done in the Python space but can reuse these same functions
https://api.github.com/repos/pandas-dev/pandas/pulls/30283
2019-12-15T23:45:07Z
2019-12-24T17:27:47Z
2019-12-24T17:27:47Z
2019-12-24T17:28:50Z
STY: Replace .format() to fstrings
diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 5b9e37bd54bad..b30a7a24f3495 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -88,10 +88,7 @@ def clean_fill_method(method, allow_nearest=False): valid_methods.append("nearest") expecting = "pad (ffill), backfill (bfill) or nearest" if method not in valid_methods: - msg = "Invalid fill method. Expecting {expecting}. Got {method}".format( - expecting=expecting, method=method - ) - raise ValueError(msg) + raise ValueError(f"Invalid fill method. Expecting {expecting}. Got {method}") return method @@ -119,10 +116,7 @@ def clean_interp_method(method, **kwargs): if method in ("spline", "polynomial") and order is None: raise ValueError("You must specify the order of the spline or polynomial.") if method not in valid: - raise ValueError( - "method must be one of {valid}. Got '{method}' " - "instead.".format(valid=valid, method=method) - ) + raise ValueError(f"method must be one of {valid}. Got '{method}' instead.") return method @@ -212,7 +206,7 @@ def interpolate_1d( limit_direction = limit_direction.lower() if limit_direction not in valid_limit_directions: raise ValueError( - f"Invalid limit_direction: expecting one of " + "Invalid limit_direction: expecting one of " f"{valid_limit_directions}, got '{limit_direction}'." ) @@ -221,8 +215,8 @@ def interpolate_1d( limit_area = limit_area.lower() if limit_area not in valid_limit_areas: raise ValueError( - "Invalid limit_area: expecting one of {}, got " - "{}.".format(valid_limit_areas, limit_area) + f"Invalid limit_area: expecting one of {valid_limit_areas}, got " + f"{limit_area}." ) # default limit is unlimited GH #16282 @@ -328,7 +322,7 @@ def _interpolate_scipy_wrapper( Returns an array interpolated at new_x. Add any new methods to the list in _clean_interp_method. """ - extra = "{method} interpolation requires SciPy.".format(method=method) + extra = f"{method} interpolation requires SciPy." import_optional_dependency("scipy", extra=extra) from scipy import interpolate @@ -375,8 +369,7 @@ def _interpolate_scipy_wrapper( # GH #10633, #24014 if isna(order) or (order <= 0): raise ValueError( - "order needs to be specified and greater than 0; " - "got order: {}".format(order) + f"order needs to be specified and greater than 0; got order: {order}" ) terp = interpolate.UnivariateSpline(x, y, k=order, **kwargs) new_y = terp(new_x) diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 8de955e5ff2cf..f27e3d4527921 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -1301,9 +1301,7 @@ def _ensure_numeric(x): x = complex(x) except ValueError: # e.g. "foo" - raise TypeError( - "Could not convert {value!s} to numeric".format(value=x) - ) + raise TypeError(f"Could not convert {x} to numeric") return x diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index 51aeb40744c3a..8d5aa64a49cf2 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -274,7 +274,7 @@ def test_partial_slicing_dataframe(self): result = df["a"][ts_string] assert isinstance(result, np.int64) assert result == expected - msg = r"^'{}'$".format(ts_string) + msg = fr"^'{ts_string}'$" with pytest.raises(KeyError, match=msg): df[ts_string] @@ -302,7 +302,7 @@ def test_partial_slicing_dataframe(self): result = df["a"][ts_string] assert isinstance(result, np.int64) assert result == 2 - msg = r"^'{}'$".format(ts_string) + msg = fr"^'{ts_string}'$" with pytest.raises(KeyError, match=msg): df[ts_string] @@ -311,7 +311,7 @@ def test_partial_slicing_dataframe(self): for fmt, res in list(zip(formats, resolutions))[rnum + 1 :]: ts = index[1] + Timedelta("1 " + res) ts_string = ts.strftime(fmt) - msg = r"^'{}'$".format(ts_string) + msg = fr"^'{ts_string}'$" with pytest.raises(KeyError, match=msg): df["a"][ts_string] with pytest.raises(KeyError, match=msg):
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry #29547
https://api.github.com/repos/pandas-dev/pandas/pulls/30278
2019-12-14T21:32:29Z
2019-12-18T09:57:19Z
2019-12-18T09:57:19Z
2019-12-18T09:57:32Z
[bug] don't remove timezone-awareness when using the method from Dat…
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 1253788d7ff27..faca744a8f92c 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -714,6 +714,7 @@ Datetimelike - Bug in :func:`pandas.to_datetime` failing for `deques` when using ``cache=True`` (the default) (:issue:`29403`) - Bug in :meth:`Series.item` with ``datetime64`` or ``timedelta64`` dtype, :meth:`DatetimeIndex.item`, and :meth:`TimedeltaIndex.item` returning an integer instead of a :class:`Timestamp` or :class:`Timedelta` (:issue:`30175`) - Bug in :class:`DatetimeIndex` addition when adding a non-optimized :class:`DateOffset` incorrectly dropping timezone information (:issue:`30336`) +- Bug in :meth:`DataFrame.append` would remove the timezone-awareness of new data (:issue:`30238`) Timedelta ^^^^^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 51330bfc55dc3..dfda1470413b7 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6757,25 +6757,18 @@ def append(self, other, ignore_index=False, verify_integrity=False, sort=False): " or if the Series has a name" ) - if other.name is None: - index = None - else: - # other must have the same index name as self, otherwise - # index name will be reset - index = Index([other.name], name=self.index.name) - + index = Index([other.name], name=self.index.name) idx_diff = other.index.difference(self.columns) try: combined_columns = self.columns.append(idx_diff) except TypeError: combined_columns = self.columns.astype(object).append(idx_diff) - other = other.reindex(combined_columns, copy=False) - other = DataFrame( - other.values.reshape((1, len(other))), - index=index, - columns=combined_columns, + other = ( + other.reindex(combined_columns, copy=False) + .to_frame() + .T.infer_objects() + .rename_axis(index.names, copy=False) ) - other = other._convert(datetime=True, timedelta=True) if not self.columns.equals(combined_columns): self = self.reindex(columns=combined_columns) elif isinstance(other, list): diff --git a/pandas/tests/frame/test_combine_concat.py b/pandas/tests/frame/test_combine_concat.py index e72de487abb2f..ebc4438366001 100644 --- a/pandas/tests/frame/test_combine_concat.py +++ b/pandas/tests/frame/test_combine_concat.py @@ -288,6 +288,17 @@ def test_append_dtypes(self): expected = DataFrame({"bar": Series([Timestamp("20130101"), 1])}) tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( + "timestamp", ["2019-07-19 07:04:57+0100", "2019-07-19 07:04:57"] + ) + def test_append_timestamps_aware_or_naive(self, tz_naive_fixture, timestamp): + # GH 30238 + tz = tz_naive_fixture + df = pd.DataFrame([pd.Timestamp(timestamp, tz=tz)]) + result = df.append(df.iloc[0]).iloc[-1] + expected = pd.Series(pd.Timestamp(timestamp, tz=tz), name=0) + tm.assert_series_equal(result, expected) + def test_update(self): df = DataFrame( [[1.5, np.nan, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]]
…aFrame - [x] closes #30238 - [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/30277
2019-12-14T18:38:20Z
2019-12-24T14:58:53Z
2019-12-24T14:58:53Z
2019-12-24T16:08:38Z
CLN: changed .format to f-string in pandas/core/indexes
diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index e8d2ba85e08a6..ae27aad3dda08 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -26,8 +26,8 @@ class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin): def __init__(self, data, orig): if not isinstance(data, ABCSeries): raise TypeError( - "cannot convert an object of type {0} to a " - "datetimelike index".format(type(data)) + f"cannot convert an object of type {type(data)} to a " + "datetimelike index" ) self._parent = data @@ -54,8 +54,7 @@ def _get_values(self): return DatetimeIndex(data, copy=False, name=self.name) raise TypeError( - "cannot convert an object of type {0} to a " - "datetimelike index".format(type(data)) + f"cannot convert an object of type {type(data)} to a datetimelike index" ) def _delegate_property_get(self, name): @@ -315,8 +314,8 @@ def __new__(cls, data): if not isinstance(data, ABCSeries): raise TypeError( - "cannot convert an object of type {0} to a " - "datetimelike index".format(type(data)) + f"cannot convert an object of type {type(data)} to a " + "datetimelike index" ) orig = data if is_categorical_dtype(data) else None diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index dc1cbb6014608..44478d00da9cf 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -893,7 +893,7 @@ def _add_comparison_methods(cls): """ add in comparison methods """ def _make_compare(op): - opname = "__{op}__".format(op=op.__name__) + opname = f"__{op.__name__}__" def _evaluate_compare(self, other): with np.errstate(all="ignore"): diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index eb3728c1e3bd2..50dbddec5c8b2 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -137,7 +137,7 @@ def wrapper(self, other): return result wrapper.__doc__ = op.__doc__ - wrapper.__name__ = "__{}__".format(op.__name__) + wrapper.__name__ = f"__{op.__name__}__" return wrapper @property @@ -677,7 +677,7 @@ def _summary(self, name=None): name = type(self).__name__ result = f"{name}: {len(self)} entries{index_summary}" if self.freq: - result += "\nFreq: %s" % self.freqstr + result += f"\nFreq: {self.freqstr}" # display as values, not quoted result = result.replace("'", "") diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index cafa2e03f23d0..523c434cb7377 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -247,10 +247,8 @@ def __new__( if is_scalar(data): raise TypeError( - "{cls}() must be called with a " - "collection of some kind, {data} was passed".format( - cls=cls.__name__, data=repr(data) - ) + f"{cls.__name__}() must be called with a " + f"collection of some kind, {repr(data)} was passed" ) # - Cases checked above all return/raise before reaching here - # @@ -973,9 +971,7 @@ def get_loc(self, key, method=None, tolerance=None): elif isinstance(key, timedelta): # GH#20464 raise TypeError( - "Cannot index {cls} with {other}".format( - cls=type(self).__name__, other=type(key).__name__ - ) + f"Cannot index {type(self).__name__} with {type(key).__name__}" ) if isinstance(key, time): @@ -1577,13 +1573,13 @@ def bdate_range( weekmask = weekmask or "Mon Tue Wed Thu Fri" freq = prefix_mapping[freq](holidays=holidays, weekmask=weekmask) except (KeyError, TypeError): - msg = "invalid custom frequency string: {freq}".format(freq=freq) + msg = f"invalid custom frequency string: {freq}" raise ValueError(msg) elif holidays or weekmask: msg = ( "a custom frequency string is required when holidays or " - "weekmask are passed, got frequency {freq}" - ).format(freq=freq) + f"weekmask are passed, got frequency {freq}" + ) raise ValueError(msg) return date_range( diff --git a/pandas/core/indexes/frozen.py b/pandas/core/indexes/frozen.py index 27f88933f9998..fd8ab74ed4920 100644 --- a/pandas/core/indexes/frozen.py +++ b/pandas/core/indexes/frozen.py @@ -93,11 +93,7 @@ def __hash__(self): def _disabled(self, *args, **kwargs): """This method will not function because object is immutable.""" - raise TypeError( - "'{cls}' does not support mutable operations.".format( - cls=type(self).__name__ - ) - ) + raise TypeError(f"'{type(self).__name__}' does not support mutable operations.") def __str__(self) -> str: return pprint_thing(self, quote_strings=True, escape_chars=("\t", "\r", "\n")) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index b1f67eeab903d..f046f0d89c428 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -154,10 +154,10 @@ def func(intvidx_self, other, sort=False): common_subtype = find_common_type(subtypes) if is_object_dtype(common_subtype): msg = ( - "can only do {op} between two IntervalIndex " + f"can only do {self.op_name} between two IntervalIndex " "objects that have compatible dtypes" ) - raise TypeError(msg.format(op=self.op_name)) + raise TypeError(msg) return setop(intvidx_self, other, sort) @@ -432,8 +432,7 @@ def closed(self): ) def set_closed(self, closed): if closed not in _VALID_CLOSED: - msg = "invalid option for 'closed': {closed}" - raise ValueError(msg.format(closed=closed)) + raise ValueError(f"invalid option for 'closed': {closed}") # return self._shallow_copy(closed=closed) array = self._data.set_closed(closed) @@ -762,12 +761,12 @@ def _maybe_convert_i8(self, key): # ensure consistency with IntervalIndex subtype subtype = self.dtype.subtype - msg = ( - "Cannot index an IntervalIndex of subtype {subtype} with " - "values of dtype {other}" - ) + if not is_dtype_equal(subtype, key_dtype): - raise ValueError(msg.format(subtype=subtype, other=key_dtype)) + raise ValueError( + f"Cannot index an IntervalIndex of subtype {subtype} with " + f"values of dtype {key_dtype}" + ) return key_i8 @@ -776,8 +775,8 @@ def _check_method(self, method): return if method in ["bfill", "backfill", "pad", "ffill", "nearest"]: - msg = "method {method} not yet implemented for IntervalIndex" - raise NotImplementedError(msg.format(method=method)) + msg = f"method {method} not yet implemented for IntervalIndex" + raise NotImplementedError(msg) raise ValueError("Invalid fill method") @@ -1165,23 +1164,21 @@ def _format_data(self, name=None): summary = "[]" elif n == 1: first = formatter(self[0]) - summary = "[{first}]".format(first=first) + summary = f"[{first}]" elif n == 2: first = formatter(self[0]) last = formatter(self[-1]) - summary = "[{first}, {last}]".format(first=first, last=last) + summary = f"[{first}, {last}]" else: if n > max_seq_items: n = min(max_seq_items // 2, 10) head = [formatter(x) for x in self[:n]] tail = [formatter(x) for x in self[-n:]] - summary = "[{head} ... {tail}]".format( - head=", ".join(head), tail=", ".join(tail) - ) + summary = f"[{', '.join(head)} ... {', '.join(tail)}]" else: tail = [formatter(x) for x in self] - summary = "[{tail}]".format(tail=", ".join(tail)) + summary = f"[{', '.join(tail)}]" return summary + "," + self._format_space() @@ -1189,12 +1186,12 @@ def _format_attrs(self): attrs = [("closed", repr(self.closed))] if self.name is not None: attrs.append(("name", default_pprint(self.name))) - attrs.append(("dtype", "'{dtype}'".format(dtype=self.dtype))) + attrs.append(("dtype", f"'{self.dtype}'")) return attrs def _format_space(self): space = " " * (len(type(self).__name__) + 1) - return "\n{space}".format(space=space) + return f"\n{space}" # -------------------------------------------------------------------- @@ -1490,25 +1487,21 @@ def interval_range( ) if not _is_valid_endpoint(start): - msg = "start must be numeric or datetime-like, got {start}" - raise ValueError(msg.format(start=start)) + raise ValueError(f"start must be numeric or datetime-like, got {start}") elif not _is_valid_endpoint(end): - msg = "end must be numeric or datetime-like, got {end}" - raise ValueError(msg.format(end=end)) + raise ValueError(f"end must be numeric or datetime-like, got {end}") if is_float(periods): periods = int(periods) elif not is_integer(periods) and periods is not None: - msg = "periods must be a number, got {periods}" - raise TypeError(msg.format(periods=periods)) + raise TypeError(f"periods must be a number, got {periods}") if freq is not None and not is_number(freq): try: freq = to_offset(freq) except ValueError: raise ValueError( - "freq must be numeric or convertible to " - "DateOffset, got {freq}".format(freq=freq) + f"freq must be numeric or convertible to DateOffset, got {freq}" ) # verify type compatibility diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 7b0cc871cbcbc..459d1fd19738d 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -343,35 +343,26 @@ def _verify_integrity(self, codes=None, levels=None): for i, (level, level_codes) in enumerate(zip(levels, codes)): if len(level_codes) != codes_length: raise ValueError( - "Unequal code lengths: %s" % ([len(code_) for code_ in codes]) + f"Unequal code lengths: {[len(code_) for code_ in codes]}" ) if len(level_codes) and level_codes.max() >= len(level): - msg = ( - "On level {level}, code max ({max_code}) >= length of " - "level ({level_len}). NOTE: this index is in an " - "inconsistent state".format( - level=i, max_code=level_codes.max(), level_len=len(level) - ) - ) - raise ValueError(msg) - if len(level_codes) and level_codes.min() < -1: raise ValueError( - "On level {level}, code value ({code})" - " < -1".format(level=i, code=level_codes.min()) + f"On level {i}, code max ({level_codes.max()}) >= length of " + f"level ({len(level)}). NOTE: this index is in an " + "inconsistent state" ) + if len(level_codes) and level_codes.min() < -1: + raise ValueError(f"On level {i}, code value ({level_codes.min()}) < -1") if not level.is_unique: raise ValueError( - "Level values must be unique: {values} on " - "level {level}".format(values=list(level), level=i) + f"Level values must be unique: {list(level)} on level {i}" ) if self.sortorder is not None: if self.sortorder > self._lexsort_depth(): raise ValueError( - "Value for sortorder must be inferior or equal " - "to actual lexsort_depth: " - "sortorder {sortorder} with lexsort_depth {lexsort_depth}".format( - sortorder=self.sortorder, lexsort_depth=self._lexsort_depth() - ) + "Value for sortorder must be inferior or equal to actual " + f"lexsort_depth: sortorder {self.sortorder} " + f"with lexsort_depth {self._lexsort_depth()}" ) codes = [ @@ -1241,7 +1232,7 @@ def _set_names(self, names, level=None, validate=True): # All items in 'names' need to be hashable: if not is_hashable(name): raise TypeError( - "{}.name must be a hashable type".format(type(self).__name__) + f"{type(self).__name__}.name must be a hashable type" ) self._names[lev] = name @@ -1312,8 +1303,8 @@ def _get_level_number(self, level) -> int: # Note: levels are zero-based elif level >= self.nlevels: raise IndexError( - "Too many levels: Index has only %d levels, " - "not %d" % (self.nlevels, level + 1) + f"Too many levels: Index has only {self.nlevels} levels, " + f"not {level + 1}" ) return level @@ -1465,7 +1456,7 @@ def dropna(self, how="any"): elif how == "all": indexer = np.all(nans, axis=0) else: - raise ValueError("invalid how option: {0}".format(how)) + raise ValueError(f"invalid how option: {how}") new_codes = [level_codes[~indexer] for level_codes in self.codes] return self.copy(codes=new_codes, deep=True) @@ -2103,7 +2094,7 @@ def drop(self, codes, level=None, errors="raise"): loc = loc.nonzero()[0] inds.extend(loc) else: - msg = "unsupported indexer of type {}".format(type(loc)) + msg = f"unsupported indexer of type {type(loc)}" raise AssertionError(msg) except KeyError: if errors != "ignore": @@ -2330,7 +2321,7 @@ def _convert_listlike_indexer(self, keyarr, kind=None): check = self.levels[0].get_indexer(keyarr) mask = check == -1 if mask.any(): - raise KeyError("%s not in index" % keyarr[mask]) + raise KeyError(f"{keyarr[mask]} not in index") return indexer, keyarr @@ -2600,8 +2591,7 @@ def _maybe_to_slice(loc): keylen = len(key) if self.nlevels < keylen: raise KeyError( - "Key length ({0}) exceeds index depth ({1})" - "".format(keylen, self.nlevels) + f"Key length ({keylen}) exceeds index depth ({self.nlevels})" ) if keylen == self.nlevels and self.is_unique: @@ -2917,9 +2907,8 @@ def get_locs(self, seq): true_slices = [i for (i, s) in enumerate(com.is_true_slices(seq)) if s] if true_slices and true_slices[-1] >= self.lexsort_depth: raise UnsortedIndexError( - "MultiIndex slicing requires the index " - "to be lexsorted: slicing on levels {0}, " - "lexsort depth {1}".format(true_slices, self.lexsort_depth) + "MultiIndex slicing requires the index to be lexsorted: slicing " + f"on levels {true_slices}, lexsort depth {self.lexsort_depth}" ) # indexer # this is the list of all values that we want to select @@ -3261,10 +3250,10 @@ def astype(self, dtype, copy=True): msg = "> 1 ndim Categorical are not supported at this time" raise NotImplementedError(msg) elif not is_object_dtype(dtype): - msg = ( - "Setting {cls} dtype to anything other than object is not supported" - ).format(cls=type(self)) - raise TypeError(msg) + raise TypeError( + f"Setting {type(self)} dtype to anything other " + "than object is not supported" + ) elif copy is True: return self._shallow_copy() return self diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 536a1fb6ae243..048bff46759bc 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -381,11 +381,10 @@ def inferred_type(self) -> str: def astype(self, dtype, copy=True): dtype = pandas_dtype(dtype) if needs_i8_conversion(dtype): - msg = ( - "Cannot convert Float64Index to dtype {dtype}; integer " + raise TypeError( + f"Cannot convert Float64Index to dtype {dtype}; integer " "values are required for conversion" - ).format(dtype=dtype) - raise TypeError(msg) + ) 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 diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 15639d4436d5f..979ab275f64f2 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -182,11 +182,8 @@ def __new__( } if not set(fields).issubset(valid_field_set): - raise TypeError( - "__new__() got an unexpected keyword argument {}".format( - list(set(fields) - valid_field_set)[0] - ) - ) + argument = list(set(fields) - valid_field_set)[0] + raise TypeError(f"__new__() got an unexpected keyword argument {argument}") if name is None and hasattr(data, "name"): name = data.name @@ -445,10 +442,10 @@ def __array_wrap__(self, result, context=None): return Index(result, name=name) elif isinstance(func, np.ufunc): if "M->M" not in func.types: - msg = "ufunc '{0}' not supported for the PeriodIndex" + msg = f"ufunc '{func.__name__}' not supported for the PeriodIndex" # This should be TypeError, but TypeError cannot be raised # from here because numpy catches. - raise ValueError(msg.format(func.__name__)) + raise ValueError(msg) if is_bool_dtype(result): return result @@ -508,7 +505,7 @@ def searchsorted(self, value, side="left", sorter=None): try: value = Period(value, freq=self.freq).ordinal except DateParseError: - raise KeyError("Cannot interpret '{}' as period".format(value)) + raise KeyError(f"Cannot interpret '{value}' as period") return self._ndarray_values.searchsorted(value, side=side, sorter=sorter) @@ -656,7 +653,7 @@ def get_loc(self, key, method=None, tolerance=None): pass except DateParseError: # A string with invalid format - raise KeyError("Cannot interpret '{}' as period".format(key)) + raise KeyError(f"Cannot interpret '{key}' as period") try: key = Period(key, freq=self.freq) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index f300cde3b5bcc..6ad70841a48b0 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -121,8 +121,8 @@ def from_range(cls, data, name=None, dtype=None): """ if not isinstance(data, range): raise TypeError( - "{0}(...) must be called with object coercible to a " - "range, {1} was passed".format(cls.__name__, repr(data)) + f"{cls.__name__}(...) must be called with object coercible to a " + f"range, {repr(data)} was passed" ) cls._validate_dtype(dtype) @@ -695,8 +695,7 @@ def __getitem__(self, key): return self._range[new_key] except IndexError: raise IndexError( - "index {key} is out of bounds for axis 0 " - "with size {size}".format(key=key, size=len(self)) + f"index {key} is out of bounds for axis 0 with size {len(self)}" ) elif is_scalar(key): raise IndexError( @@ -796,7 +795,7 @@ def _evaluate_numeric_binop(self, other): return op(self._int64index, other) # TODO: Do attrs get handled reliably? - name = "__{name}__".format(name=op.__name__) + name = f"__{op.__name__}__" return compat.set_function_name(_evaluate_numeric_binop, name, cls) cls.__add__ = _make_evaluate_binop(operator.add) diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 16db4106552a9..889075ebe4e31 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -166,10 +166,8 @@ def __new__( if is_scalar(data): raise TypeError( - "{cls}() must be called with a " - "collection of some kind, {data} was passed".format( - cls=cls.__name__, data=repr(data) - ) + f"{cls.__name__}() must be called with a " + f"collection of some kind, {repr(data)} was passed" ) if unit in {"Y", "y", "M"}:
towards #29547 - [ ] closes - [x] tests 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/30273
2019-12-14T07:43:41Z
2019-12-15T12:35:23Z
2019-12-15T12:35:23Z
2019-12-15T12:39:43Z
ENH: pass through schema keyword in to_parquet for pyarrow
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 6fd758abb1f33..17818118e587d 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -205,6 +205,8 @@ Other enhancements (:meth:`~DataFrame.to_parquet` / :func:`read_parquet`) using the `'pyarrow'` engine now preserve those data types with pyarrow >= 1.0.0 (:issue:`20612`). - The ``partition_cols`` argument in :meth:`DataFrame.to_parquet` now accepts a string (:issue:`27117`) +- :func:`to_parquet` now appropriately handles the ``schema`` argument for user defined schemas in the pyarrow engine. (:issue: `30270`) + Build Changes ^^^^^^^^^^^^^ @@ -798,7 +800,6 @@ I/O - Bug in :func:`read_json` where default encoding was not set to ``utf-8`` (:issue:`29565`) - Bug in :class:`PythonParser` where str and bytes were being mixed when dealing with the decimal field (:issue:`29650`) - :meth:`read_gbq` now accepts ``progress_bar_type`` to display progress bar while the data downloads. (:issue:`29857`) -- Plotting ^^^^^^^^ diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index 51eac8d481231..54e44ff33d079 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -91,11 +91,10 @@ def write( self.validate_dataframe(df) path, _, _, _ = get_filepath_or_buffer(path, mode="wb") - from_pandas_kwargs: Dict[str, Any] - if index is None: - from_pandas_kwargs = {} - else: - from_pandas_kwargs = {"preserve_index": index} + from_pandas_kwargs: Dict[str, Any] = {"schema": kwargs.pop("schema", None)} + if index is not None: + from_pandas_kwargs["preserve_index"] = index + table = self.api.Table.from_pandas(df, **from_pandas_kwargs) if partition_cols is not None: self.api.parquet.write_to_dataset( diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 251548e7caaab..0b8677d6b1415 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -517,6 +517,14 @@ def test_empty_dataframe(self, pa): df = pd.DataFrame() check_round_trip(df, pa) + def test_write_with_schema(self, pa): + import pyarrow + + df = pd.DataFrame({"x": [0, 1]}) + schema = pyarrow.schema([pyarrow.field("x", type=pyarrow.bool_())]) + out_df = df.astype(bool) + check_round_trip(df, pa, write_kwargs={"schema": schema}, expected=out_df) + @pytest.mark.skip(reason="broken test") @td.skip_if_no("pyarrow", min_version="0.15.0") def test_additional_extension_arrays(self, pa):
- [X] closes #30189 - [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/30270
2019-12-13T23:47:53Z
2019-12-18T10:39:32Z
2019-12-18T10:39:32Z
2019-12-18T10:39:46Z
Remove skiplist.pxd
diff --git a/pandas/_libs/skiplist.pxd b/pandas/_libs/skiplist.pxd deleted file mode 100644 index e827223bbe0a7..0000000000000 --- a/pandas/_libs/skiplist.pxd +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- -# See GH#27465 for reference on related-but-unused cython code - -cdef extern from "src/skiplist.h": - ctypedef struct node_t: - node_t **next - int *width - double value - int is_nil - int levels - int ref_count - - ctypedef struct skiplist_t: - node_t *head - node_t **tmp_chain - int *tmp_steps - int size - int maxlevels - - skiplist_t* skiplist_init(int) nogil - void skiplist_destroy(skiplist_t*) nogil - double skiplist_get(skiplist_t*, int, int*) nogil - int skiplist_insert(skiplist_t*, double) nogil - int skiplist_remove(skiplist_t*, double) nogil diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx index 8b1588c35b4de..0348843abc129 100644 --- a/pandas/_libs/window/aggregations.pyx +++ b/pandas/_libs/window/aggregations.pyx @@ -22,9 +22,27 @@ from pandas._libs.algos import is_monotonic from pandas._libs.util cimport numeric -from pandas._libs.skiplist cimport ( - skiplist_t, skiplist_init, skiplist_destroy, skiplist_get, skiplist_insert, - skiplist_remove) +cdef extern from "../src/skiplist.h": + ctypedef struct node_t: + node_t **next + int *width + double value + int is_nil + int levels + int ref_count + + ctypedef struct skiplist_t: + node_t *head + node_t **tmp_chain + int *tmp_steps + int size + int maxlevels + + skiplist_t* skiplist_init(int) nogil + void skiplist_destroy(skiplist_t*) nogil + double skiplist_get(skiplist_t*, int, int*) nogil + int skiplist_insert(skiplist_t*, double) nogil + int skiplist_remove(skiplist_t*, double) nogil cdef: float32_t MINfloat32 = np.NINF diff --git a/setup.py b/setup.py index 01d41ea5241f2..e42a570200dc3 100755 --- a/setup.py +++ b/setup.py @@ -687,6 +687,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "pyxfile": "_libs/window/aggregations", "language": "c++", "suffix": ".cpp", + "depends": ["pandas/_libs/src/skiplist.h"], }, "_libs.window.indexers": {"pyxfile": "_libs/window/indexers"}, "_libs.writers": {"pyxfile": "_libs/writers"},
Just placed header definitions where they are actually used follow up to #27465
https://api.github.com/repos/pandas-dev/pandas/pulls/30269
2019-12-13T22:55:08Z
2019-12-14T03:57:40Z
2019-12-14T03:57:40Z
2019-12-14T03:58:00Z
Made date time sources usage more explicit in setup.py
diff --git a/setup.py b/setup.py index 01d41ea5241f2..9a1a3a5848b66 100755 --- a/setup.py +++ b/setup.py @@ -549,17 +549,10 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): klib_include = ["pandas/_libs/src/klib"] -np_datetime_headers = [ +tseries_depends = [ "pandas/_libs/tslibs/src/datetime/np_datetime.h", "pandas/_libs/tslibs/src/datetime/np_datetime_strings.h", ] -np_datetime_sources = [ - "pandas/_libs/tslibs/src/datetime/np_datetime.c", - "pandas/_libs/tslibs/src/datetime/np_datetime_strings.c", -] - -tseries_depends = np_datetime_headers - ext_data = { "_libs.algos": { @@ -578,7 +571,6 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "pyxfile": "_libs/index", "include": klib_include, "depends": _pxi_dep["index"], - "sources": np_datetime_sources, }, "_libs.indexing": {"pyxfile": "_libs/indexing"}, "_libs.internals": {"pyxfile": "_libs/internals"}, @@ -612,38 +604,34 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "_libs.properties": {"pyxfile": "_libs/properties"}, "_libs.reshape": {"pyxfile": "_libs/reshape", "depends": []}, "_libs.sparse": {"pyxfile": "_libs/sparse", "depends": _pxi_dep["sparse"]}, - "_libs.tslib": { - "pyxfile": "_libs/tslib", - "depends": tseries_depends, - "sources": np_datetime_sources, - }, + "_libs.tslib": {"pyxfile": "_libs/tslib", "depends": tseries_depends}, "_libs.tslibs.c_timestamp": { "pyxfile": "_libs/tslibs/c_timestamp", "depends": tseries_depends, - "sources": np_datetime_sources, }, "_libs.tslibs.ccalendar": {"pyxfile": "_libs/tslibs/ccalendar"}, "_libs.tslibs.conversion": { "pyxfile": "_libs/tslibs/conversion", "depends": tseries_depends, - "sources": np_datetime_sources, + "sources": ["pandas/_libs/tslibs/src/datetime/np_datetime.c"], }, "_libs.tslibs.fields": { "pyxfile": "_libs/tslibs/fields", "depends": tseries_depends, - "sources": np_datetime_sources, }, "_libs.tslibs.frequencies": {"pyxfile": "_libs/tslibs/frequencies"}, "_libs.tslibs.nattype": {"pyxfile": "_libs/tslibs/nattype"}, "_libs.tslibs.np_datetime": { "pyxfile": "_libs/tslibs/np_datetime", - "depends": np_datetime_headers, - "sources": np_datetime_sources, + "depends": tseries_depends, + "sources": [ + "pandas/_libs/tslibs/src/datetime/np_datetime.c", + "pandas/_libs/tslibs/src/datetime/np_datetime_strings.c", + ], }, "_libs.tslibs.offsets": { "pyxfile": "_libs/tslibs/offsets", "depends": tseries_depends, - "sources": np_datetime_sources, }, "_libs.tslibs.parsing": { "pyxfile": "_libs/tslibs/parsing", @@ -654,33 +642,28 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "_libs.tslibs.period": { "pyxfile": "_libs/tslibs/period", "depends": tseries_depends, - "sources": np_datetime_sources, + "sources": ["pandas/_libs/tslibs/src/datetime/np_datetime.c"], }, "_libs.tslibs.resolution": { "pyxfile": "_libs/tslibs/resolution", "depends": tseries_depends, - "sources": np_datetime_sources, }, "_libs.tslibs.strptime": { "pyxfile": "_libs/tslibs/strptime", "depends": tseries_depends, - "sources": np_datetime_sources, }, "_libs.tslibs.timedeltas": { "pyxfile": "_libs/tslibs/timedeltas", - "depends": np_datetime_headers, - "sources": np_datetime_sources, + "depends": tseries_depends, }, "_libs.tslibs.timestamps": { "pyxfile": "_libs/tslibs/timestamps", "depends": tseries_depends, - "sources": np_datetime_sources, }, "_libs.tslibs.timezones": {"pyxfile": "_libs/tslibs/timezones"}, "_libs.tslibs.tzconversion": { "pyxfile": "_libs/tslibs/tzconversion", "depends": tseries_depends, - "sources": np_datetime_sources, }, "_libs.testing": {"pyxfile": "_libs/testing"}, "_libs.window.aggregations": { @@ -738,7 +721,10 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "pandas/_libs/src/ujson/lib/ultrajsonenc.c", "pandas/_libs/src/ujson/lib/ultrajsondec.c", ] - + np_datetime_sources + + [ + "pandas/_libs/tslibs/src/datetime/np_datetime.c", + "pandas/_libs/tslibs/src/datetime/np_datetime_strings.c", + ] ), include_dirs=[ "pandas/_libs/src/ujson/python",
Not sure this fully solves #30236 but doesn't hurt and makes things more explicit
https://api.github.com/repos/pandas-dev/pandas/pulls/30266
2019-12-13T22:08:24Z
2019-12-18T18:34:02Z
2019-12-18T18:34:02Z
2019-12-18T18:34:06Z
CLN: Assorted cleanups
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 0de7a2e745531..b398a197a4bc0 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -244,13 +244,13 @@ def maybe_upcast_putmask(result: np.ndarray, mask: np.ndarray, other): necessary. mask : boolean ndarray other : scalar - The source value + The source value. Returns ------- result : ndarray - changed : boolean - Set to true if the result array was upcasted + changed : bool + Set to true if the result array was upcasted. Examples -------- @@ -337,6 +337,21 @@ def changeit(): def maybe_promote(dtype, fill_value=np.nan): + """ + Find the minimal dtype that can hold both the given dtype and fill_value. + + Parameters + ---------- + dtype : np.dtype or ExtensionDtype + fill_value : scalar, default np.nan + + Returns + ------- + dtype + Upcasted from dtype argument if necessary. + fill_value + Upcasted from fill_value argument if necessary. + """ if not is_scalar(fill_value) and not is_object_dtype(dtype): # with object dtype there is nothing to promote, and the user can # pass pretty much any weird fill_value they like @@ -592,11 +607,11 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False): def infer_dtype_from_array(arr, pandas_dtype: bool = False): """ - Infer the dtype from a scalar or array. + Infer the dtype from an array. Parameters ---------- - arr : scalar or array + arr : array pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, array belongs to pandas extension types @@ -622,7 +637,6 @@ def infer_dtype_from_array(arr, pandas_dtype: bool = False): >>> infer_dtype_from_array([1, '1']) (numpy.object_, [1, '1']) - """ if isinstance(arr, np.ndarray): @@ -686,10 +700,12 @@ def maybe_upcast(values, fill_value=np.nan, dtype=None, copy: bool = False): Parameters ---------- - values : the ndarray that we want to maybe upcast + values : ndarray or ExtensionArray + The array that we want to maybe upcast. fill_value : what we want to fill with dtype : if None, then use the dtype of the values, else coerce to this type - copy : if True always make a copy even if no upcast is required + copy : bool, default True + If True always make a copy even if no upcast is required. """ if not is_scalar(fill_value) and not is_object_dtype(values.dtype): # We allow arbitrary fill values for object dtype diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 55dd91a8129b5..851d353a79eb1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4354,7 +4354,7 @@ def _maybe_casted_values(index, labels=None): values = values._data if mask.any(): - values, changed = maybe_upcast_putmask(values, mask, np.nan) + values, _ = maybe_upcast_putmask(values, mask, np.nan) if issubclass(values_type, DatetimeLikeArray): values = values_type(values, dtype=values_dtype) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index fc2412ceaca0e..470c3c76afe12 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -331,11 +331,12 @@ def __new__( # extension dtype elif is_extension_array_dtype(data) or is_extension_array_dtype(dtype): - data = np.asarray(data) if not (dtype is None or is_object_dtype(dtype)): # coerce to the provided dtype ea_cls = dtype.construct_array_type() data = ea_cls._from_sequence(data, dtype=dtype, copy=False) + else: + data = np.asarray(data, dtype=object) # coerce to the object dtype data = data.astype(object) diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 77e9f0b44c0cb..8de955e5ff2cf 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -314,7 +314,7 @@ def _get_values( # promote if needed else: - values, changed = maybe_upcast_putmask(values, mask, fill_value) + values, _ = maybe_upcast_putmask(values, mask, fill_value) # return a platform independent precision dtype dtype_max = dtype diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py index de34258f863d0..40bf19c60e144 100644 --- a/pandas/core/ops/array_ops.py +++ b/pandas/core/ops/array_ops.py @@ -110,7 +110,7 @@ def masked_arith_op(x, y, op): with np.errstate(all="ignore"): result[mask] = op(xrav[mask], y) - result, changed = maybe_upcast_putmask(result, ~mask, np.nan) + result, _ = maybe_upcast_putmask(result, ~mask, np.nan) result = result.reshape(x.shape) # 2D compat return result diff --git a/pandas/core/strings.py b/pandas/core/strings.py index d4d8be90402b7..24e2e674f6ae3 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -74,10 +74,12 @@ def cat_core(list_of_columns: List, sep: str): """ if sep == "": # no need to interleave sep if it is empty - return np.sum(list_of_columns, axis=0) + arr_of_cols = np.asarray(list_of_columns, dtype=object) + return np.sum(arr_of_cols, axis=0) list_with_sep = [sep] * (2 * len(list_of_columns) - 1) list_with_sep[::2] = list_of_columns - return np.sum(list_with_sep, axis=0) + arr_with_sep = np.asarray(list_with_sep) + return np.sum(arr_with_sep, axis=0) def cat_safe(list_of_columns: List, sep: str): diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index f4c3955bedb70..62b6211e2d82d 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1314,7 +1314,7 @@ def create_table_index( optlevel : int or None, default None Optimization level, if None, pytables defaults to 6. kind : str or None, default None - Kind of index, if None, pytables defaults to "medium" + Kind of index, if None, pytables defaults to "medium". Raises ------ @@ -1741,24 +1741,24 @@ def _read_group(self, group: "Node"): class TableIterator: - """ define the iteration interface on a table - - Parameters - ---------- + """ + Define the iteration interface on a table - store : the reference store - s : the referred storer - func : the function to execute the query - where : the where of the query - nrows : the rows to iterate on - start : the passed start value (default is None) - stop : the passed stop value (default is None) - iterator : bool, default False - Whether to use the default iterator. - chunksize : the passed chunking value (default is 100000) - auto_close : boolean, automatically close the store at the end of - iteration, default is False - """ + Parameters + ---------- + store : HDFStore + s : the referred storer + func : the function to execute the query + where : the where of the query + nrows : the rows to iterate on + start : the passed start value (default is None) + stop : the passed stop value (default is None) + iterator : bool, default False + Whether to use the default iterator. + chunksize : the passed chunking value (default is 100000) + auto_close : bool, default False + Whether to automatically close the store at the end of iteration. + """ chunksize: Optional[int] store: HDFStore @@ -1974,7 +1974,8 @@ def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str): if values.dtype.fields is not None: values = values[self.cname] - values = _maybe_convert(values, self.kind, encoding, errors) + val_kind = _ensure_decoded(self.kind) + values = _maybe_convert(values, val_kind, encoding, errors) kwargs = dict() kwargs["name"] = _ensure_decoded(self.index_name) @@ -2500,13 +2501,18 @@ class Fixed: pandas_kind: str obj_type: Type[Union[DataFrame, Series]] ndim: int + encoding: str parent: HDFStore group: "Node" errors: str is_table = False def __init__( - self, parent: HDFStore, group: "Node", encoding=None, errors: str = "strict" + self, + parent: HDFStore, + group: "Node", + encoding: str = "UTF-8", + errors: str = "strict", ): assert isinstance(parent, HDFStore), type(parent) assert _table_mod is not None # needed for mypy @@ -2556,10 +2562,6 @@ def copy(self): new_self = copy.copy(self) return new_self - @property - def storage_obj_type(self): - return self.obj_type - @property def shape(self): return self.nrows @@ -2584,10 +2586,6 @@ def _complevel(self) -> int: def _fletcher32(self) -> bool: return self.parent._fletcher32 - @property - def _complib(self): - return self.parent._complib - @property def attrs(self): return self.group._v_attrs @@ -3314,12 +3312,12 @@ def data_orientation(self): def queryables(self) -> Dict[str, Any]: """ return a dict of the kinds allowable columns for this object """ + # mypy doesnt recognize DataFrame._AXIS_NAMES, so we re-write it here + axis_names = {0: "index", 1: "columns"} + # compute the values_axes queryables d1 = [(a.cname, a) for a in self.index_axes] - d2 = [ - (self.storage_obj_type._AXIS_NAMES[axis], None) - for axis, values in self.non_index_axes - ] + d2 = [(axis_names[axis], None) for axis, values in self.non_index_axes] d3 = [ (v.cname, v) for v in self.values_axes if v.name in set(self.data_columns) ] @@ -3342,9 +3340,9 @@ def _get_metadata_path(self, key: str) -> str: group = self.group._v_pathname return f"{group}/meta/{key}/meta" - def write_metadata(self, key: str, values): + def write_metadata(self, key: str, values: np.ndarray): """ - write out a meta data array to the key as a fixed-format Series + Write out a metadata array to the key as a fixed-format Series. Parameters ---------- @@ -3498,9 +3496,7 @@ def f(i, c): def create_index(self, columns=None, optlevel=None, kind: Optional[str] = None): """ - Create a pytables index on the specified columns - note: cannot index Time64Col() or ComplexCol currently; - PyTables must be >= 3.0 + Create a pytables index on the specified columns. Parameters ---------- @@ -3515,12 +3511,16 @@ def create_index(self, columns=None, optlevel=None, kind: Optional[str] = None): optlevel : int or None, default None Optimization level, if None, pytables defaults to 6. kind : str or None, default None - Kind of index, if None, pytables defaults to "medium" + Kind of index, if None, pytables defaults to "medium". Raises ------ - raises if the node is not a table + TypeError if trying to create an index on a complex-type column. + Notes + ----- + Cannot index Time64Col or ComplexCol. + Pytables must be >= 3.0. """ if not self.infer_axes(): @@ -3964,10 +3964,10 @@ def process_filter(field, filt): def create_description( self, - complib=None, - complevel: Optional[int] = None, - fletcher32: bool = False, - expectedrows: Optional[int] = None, + complib, + complevel: Optional[int], + fletcher32: bool, + expectedrows: Optional[int], ) -> Dict[str, Any]: """ create the description of the table from the axes & values """ @@ -4216,7 +4216,13 @@ def write_data(self, chunksize: Optional[int], dropna: bool = False): values=[v[start_i:end_i] for v in bvalues], ) - def write_data_chunk(self, rows, indexes, mask, values): + def write_data_chunk( + self, + rows: np.ndarray, + indexes: List[np.ndarray], + mask: Optional[np.ndarray], + values: List[np.ndarray], + ): """ Parameters ---------- @@ -4424,7 +4430,6 @@ class AppendableSeriesTable(AppendableFrameTable): table_type = "appendable_series" ndim = 2 obj_type = Series - storage_obj_type = DataFrame @property def is_transposed(self) -> bool: @@ -4446,7 +4451,7 @@ def read( columns=None, start: Optional[int] = None, stop: Optional[int] = None, - ): + ) -> Series: is_multi_index = self.is_multi_index if columns is not None and is_multi_index: @@ -4589,7 +4594,7 @@ def read( return df -def _reindex_axis(obj, axis: int, labels: Index, other=None): +def _reindex_axis(obj: DataFrame, axis: int, labels: Index, other=None) -> DataFrame: ax = obj._get_axis(axis) labels = ensure_index(labels) @@ -4652,7 +4657,7 @@ def _set_tz( return values -def _convert_index(name: str, index: Index, encoding=None, errors="strict"): +def _convert_index(name: str, index: Index, encoding: str, errors: str) -> IndexCol: assert isinstance(name, str) index_name = index.name @@ -4711,7 +4716,9 @@ def _convert_index(name: str, index: Index, encoding=None, errors="strict"): return IndexCol(name, converted, kind, atom, index_name=index_name,) -def _unconvert_index(data, kind: str, encoding=None, errors="strict"): +def _unconvert_index( + data, kind: str, encoding: str, errors: str +) -> Union[np.ndarray, Index]: index: Union[Index, np.ndarray] if kind == "datetime64": @@ -4802,61 +4809,59 @@ def _maybe_convert_for_string_atom( return data_converted -def _convert_string_array(data, encoding, errors, itemsize=None): +def _convert_string_array(data: np.ndarray, encoding: str, errors: str) -> np.ndarray: """ - we take a string-like that is object dtype and coerce to a fixed size - string type + Take a string-like that is object dtype and coerce to a fixed size string type. Parameters ---------- - data : a numpy array of object dtype - encoding : None or string-encoding - errors : handler for encoding errors - itemsize : integer, optional, defaults to the max length of the strings + data : np.ndarray[object] + encoding : str + errors : str + Handler for encoding errors. Returns ------- - data in a fixed-length string dtype, encoded to bytes if needed + np.ndarray[fixed-length-string] """ # encode if needed - if encoding is not None and len(data): + if len(data): data = ( Series(data.ravel()).str.encode(encoding, errors).values.reshape(data.shape) ) # create the sized dtype - if itemsize is None: - ensured = ensure_object(data.ravel()) - itemsize = max(1, libwriters.max_len_string_array(ensured)) + ensured = ensure_object(data.ravel()) + itemsize = max(1, libwriters.max_len_string_array(ensured)) data = np.asarray(data, dtype=f"S{itemsize}") return data -def _unconvert_string_array(data, nan_rep=None, encoding=None, errors="strict"): +def _unconvert_string_array( + data: np.ndarray, nan_rep, encoding: str, errors: str +) -> np.ndarray: """ - inverse of _convert_string_array + Inverse of _convert_string_array. Parameters ---------- - data : fixed length string dtyped array - nan_rep : the storage repr of NaN, optional - encoding : the encoding of the data, optional - errors : handler for encoding errors, default 'strict' + data : np.ndarray[fixed-length-string] + nan_rep : the storage repr of NaN + encoding : str + errors : str + Handler for encoding errors. Returns ------- - an object array of the decoded data - + np.ndarray[object] + Decoded data. """ shape = data.shape data = np.asarray(data.ravel(), dtype=object) - # guard against a None encoding (because of a legacy - # where the passed encoding is actually None) - encoding = _ensure_encoding(encoding) - if encoding is not None and len(data): + if len(data): itemsize = libwriters.max_len_string_array(ensure_object(data)) dtype = f"U{itemsize}" @@ -4873,8 +4878,8 @@ def _unconvert_string_array(data, nan_rep=None, encoding=None, errors="strict"): return data.reshape(shape) -def _maybe_convert(values: np.ndarray, val_kind, encoding: str, errors: str): - val_kind = _ensure_decoded(val_kind) +def _maybe_convert(values: np.ndarray, val_kind: str, encoding: str, errors: str): + assert isinstance(val_kind, str), type(val_kind) if _need_convert(val_kind): conv = _get_converter(val_kind, encoding, errors) values = conv(values) @@ -4885,12 +4890,14 @@ def _get_converter(kind: str, encoding: str, errors: str): if kind == "datetime64": return lambda x: np.asarray(x, dtype="M8[ns]") elif kind == "string": - return lambda x: _unconvert_string_array(x, encoding=encoding, errors=errors) + return lambda x: _unconvert_string_array( + x, nan_rep=None, encoding=encoding, errors=errors + ) else: # pragma: no cover raise ValueError(f"invalid kind {kind}") -def _need_convert(kind) -> bool: +def _need_convert(kind: str) -> bool: if kind in ("datetime64", "string"): return True return False diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 3fb4e291d7d91..47ac4113d90ce 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -449,7 +449,7 @@ def test_scientific_no_exponent(self): def test_convert_non_hashable(self): # GH13324 # make sure that we are handing non-hashables - arr = np.array([[10.0, 2], 1.0, "apple"]) + arr = np.array([[10.0, 2], 1.0, "apple"], dtype=object) result = lib.maybe_convert_numeric(arr, set(), False, True) tm.assert_numpy_array_equal(result, np.array([np.nan, 1.0, np.nan])) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 90ff7a585a323..ad6e0c963e730 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -1725,9 +1725,9 @@ def test_constructor_with_datetimes(self): expected = DataFrame({"a": i.to_series().reset_index(drop=True), "b": i_no_tz}) tm.assert_frame_equal(df, expected) - def test_constructor_datetimes_with_nulls(self): - # gh-15869, GH#11220 - for arr in [ + @pytest.mark.parametrize( + "arr", + [ np.array([None, None, None, None, datetime.now(), None]), np.array([None, None, datetime.now(), None]), [[np.datetime64("NaT")], [None]], @@ -1736,10 +1736,13 @@ def test_constructor_datetimes_with_nulls(self): [[None], [pd.NaT]], [[pd.NaT], [np.datetime64("NaT")]], [[pd.NaT], [None]], - ]: - result = DataFrame(arr).dtypes - expected = Series([np.dtype("datetime64[ns]")]) - tm.assert_series_equal(result, expected) + ], + ) + def test_constructor_datetimes_with_nulls(self, arr): + # gh-15869, GH#11220 + result = DataFrame(arr).dtypes + expected = Series([np.dtype("datetime64[ns]")]) + tm.assert_series_equal(result, expected) def test_constructor_for_list_with_dtypes(self): # test list of lists/ndarrays diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 8dcc77fc2fbc1..bb150c5825650 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -761,8 +761,9 @@ def test_array_list(self): ["a", "b"], {"key": "val"}, ] - arr = np.array(arr_list) - tm.assert_numpy_array_equal(np.array(ujson.decode(ujson.encode(arr))), arr) + arr = np.array(arr_list, dtype=object) + result = np.array(ujson.decode(ujson.encode(arr)), dtype=object) + tm.assert_numpy_array_equal(result, arr) def test_array_float(self): dtype = np.float32 diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index ae16d0fa651d2..5d9ee691edbf0 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -120,7 +120,8 @@ def test_append_index(self): (1.2, tz.localize(datetime.datetime(2011, 1, 2)), "B"), (1.3, tz.localize(datetime.datetime(2011, 1, 3)), "C"), ] - + expected_tuples + + expected_tuples, + dtype=object, ), None, ) diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 584550d562b0d..2e651c0b35deb 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -2857,7 +2857,8 @@ def test_partition_index(self): result = values.str.partition("_", expand=False) exp = Index( np.array( - [("a", "_", "b_c"), ("c", "_", "d_e"), ("f", "_", "g_h"), np.nan, None] + [("a", "_", "b_c"), ("c", "_", "d_e"), ("f", "_", "g_h"), np.nan, None], + dtype=object, ) ) tm.assert_index_equal(result, exp) @@ -2866,7 +2867,8 @@ def test_partition_index(self): result = values.str.rpartition("_", expand=False) exp = Index( np.array( - [("a_b", "_", "c"), ("c_d", "_", "e"), ("f_g", "_", "h"), np.nan, None] + [("a_b", "_", "c"), ("c_d", "_", "e"), ("f_g", "_", "h"), np.nan, None], + dtype=object, ) ) tm.assert_index_equal(result, exp)
Many of these are broken off from #30035.
https://api.github.com/repos/pandas-dev/pandas/pulls/30260
2019-12-13T17:45:36Z
2019-12-15T21:43:42Z
2019-12-15T21:43:42Z
2019-12-16T01:04:30Z
CLN: more lgtm.com cleanups
diff --git a/pandas/core/arrays/_ranges.py b/pandas/core/arrays/_ranges.py index 2cae2c9250ea5..20e4cf70eddcf 100644 --- a/pandas/core/arrays/_ranges.py +++ b/pandas/core/arrays/_ranges.py @@ -179,7 +179,6 @@ def _generate_range_overflow_safe_signed( # watch out for very special case in which we just slightly # exceed implementation bounds, but when passing the result to # np.arange will get a result slightly within the bounds - assert endpoint >= 0 result = np.uint64(endpoint) + np.uint64(addend) i64max = np.uint64(np.iinfo(np.int64).max) assert result > i64max diff --git a/pandas/core/base.py b/pandas/core/base.py index 88b8fe405c8e4..c900a0ba722c0 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -309,7 +309,6 @@ def _aggregate(self, arg, *args, **kwargs): None if not required """ is_aggregator = lambda x: isinstance(x, (list, tuple, dict)) - is_nested_renamer = False _axis = kwargs.pop("_axis", None) if _axis is None: @@ -398,24 +397,7 @@ def _agg(arg, func): keys = list(arg.keys()) result = OrderedDict() - # nested renamer - if is_nested_renamer: - result = list(_agg(arg, _agg_1dim).values()) - - if all(isinstance(r, dict) for r in result): - - result, results = OrderedDict(), result - for r in results: - result.update(r) - keys = list(result.keys()) - - else: - - if self._selection is not None: - keys = None - - # some selection on the object - elif self._selection is not None: + if self._selection is not None: sl = set(self._selection_list) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index ec183fcfc154a..bfe3c628169e9 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1131,7 +1131,6 @@ def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame: obj = self._obj_with_exclusions result: OrderedDict = OrderedDict() cannot_agg = [] - errors = None for item in obj: data = obj[item] colg = SeriesGroupBy(data, selection=item, grouper=self.grouper) @@ -1157,10 +1156,6 @@ def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame: if cannot_agg: result_columns = result_columns.drop(cannot_agg) - # GH6337 - if not len(result_columns) and errors is not None: - raise errors - return DataFrame(result, columns=result_columns) def _wrap_applied_output(self, keys, values, not_indexed_same=False): diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 7b0cc871cbcbc..4c665ad596eb1 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2204,9 +2204,6 @@ def reorder_levels(self, order): levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False ) - def __getslice__(self, i, j): - return self.__getitem__(slice(i, j)) - def _get_codes_for_sorting(self): """ we categorizing our codes by using the diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 7cb693474c82f..c6f30ef65e9d5 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -195,7 +195,6 @@ def get_reindexed_values(self, empty_dtype, upcasted_na): return array( np.full(self.shape[1], fill_value.value), dtype=empty_dtype ) - pass elif getattr(self.block, "is_categorical", False): pass elif getattr(self.block, "is_extension", False): diff --git a/pandas/core/ops/missing.py b/pandas/core/ops/missing.py index 3bb7bb022dd3a..96a615d488bf2 100644 --- a/pandas/core/ops/missing.py +++ b/pandas/core/ops/missing.py @@ -168,7 +168,7 @@ def dispatch_fill_zeros(op, left, right, result): # Note: no need to do this for truediv; in py3 numpy behaves the way # we want. result = mask_zero_div_zero(left, right, result) - elif op is op is rfloordiv: + elif op is rfloordiv: # Note: no need to do this for rtruediv; in py3 numpy behaves the way # we want. result = mask_zero_div_zero(right, left, result) diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index feb895a099da5..5386c222f7bfb 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -387,12 +387,12 @@ def __call__(self): except ValueError: return [] - if dmin > dmax: - dmax, dmin = dmin, dmax # We need to cap at the endpoints of valid datetime # FIXME: dont leave commented-out # TODO(wesm) unused? + # if dmin > dmax: + # dmax, dmin = dmin, dmax # delta = relativedelta(dmax, dmin) # try: # start = dmin - delta diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py index 7c6f2fea97933..b0eeb7b96e0eb 100755 --- a/scripts/validate_docstrings.py +++ b/scripts/validate_docstrings.py @@ -965,7 +965,7 @@ def header(title, width=80, char="#"): "]{text}\n" ) else: - raise ValueError('Unknown output_format "{}"'.format(output_format)) + raise ValueError(f'Unknown output_format "{output_format}"') output = "" for name, res in result.items(): @@ -977,11 +977,10 @@ def header(title, width=80, char="#"): continue exit_status += 1 output += output_format.format( - name=name, path=res["file"], row=res["file_line"], code=err_code, - text="{}: {}".format(name, err_desc), + text=f"{name}: {err_desc}", ) sys.stdout.write(output)
https://api.github.com/repos/pandas-dev/pandas/pulls/30259
2019-12-13T17:03:49Z
2019-12-15T21:39:26Z
2019-12-15T21:39:26Z
2019-12-16T00:34:04Z
CLN: various lgtm.com cleanups
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index ef3d8cd53596b..14a3c3c008e92 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -320,7 +320,6 @@ def apply_series_generator(self) -> Tuple[ResType, "Index"]: series_gen = self.series_generator res_index = self.result_index - i = None keys = [] results = {} if self.ignore_failures: diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 2cd8aafe00f37..e41f2a840d151 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -2109,7 +2109,6 @@ def _validate_dt64_dtype(dtype): dtype = pandas_dtype(dtype) if is_dtype_equal(dtype, np.dtype("M8")): # no precision, disallowed GH#24806 - dtype = _NS_DTYPE msg = ( "Passing in 'datetime64' dtype with no precision is not allowed. " "Please pass in 'datetime64[ns]' instead." diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index d47e7e3df27e1..c0ca30be34ad5 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -78,7 +78,8 @@ def itemsize(self): @classmethod def construct_array_type(cls): - """Return the array type associated with this dtype + """ + Return the array type associated with this dtype. Returns ------- diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 13748e03e856d..deec30dfe34ff 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -79,7 +79,15 @@ def construct_from_string(cls, string): f"Cannot construct a 'PandasDtype' from '{string}'" ) from err + @classmethod def construct_array_type(cls): + """ + Return the array type associated with this dtype. + + Returns + ------- + type + """ return PandasArray @property diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index a295dfed2cf96..935f657416396 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -168,6 +168,13 @@ def __repr__(self) -> str: @classmethod def construct_array_type(cls): + """ + Return the array type associated with this dtype. + + Returns + ------- + type + """ from .array import SparseArray return SparseArray diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index b51773961811b..db4effa608582 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -1122,7 +1122,6 @@ def _validate_td64_dtype(dtype): dtype = pandas_dtype(dtype) if is_dtype_equal(dtype, np.dtype("timedelta64")): # no precision disallowed GH#24806 - dtype = _TD_DTYPE msg = ( "Passing in 'timedelta' dtype with no precision is not allowed. " "Please pass in 'timedelta64[ns]' instead." diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index ae544376c452e..1dda51da49ffb 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -183,7 +183,7 @@ def names(self) -> Optional[List[str]]: @classmethod def construct_array_type(cls): """ - Return the array type associated with this dtype + Return the array type associated with this dtype. Returns ------- diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 4421fad5f19d1..77ec182be5ed4 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -486,7 +486,7 @@ def _hash_categories(categories, ordered: Ordered = True) -> int: @classmethod def construct_array_type(cls): """ - Return the array type associated with this dtype + Return the array type associated with this dtype. Returns ------- @@ -668,7 +668,7 @@ def __init__(self, unit="ns", tz=None): unit = result.unit tz = result.tz msg = ( - "Passing a dtype alias like 'datetime64[ns, {tz}]' " + f"Passing a dtype alias like 'datetime64[ns, {tz}]' " "to DatetimeTZDtype is no longer supported. Use " "'DatetimeTZDtype.construct_from_string()' instead." ) @@ -704,7 +704,7 @@ def tz(self): @classmethod def construct_array_type(cls): """ - Return the array type associated with this dtype + Return the array type associated with this dtype. Returns ------- @@ -936,6 +936,13 @@ def is_dtype(cls, dtype) -> bool: @classmethod def construct_array_type(cls): + """ + Return the array type associated with this dtype. + + Returns + ------- + type + """ from pandas.core.arrays import PeriodArray return PeriodArray @@ -1030,7 +1037,7 @@ def subtype(self): @classmethod def construct_array_type(cls): """ - Return the array type associated with this dtype + Return the array type associated with this dtype. Returns ------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index fa85c54eb42fa..0c5caac36054e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2606,7 +2606,6 @@ def _ixs(self, i: int, axis: int = 0): """ # irow if axis == 0: - label = self.index[i] new_values = self._data.fast_xs(i) # if we are a copy, mark as such diff --git a/pandas/core/generic.py b/pandas/core/generic.py index cf2244b4df4d2..4508f02757def 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5746,8 +5746,6 @@ def __deepcopy__(self: FrameOrSeries, memo=None) -> FrameOrSeries: memo, default None Standard signature. Unused """ - if memo is None: - memo = {} return self.copy(deep=True) def _convert( diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index b0df04f18ff1d..63d6e88850cdd 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -131,7 +131,7 @@ def _get_grouper(self, obj, validate: bool = True): """ self._set_grouper(obj) - self.grouper, exclusions, self.obj = get_grouper( + self.grouper, _, self.obj = get_grouper( self.obj, [self.key], axis=self.axis, diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index fc2412ceaca0e..22dd25c0448d2 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -910,8 +910,6 @@ def __deepcopy__(self, memo=None): memo, default None Standard signature. Unused """ - if memo is None: - memo = {} return self.copy(deep=True) # -------------------------------------------------------------------- diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 8a543832b50fe..610a39a05148b 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -3024,7 +3024,6 @@ def _merge_blocks(blocks, dtype=None, _can_consolidate=True): if dtype is None: if len({b.dtype for b in blocks}) != 1: raise AssertionError("_merge_blocks are invalid!") - dtype = blocks[0].dtype # FIXME: optimization potential in case all mgrs contain slices and # combination of those slices is a slice, too. diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index a8dcc995e48da..b74eda38a08fe 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -230,11 +230,9 @@ def get_new_values(self): if needs_i8_conversion(values): sorted_values = sorted_values.view("i8") new_values = new_values.view("i8") - name = "int64" elif is_bool_dtype(values): sorted_values = sorted_values.astype("object") new_values = new_values.astype("object") - name = "object" else: sorted_values = sorted_values.astype(name, copy=False) diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index dc9eede7e4d52..8957389ac2b13 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -27,7 +27,7 @@ def _args_adjust(self): values = np.ravel(values) values = values[~isna(values)] - hist, self.bins = np.histogram( + _, self.bins = np.histogram( values, bins=self.bins, range=self.kwds.get("range", None), diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py index 479f8dbad0418..f2a4e73e7b6ad 100644 --- a/pandas/tests/arrays/test_array.py +++ b/pandas/tests/arrays/test_array.py @@ -287,6 +287,13 @@ class DecimalDtype2(DecimalDtype): @classmethod def construct_array_type(cls): + """ + Return the array type associated with this dtype. + + Returns + ------- + type + """ return DecimalArray2 diff --git a/pandas/tests/extension/arrow/arrays.py b/pandas/tests/extension/arrow/arrays.py index 86e23b3264456..b0e5a6f85feeb 100644 --- a/pandas/tests/extension/arrow/arrays.py +++ b/pandas/tests/extension/arrow/arrays.py @@ -37,6 +37,13 @@ def construct_from_string(cls, string): @classmethod def construct_array_type(cls): + """ + Return the array type associated with this dtype. + + Returns + ------- + type + """ return ArrowBoolArray def _is_boolean(self): @@ -60,6 +67,13 @@ def construct_from_string(cls, string): @classmethod def construct_array_type(cls): + """ + Return the array type associated with this dtype. + + Returns + ------- + type + """ return ArrowStringArray diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 0b0865c424f34..74f1e3cfbaf20 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -27,7 +27,8 @@ def __repr__(self) -> str: @classmethod def construct_array_type(cls): - """Return the array type associated with this dtype + """ + Return the array type associated with this dtype. Returns ------- diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 28929d50718b6..46ca7bd8f760a 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -31,7 +31,8 @@ class JSONDtype(ExtensionDtype): @classmethod def construct_array_type(cls): - """Return the array type associated with this dtype + """ + Return the array type associated with this dtype. Returns -------
https://api.github.com/repos/pandas-dev/pandas/pulls/30258
2019-12-13T16:11:36Z
2019-12-15T21:46:17Z
2019-12-15T21:46:17Z
2019-12-16T00:33:55Z
DOC: .get_slice_bound in MultiIndex needs documentation.
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 05a4da28eb0a1..0908bc6209369 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1,7 +1,7 @@ from collections import OrderedDict import datetime from sys import getsizeof -from typing import List, Optional +from typing import Hashable, List, Optional, Sequence, Union import warnings import numpy as np @@ -2430,7 +2430,53 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None): return target, indexer - def get_slice_bound(self, label, side, kind): + def get_slice_bound( + self, label: Union[Hashable, Sequence[Hashable]], side: str, kind: str + ) -> int: + """ + For an ordered MultiIndex, compute slice bound + that corresponds to given label. + + Returns leftmost (one-past-the-rightmost if `side=='right') position + of given label. + + Parameters + ---------- + label : object or tuple of objects + side : {'left', 'right'} + kind : {'loc', 'getitem'} + + Returns + ------- + int + Index of label. + + Notes + ----- + This method only works if level 0 index of the MultiIndex is lexsorted. + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays([list('abbc'), list('gefd')]) + + Get the locations from the leftmost 'b' in the first level + until the end of the multiindex: + + >>> mi.get_slice_bound('b', side="left", kind="loc") + 1 + + Like above, but if you get the locations from the rightmost + 'b' in the first level and 'f' in the second level: + + >>> mi.get_slice_bound(('b','f'), side="right", kind="loc") + 3 + + See Also + -------- + MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.get_locs : Get location for a label/slice/list/mask or a + sequence of such. + """ if not isinstance(label, tuple): label = (label,)
- [x] closes #29967 - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry I'm not good at English. So if there are wrong sentences or awkward sentences, please let me know.
https://api.github.com/repos/pandas-dev/pandas/pulls/30257
2019-12-13T13:56:19Z
2020-01-01T17:27:21Z
2020-01-01T17:27:21Z
2020-06-17T11:31:50Z
CI: wrap ExcelFile.__del__ in try/except
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 7cb1309ae8d41..81d3d46f78bdb 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -903,5 +903,9 @@ def __exit__(self, exc_type, exc_value, traceback): self.close() def __del__(self): - # Ensure we don't leak file descriptors - self.close() + # Ensure we don't leak file descriptors, but put in try/except in case + # attributes are already deleted + try: + self.close() + except AttributeError: + pass
Closes https://github.com/pandas-dev/pandas/issues/30217
https://api.github.com/repos/pandas-dev/pandas/pulls/30255
2019-12-13T10:08:40Z
2019-12-13T17:31:05Z
2019-12-13T17:31:05Z
2019-12-14T07:45:52Z
DEPR: change DataFrame.append default sort kwarg
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index fa85c54eb42fa..66226d4ef0fe7 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6664,7 +6664,7 @@ def infer(x): # ---------------------------------------------------------------------- # Merging / joining methods - def append(self, other, ignore_index=False, verify_integrity=False, sort=None): + def append(self, other, ignore_index=False, verify_integrity=False, sort=False): """ Append rows of `other` to the end of caller, returning a new object. @@ -6678,14 +6678,13 @@ def append(self, other, ignore_index=False, verify_integrity=False, sort=None): If True, do not use the index labels. verify_integrity : bool, default False If True, raise ValueError on creating index with duplicates. - sort : bool, default None + sort : bool, default False Sort columns if the columns of `self` and `other` are not aligned. - The default sorting is deprecated and will change to not-sorting - in a future version of pandas. Explicitly pass ``sort=True`` to - silence the warning and sort. Explicitly pass ``sort=False`` to - silence the warning and not sort. .. versionadded:: 0.23.0 + .. versionchanged:: 1.0.0 + + Changed to not sort by default. Returns -------
xref #20613 AFAICT this doesn't break any tests, was this supposed to have been changed along with the default in `concat` #29786 ?
https://api.github.com/repos/pandas-dev/pandas/pulls/30251
2019-12-13T01:15:27Z
2019-12-15T21:46:58Z
2019-12-15T21:46:58Z
2019-12-16T01:06:10Z
CLN : f-string instead of str.format() in pandas/utils and pandas/io/formats
diff --git a/pandas/io/formats/css.py b/pandas/io/formats/css.py index 6bc5f56bb5f7f..583dd49d4c66a 100644 --- a/pandas/io/formats/css.py +++ b/pandas/io/formats/css.py @@ -18,8 +18,7 @@ def expand(self, prop, value): mapping = self.SIDE_SHORTHANDS[len(tokens)] except KeyError: warnings.warn( - 'Could not expand "{prop}: {val}"'.format(prop=prop, val=value), - CSSWarning, + f'Could not expand "{prop}: {value}"', CSSWarning, ) return for key, idx in zip(self.SIDES, mapping): @@ -110,14 +109,14 @@ def __call__(self, declarations_str, inherited=None): # 3. TODO: resolve other font-relative units for side in self.SIDES: - prop = "border-{side}-width".format(side=side) + prop = f"border-{side}-width" if prop in props: props[prop] = self.size_to_pt( props[prop], em_pt=font_size, conversions=self.BORDER_WIDTH_RATIOS ) for prop in [ - "margin-{side}".format(side=side), - "padding-{side}".format(side=side), + f"margin-{side}", + f"padding-{side}", ]: if prop in props: # TODO: support % @@ -206,9 +205,9 @@ def _error(): val = round(val, 5) if int(val) == val: - size_fmt = "{fmt:d}pt".format(fmt=int(val)) + size_fmt = f"{int(val):d}pt" else: - size_fmt = "{fmt:f}pt".format(fmt=val) + size_fmt = f"{val:f}pt" return size_fmt def atomize(self, declarations): diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 5d8573c1341f5..2f7a80eea1554 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -91,6 +91,7 @@ def build_xlstyle(self, props): "font": self.build_font(props), "number_format": self.build_number_format(props), } + # TODO: handle cell width and height: needs support in pandas.io.excel def remove_none(d): @@ -132,12 +133,10 @@ def build_border(self, props): return { side: { "style": self._border_style( - props.get("border-{side}-style".format(side=side)), - props.get("border-{side}-width".format(side=side)), - ), - "color": self.color_to_excel( - props.get("border-{side}-color".format(side=side)) + props.get(f"border-{side}-style"), + props.get(f"border-{side}-width"), ), + "color": self.color_to_excel(props.get(f"border-{side}-color")), } for side in ["top", "right", "bottom", "left"] } @@ -427,7 +426,7 @@ def _format_value(self, val): if missing.isposinf_scalar(val): val = self.inf_rep elif missing.isneginf_scalar(val): - val = "-{inf}".format(inf=self.inf_rep) + val = f"-{self.inf_rep}" elif self.float_format is not None: val = float(self.float_format % val) if getattr(val, "tzinfo", None) is not None: @@ -509,8 +508,8 @@ def _format_header_regular(self): if has_aliases: if len(self.header) != len(self.columns): raise ValueError( - "Writing {cols} cols but got {alias} " - "aliases".format(cols=len(self.columns), alias=len(self.header)) + f"Writing {len(self.columns)} cols but got {len(self.header)} " + "aliases" ) else: colnames = self.header @@ -718,8 +717,8 @@ def write( if num_rows > self.max_rows or num_cols > self.max_cols: raise ValueError( "This sheet is too large! Your sheet size is: " - + "{}, {} ".format(num_rows, num_cols) - + "Max sheet size is: {}, {}".format(self.max_rows, self.max_cols) + f"{num_rows}, {num_cols} " + f"Max sheet size is: {self.max_rows}, {self.max_cols}" ) if isinstance(writer, ExcelWriter): diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index a45045991e879..d3a12ccb77048 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -165,7 +165,7 @@ def default_display_func(x): if self.na_rep is not None and pd.isna(x): return self.na_rep elif is_float(x): - display_format = "{0:.{precision}f}".format(x, precision=self.precision) + display_format = f"{x:.{self.precision}f}" return display_format else: return x @@ -293,7 +293,7 @@ def format_attr(pair): name = self.data.columns.names[r] cs = [ BLANK_CLASS if name is None else INDEX_NAME_CLASS, - "level{lvl}".format(lvl=r), + f"level{r}", ] name = BLANK_VALUE if name is None else name row_es.append( @@ -310,8 +310,8 @@ def format_attr(pair): for c, value in enumerate(clabels[r]): cs = [ COL_HEADING_CLASS, - "level{lvl}".format(lvl=r), - "col{col}".format(col=c), + f"level{r}", + f"col{c}", ] cs.extend( cell_context.get("col_headings", {}).get(r, {}).get(c, []) @@ -339,7 +339,7 @@ def format_attr(pair): index_header_row = [] for c, name in enumerate(self.data.index.names): - cs = [INDEX_NAME_CLASS, "level{lvl}".format(lvl=c)] + cs = [INDEX_NAME_CLASS, f"level{c}"] name = "" if name is None else name index_header_row.append( {"type": "th", "value": name, "class": " ".join(cs)} @@ -358,8 +358,8 @@ def format_attr(pair): for c, value in enumerate(rlabels[r]): rid = [ ROW_HEADING_CLASS, - "level{lvl}".format(lvl=c), - "row{row}".format(row=r), + f"level{c}", + f"row{r}", ] es = { "type": "th", @@ -377,7 +377,7 @@ def format_attr(pair): row_es.append(es) for c, col in enumerate(self.data.columns): - cs = [DATA_CLASS, "row{row}".format(row=r), "col{col}".format(col=c)] + cs = [DATA_CLASS, f"row{r}", f"col{c}"] cs.extend(cell_context.get("data", {}).get(r, {}).get(c, [])) formatter = self._display_funcs[(r, c)] value = self.data.iloc[r, c] @@ -399,12 +399,7 @@ def format_attr(pair): props.append(x.split(":")) else: props.append(["", ""]) - cellstyle.append( - { - "props": props, - "selector": "row{row}_col{col}".format(row=r, col=c), - } - ) + cellstyle.append({"props": props, "selector": f"row{r}_col{c}"}) body.append(row_es) table_attr = self.table_attributes @@ -971,9 +966,7 @@ def hide_columns(self, subset): @staticmethod def _highlight_null(v, null_color): - return ( - "background-color: {color}".format(color=null_color) if pd.isna(v) else "" - ) + return f"background-color: {null_color}" if pd.isna(v) else "" def highlight_null(self, null_color="red"): """ @@ -1126,9 +1119,7 @@ def relative_luminance(rgba): def css(rgba): dark = relative_luminance(rgba) < text_color_threshold text_color = "#f1f1f1" if dark else "#000000" - return "background-color: {b};color: {c};".format( - b=colors.rgb2hex(rgba), c=text_color - ) + return f"background-color: {colors.rgb2hex(rgba)};color: {text_color};" if s.ndim == 1: return [css(rgba) for rgba in rgbas] @@ -1160,7 +1151,7 @@ def set_properties(self, subset=None, **kwargs): >>> df.style.set_properties(color="white", align="right") >>> df.style.set_properties(**{'background-color': 'yellow'}) """ - values = ";".join("{p}: {v}".format(p=p, v=v) for p, v in kwargs.items()) + values = ";".join(f"{p}: {v}" for p, v in kwargs.items()) f = lambda x: values return self.applymap(f, subset=subset) @@ -1191,12 +1182,9 @@ def css_bar(start, end, color): if end > start: css += "background: linear-gradient(90deg," if start > 0: - css += " transparent {s:.1f}%, {c} {s:.1f}%, ".format( - s=start, c=color - ) - css += "{c} {e:.1f}%, transparent {e:.1f}%)".format( - e=min(end, width), c=color - ) + css += f" transparent {start:.1f}%, {color} {start:.1f}%, " + e = min(end, width) + css += f"{color} {e:.1f}%, transparent {e:.1f}%)" return css def css(x): @@ -1358,7 +1346,7 @@ def _highlight_extrema(data, color="yellow", max_=True): """ Highlight the min or max in a Series or DataFrame. """ - attr = "background-color: {0}".format(color) + attr = f"background-color: {color}" if max_: extrema = data == np.nanmax(data.to_numpy()) @@ -1528,10 +1516,7 @@ def _maybe_wrap_formatter(formatter, na_rep: Optional[str]): elif callable(formatter): formatter_func = formatter else: - msg = ( - "Expected a template string or callable, got {formatter} " - "instead".format(formatter=formatter) - ) + msg = f"Expected a template string or callable, got {formatter} instead" raise TypeError(msg) if na_rep is None: @@ -1539,5 +1524,5 @@ def _maybe_wrap_formatter(formatter, na_rep: Optional[str]): elif isinstance(na_rep, str): return lambda x: na_rep if pd.isna(x) else formatter_func(x) else: - msg = "Expected a string, got {na_rep} instead".format(na_rep=na_rep) + msg = f"Expected a string, got {na_rep} instead" raise TypeError(msg) diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index 2684b90e33b7e..2e91d76b0fe98 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -84,18 +84,13 @@ def wrapper(*args, **kwargs) -> Callable[..., Any]: if empty1 or empty2 and not summary: raise AssertionError(doc_error_msg) wrapper.__doc__ = dedent( - """ - {summary} - - .. deprecated:: {depr_version} - {depr_msg} - - {rest_of_docstring}""" - ).format( - summary=summary.strip(), - depr_version=version, - depr_msg=msg, - rest_of_docstring=dedent(doc), + f""" + {summary.strip()} + + .. deprecated:: {version} + {msg} + + {dedent(doc)}""" ) return wrapper diff --git a/pandas/util/_depr_module.py b/pandas/util/_depr_module.py index ae3c6359d20e0..99dafdd760d26 100644 --- a/pandas/util/_depr_module.py +++ b/pandas/util/_depr_module.py @@ -61,17 +61,15 @@ def __getattr__(self, name): if self.removals is not None and name in self.removals: warnings.warn( - "{deprmod}.{name} is deprecated and will be removed in " - "a future version.".format(deprmod=self.deprmod, name=name), + f"{self.deprmod}.{name} is deprecated and will be removed in " + "a future version.", FutureWarning, stacklevel=2, ) elif self.moved is not None and name in self.moved: warnings.warn( - "{deprmod} is deprecated and will be removed in " - "a future version.\nYou can access {name} as {moved}".format( - deprmod=self.deprmod, name=name, moved=self.moved[name] - ), + f"{self.deprmod} is deprecated and will be removed in " + f"a future version.\nYou can access {name} as {self.moved[name]}", FutureWarning, stacklevel=2, ) @@ -79,8 +77,8 @@ def __getattr__(self, name): deprmodto = self.deprmodto if deprmodto is False: warnings.warn( - "{deprmod}.{name} is deprecated and will be removed in " - "a future version.".format(deprmod=self.deprmod, name=name), + f"{self.deprmod}.{name} is deprecated and will be removed in " + "a future version.", FutureWarning, stacklevel=2, ) @@ -89,10 +87,8 @@ def __getattr__(self, name): deprmodto = obj.__module__ # The object is actually located in another module. warnings.warn( - "{deprmod}.{name} is deprecated. Please use " - "{deprmodto}.{name} instead.".format( - deprmod=self.deprmod, name=name, deprmodto=deprmodto - ), + f"{self.deprmod}.{name} is deprecated. Please use " + f"{deprmodto}.{name} instead.", FutureWarning, stacklevel=2, ) diff --git a/pandas/util/_doctools.py b/pandas/util/_doctools.py index 11156bc972857..91972fed7a3bb 100644 --- a/pandas/util/_doctools.py +++ b/pandas/util/_doctools.py @@ -113,7 +113,7 @@ def _insert_index(self, data): data.insert(0, "Index", data.index) else: for i in range(idx_nlevels): - data.insert(i, "Index{0}".format(i), data.index._get_level_values(i)) + data.insert(i, f"Index{i}", data.index._get_level_values(i)) col_nlevels = data.columns.nlevels if col_nlevels > 1: diff --git a/pandas/util/_print_versions.py b/pandas/util/_print_versions.py index d1c74e8530245..b9f7e0c69f8b6 100644 --- a/pandas/util/_print_versions.py +++ b/pandas/util/_print_versions.py @@ -40,14 +40,14 @@ def get_sys_info() -> List[Tuple[str, Optional[Union[str, int]]]]: [ ("python", ".".join(map(str, sys.version_info))), ("python-bits", struct.calcsize("P") * 8), - ("OS", "{sysname}".format(sysname=sysname)), - ("OS-release", "{release}".format(release=release)), + ("OS", f"{sysname}"), + ("OS-release", f"{release}"), # ("Version", "{version}".format(version=version)), - ("machine", "{machine}".format(machine=machine)), - ("processor", "{processor}".format(processor=processor)), - ("byteorder", "{byteorder}".format(byteorder=sys.byteorder)), - ("LC_ALL", "{lc}".format(lc=os.environ.get("LC_ALL", "None"))), - ("LANG", "{lang}".format(lang=os.environ.get("LANG", "None"))), + ("machine", f"{machine}"), + ("processor", f"{processor}"), + ("byteorder", f"{sys.byteorder}"), + ("LC_ALL", f"{os.environ.get('LC_ALL', 'None')}"), + ("LANG", f"{os.environ.get('LANG', 'None')}"), ("LOCALE", ".".join(map(str, locale.getlocale()))), ] ) diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py index 7669e729995d0..0e3ea25bf6fdb 100644 --- a/pandas/util/_test_decorators.py +++ b/pandas/util/_test_decorators.py @@ -129,7 +129,7 @@ def skip_if_installed(package: str) -> Callable: The name of the package. """ return pytest.mark.skipif( - safe_import(package), reason="Skipping because {} is installed.".format(package) + safe_import(package), reason=f"Skipping because {package} is installed." ) @@ -163,9 +163,9 @@ def skip_if_no(package: str, min_version: Optional[str] = None) -> Callable: a pytest.mark.skipif to use as either a test decorator or a parametrization mark. """ - msg = "Could not import '{}'".format(package) + msg = f"Could not import '{package}'" if min_version: - msg += " satisfying a min_version of {}".format(min_version) + msg += f" satisfying a min_version of {min_version}" return pytest.mark.skipif( not safe_import(package, min_version=min_version), reason=msg ) @@ -181,20 +181,17 @@ def skip_if_no(package: str, min_version: Optional[str] = None) -> Callable: is_platform_windows(), reason="not used on win32" ) skip_if_has_locale = pytest.mark.skipif( - _skip_if_has_locale(), - reason="Specific locale is set {lang}".format(lang=locale.getlocale()[0]), + _skip_if_has_locale(), reason=f"Specific locale is set {locale.getlocale()[0]}", ) skip_if_not_us_locale = pytest.mark.skipif( - _skip_if_not_us_locale(), - reason="Specific locale is set {lang}".format(lang=locale.getlocale()[0]), + _skip_if_not_us_locale(), reason=f"Specific locale is set {locale.getlocale()[0]}", ) skip_if_no_scipy = pytest.mark.skipif( _skip_if_no_scipy(), reason="Missing SciPy requirement" ) skip_if_no_ne = pytest.mark.skipif( not _USE_NUMEXPR, - reason="numexpr enabled->{enabled}, " - "installed->{installed}".format(enabled=_USE_NUMEXPR, installed=_NUMEXPR_INSTALLED), + reason=f"numexpr enabled->{_USE_NUMEXPR}, " f"installed->{_NUMEXPR_INSTALLED}", ) diff --git a/pandas/util/_tester.py b/pandas/util/_tester.py index 7822ecdeeb4d8..6a3943cab692e 100644 --- a/pandas/util/_tester.py +++ b/pandas/util/_tester.py @@ -22,7 +22,7 @@ def test(extra_args=None): extra_args = [extra_args] cmd = extra_args cmd += [PKG] - print("running: pytest {}".format(" ".join(cmd))) + print(f"running: pytest {' '.join(cmd)}") sys.exit(pytest.main(cmd)) diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py index 0eaf46d563163..8b675a6b688fe 100644 --- a/pandas/util/_validators.py +++ b/pandas/util/_validators.py @@ -26,13 +26,8 @@ def _check_arg_length(fname, args, max_fname_arg_count, compat_args): argument = "argument" if max_arg_count == 1 else "arguments" raise TypeError( - "{fname}() takes at most {max_arg} {argument} " - "({given_arg} given)".format( - fname=fname, - max_arg=max_arg_count, - argument=argument, - given_arg=actual_arg_count, - ) + f"{fname}() takes at most {max_arg_count} {argument} " + f"({actual_arg_count} given)" ) @@ -71,9 +66,9 @@ def _check_for_default_values(fname, arg_val_dict, compat_args): if not match: raise ValueError( ( - "the '{arg}' parameter is not " + f"the '{key}' parameter is not " "supported in the pandas " - "implementation of {fname}()".format(fname=fname, arg=key) + f"implementation of {fname}()" ) ) @@ -132,10 +127,7 @@ def _check_for_invalid_keys(fname, kwargs, compat_args): if diff: bad_arg = list(diff)[0] raise TypeError( - ( - "{fname}() got an unexpected " - "keyword argument '{arg}'".format(fname=fname, arg=bad_arg) - ) + (f"{fname}() got an unexpected " f"keyword argument '{bad_arg}'") ) @@ -223,8 +215,7 @@ def validate_args_and_kwargs(fname, args, kwargs, max_fname_arg_count, compat_ar for key in args_dict: if key in kwargs: raise TypeError( - "{fname}() got multiple values for keyword " - "argument '{arg}'".format(fname=fname, arg=key) + f"{fname}() got multiple values for keyword " f"argument '{key}'" ) kwargs.update(args_dict) @@ -235,8 +226,8 @@ def validate_bool_kwarg(value, arg_name): """ Ensures that argument passed in arg_name is of type bool. """ if not (is_bool(value) or value is None): raise ValueError( - 'For argument "{arg}" expected type bool, received ' - "type {typ}.".format(arg=arg_name, typ=type(value).__name__) + f'For argument "{arg_name}" expected type bool, received ' + f"type {type(value).__name__}." ) return value @@ -289,9 +280,7 @@ def validate_axis_style_args(data, args, kwargs, arg_name, method_name): # First fill with explicit values provided by the user... if arg_name in kwargs: if args: - msg = "{} got multiple values for argument '{}'".format( - method_name, arg_name - ) + msg = f"{method_name} got multiple values for argument '{arg_name}'" raise TypeError(msg) axis = data._get_axis_name(kwargs.get("axis", 0)) @@ -332,8 +321,8 @@ def validate_axis_style_args(data, args, kwargs, arg_name, method_name): out[data._AXIS_NAMES[0]] = args[0] out[data._AXIS_NAMES[1]] = args[1] else: - msg = "Cannot specify all of '{}', 'index', 'columns'." - raise TypeError(msg.format(arg_name)) + msg = f"Cannot specify all of '{arg_name}', 'index', 'columns'." + raise TypeError(msg) return out @@ -366,7 +355,7 @@ def validate_fillna_kwargs(value, method, validate_scalar_dict_value=True): if validate_scalar_dict_value and isinstance(value, (list, tuple)): raise TypeError( '"value" parameter must be a scalar or dict, but ' - 'you passed a "{0}"'.format(type(value).__name__) + f'you passed a "{type(value).__name__}"' ) elif value is not None and method is not None:
- [x] ref #29547 and ref #30020 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry I accidentally deleted the branch for #30230 which closed it, but I applied all the requested changes in this PR.
https://api.github.com/repos/pandas-dev/pandas/pulls/30250
2019-12-13T01:05:53Z
2019-12-13T13:17:24Z
2019-12-13T13:17:24Z
2019-12-14T16:02:35Z
TST: Fix apparent typo skip_if_no lxml->bs4
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index c34f2ebace683..39cbe843d1f2b 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -87,7 +87,7 @@ def test_same_ordering(datapath): @pytest.mark.parametrize( "flavor", [ - pytest.param("bs4", marks=td.skip_if_no("lxml")), + pytest.param("bs4", marks=td.skip_if_no("bs4")), pytest.param("lxml", marks=td.skip_if_no("lxml")), ], scope="class",
https://api.github.com/repos/pandas-dev/pandas/pulls/30249
2019-12-13T01:03:46Z
2019-12-13T13:31:34Z
2019-12-13T13:31:34Z
2019-12-13T15:28:11Z
CLN changed .format to f-string for test_converter.py, test_datetimel…
diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py index fb9ad57626600..5cea4fb5acca0 100644 --- a/pandas/tests/plotting/test_converter.py +++ b/pandas/tests/plotting/test_converter.py @@ -268,7 +268,7 @@ def _assert_less(ts1, ts2): val1 = self.dtc.convert(ts1, None, None) val2 = self.dtc.convert(ts2, None, None) if not val1 < val2: - raise AssertionError("{0} is not less than {1}.".format(val1, val2)) + raise AssertionError(f"{val1} is not less than {val2}.") # Matplotlib's time representation using floats cannot distinguish # intervals smaller than ~10 microsecond in the common range of years. diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index f5161b481ca50..8456f095e5868 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -1352,7 +1352,7 @@ def test_plot_outofbounds_datetime(self): def test_format_timedelta_ticks_narrow(self): - expected_labels = ["00:00:00.0000000{:0>2d}".format(i) for i in np.arange(10)] + expected_labels = [f"00:00:00.0000000{i:0>2d}" for i in np.arange(10)] rng = timedelta_range("0", periods=10, freq="ns") df = DataFrame(np.random.randn(len(rng), 3), rng) diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 766b1f61e9c1b..61722d726b28b 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -330,7 +330,7 @@ def test_pie_series(self): ax = _check_plot_works( series.plot.pie, colors=color_args, autopct="%.2f", fontsize=7 ) - pcts = ["{0:.2f}".format(s * 100) for s in series.values / float(series.sum())] + pcts = [f"{s*100:.2f}" for s in series.values / float(series.sum())] expected_texts = list(chain.from_iterable(zip(series.index, pcts))) self._check_text_labels(ax.texts, expected_texts) for t in ax.texts: @@ -865,15 +865,15 @@ def test_time_series_plot_color_with_empty_kwargs(self): def test_xticklabels(self): # GH11529 - s = Series(np.arange(10), index=["P{i:02d}".format(i=i) for i in range(10)]) + s = Series(np.arange(10), index=[f"P{i:02d}" for i in range(10)]) _, ax = self.plt.subplots() ax = s.plot(xticks=[0, 3, 5, 9], ax=ax) - exp = ["P{i:02d}".format(i=i) for i in [0, 3, 5, 9]] + exp = [f"P{i:02d}" for i in [0, 3, 5, 9]] self._check_text_labels(ax.get_xticklabels(), exp) def test_xtick_barPlot(self): # GH28172 - s = pd.Series(range(10), index=["P{i:02d}".format(i=i) for i in range(10)]) + s = pd.Series(range(10), index=[f"P{i:02d}" for i in range(10)]) ax = s.plot.bar(xticks=range(0, 11, 2)) exp = np.array(list(range(0, 11, 2))) tm.assert_numpy_array_equal(exp, ax.get_xticks())
…ike.py, test_series.py #29547 https://github.com/pandas-dev/pandas/issues/29547 - [x] 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/30248
2019-12-12T23:11:53Z
2019-12-13T13:33:34Z
2019-12-13T13:33:33Z
2019-12-27T23:45:17Z
CLN: more consistent error message for ExtensionDtype.construct_from_string
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index bc7de0e2c4e1e..13748e03e856d 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -72,7 +72,12 @@ def _is_boolean(self): @classmethod def construct_from_string(cls, string): - return cls(np.dtype(string)) + try: + return cls(np.dtype(string)) + except TypeError as err: + raise TypeError( + f"Cannot construct a 'PandasDtype' from '{string}'" + ) from err def construct_array_type(cls): return PandasArray diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index 941db116589e8..a295dfed2cf96 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -199,7 +199,7 @@ def construct_from_string(cls, string): ------- SparseDtype """ - msg = f"Could not construct SparseDtype from '{string}'" + msg = f"Cannot construct a 'SparseDtype' from '{string}'" if string.startswith("Sparse"): try: sub_type, has_fill_value = cls._parse_subtype(string) @@ -208,7 +208,7 @@ def construct_from_string(cls, string): else: result = SparseDtype(sub_type) msg = ( - f"Could not construct SparseDtype from '{string}'.\n\nIt " + f"Cannot construct a 'SparseDtype' from '{string}'.\n\nIt " "looks like the fill_value in the string is not " "the default for the dtype. Non-default fill_values " "are not supported. Use the 'SparseDtype()' " diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index e45f4ce1b72b1..4421fad5f19d1 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -732,7 +732,7 @@ def construct_from_string(cls, string: str_type): datetime64[ns, UTC] """ if isinstance(string, str): - msg = "Could not construct DatetimeTZDtype from '{string}'" + msg = f"Cannot construct a 'DatetimeTZDtype' from '{string}'" match = cls._match.match(string) if match: d = match.groupdict() @@ -743,10 +743,10 @@ def construct_from_string(cls, string: str_type): # pytz timezone (actually pytz.UnknownTimeZoneError). # TypeError if we pass a nonsense tz; # ValueError if we pass a unit other than "ns" - raise TypeError(msg.format(string=string)) from err - raise TypeError(msg.format(string=string)) + raise TypeError(msg) from err + raise TypeError(msg) - raise TypeError("Could not construct DatetimeTZDtype") + raise TypeError("Cannot construct a 'DatetimeTZDtype'") def __str__(self) -> str_type: return "datetime64[{unit}, {tz}]".format(unit=self.unit, tz=self.tz) @@ -883,7 +883,7 @@ def construct_from_string(cls, string): return cls(freq=string) except ValueError: pass - raise TypeError("could not construct PeriodDtype") + raise TypeError(f"Cannot construct a 'PeriodDtype' from '{string}'") def __str__(self) -> str_type: return self.name @@ -1054,6 +1054,7 @@ def construct_from_string(cls, string): return cls(string) msg = ( + f"Cannot construct a 'IntervalDtype' from '{string}'.\n\n" "Incorrectly formatted string passed to constructor. " "Valid formats include Interval or Interval[dtype] " "where dtype is numeric, datetime, or timedelta" diff --git a/pandas/tests/arrays/sparse/test_dtype.py b/pandas/tests/arrays/sparse/test_dtype.py index 3194498daf825..5e9e2d854f577 100644 --- a/pandas/tests/arrays/sparse/test_dtype.py +++ b/pandas/tests/arrays/sparse/test_dtype.py @@ -83,7 +83,7 @@ def test_not_equal(a, b): def test_construct_from_string_raises(): with pytest.raises( - TypeError, match="Could not construct SparseDtype from 'not a dtype'" + TypeError, match="Cannot construct a 'SparseDtype' from 'not a dtype'" ): SparseDtype.construct_from_string("not a dtype") diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index 6c6ff3272c012..bca78a1008d87 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -236,7 +236,7 @@ def test_compat(self): def test_construction_from_string(self): result = DatetimeTZDtype.construct_from_string("datetime64[ns, US/Eastern]") assert is_dtype_equal(self.dtype, result) - msg = "Could not construct DatetimeTZDtype from 'foo'" + msg = "Cannot construct a 'DatetimeTZDtype' from 'foo'" with pytest.raises(TypeError, match=msg): DatetimeTZDtype.construct_from_string("foo") @@ -244,7 +244,7 @@ def test_construct_from_string_raises(self): with pytest.raises(TypeError, match="notatz"): DatetimeTZDtype.construct_from_string("datetime64[ns, notatz]") - msg = "^Could not construct DatetimeTZDtype" + msg = "^Cannot construct a 'DatetimeTZDtype'" with pytest.raises(TypeError, match=msg): # list instead of string DatetimeTZDtype.construct_from_string(["datetime64[ns, notatz]"]) diff --git a/pandas/tests/extension/arrow/arrays.py b/pandas/tests/extension/arrow/arrays.py index a4554aca1325e..86e23b3264456 100644 --- a/pandas/tests/extension/arrow/arrays.py +++ b/pandas/tests/extension/arrow/arrays.py @@ -33,7 +33,7 @@ def construct_from_string(cls, string): if string == cls.name: return cls() else: - raise TypeError(f"Cannot construct a '{cls}' from '{string}'") + raise TypeError(f"Cannot construct a '{cls.__name__}' from '{string}'") @classmethod def construct_array_type(cls): diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py index d1e1717225e15..9a442f346c19f 100644 --- a/pandas/tests/extension/base/dtype.py +++ b/pandas/tests/extension/base/dtype.py @@ -98,5 +98,8 @@ def test_eq(self, dtype): def test_construct_from_string(self, dtype): dtype_instance = type(dtype).construct_from_string(dtype.name) assert isinstance(dtype_instance, type(dtype)) - with pytest.raises(TypeError): + + def test_construct_from_string_another_type_raises(self, dtype): + msg = f"Cannot construct a '{type(dtype).__name__}' from 'another_type'" + with pytest.raises(TypeError, match=msg): type(dtype).construct_from_string("another_type") diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 0c2f1e845909a..0b0865c424f34 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -40,7 +40,7 @@ def construct_from_string(cls, string): if string == cls.name: return cls() else: - raise TypeError(f"Cannot construct a '{cls}' from '{string}'") + raise TypeError(f"Cannot construct a '{cls.__name__}' from '{string}'") @property def _is_numeric(self): diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index b64ddbd6ac84d..28929d50718b6 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -44,7 +44,7 @@ def construct_from_string(cls, string): if string == cls.name: return cls() else: - raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string)) + raise TypeError(f"Cannot construct a '{cls.__name__}' from '{string}'") class JSONArray(ExtensionArray):
message check added to `test_construct_from_string` in `pandas/tests/extension/base/dtype.py` and error messages changed to be consistent with error message on class method in `pandas/core/dtypes/base.py` xref Provide ExtensionDtype.construct_from_string by default #26562
https://api.github.com/repos/pandas-dev/pandas/pulls/30247
2019-12-12T22:48:40Z
2019-12-13T13:32:35Z
2019-12-13T13:32:35Z
2019-12-13T14:28:49Z
ERR: stringify error message from parsers.pyx, closes #29233
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index adc7a650b745f..bb1493280dfd2 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -657,7 +657,7 @@ cdef class TextReader: if isinstance(source, str): encoding = sys.getfilesystemencoding() or "utf-8" - + usource = source source = source.encode(encoding) if self.memory_map: @@ -677,10 +677,11 @@ cdef class TextReader: if ptr == NULL: if not os.path.exists(source): + raise FileNotFoundError( ENOENT, - f'File {source} does not exist', - source) + f'File {usource} does not exist', + usource) raise IOError('Initializing from file failed') self.parser.source = ptr diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index 590f26a76802a..fe360f1346c7c 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -2,7 +2,6 @@ Tests that work on both the Python and C engines but do not have a specific classification into the other test modules. """ - import codecs from collections import OrderedDict import csv @@ -978,15 +977,15 @@ def test_path_local_path(all_parsers): def test_nonexistent_path(all_parsers): # gh-2428: pls no segfault # gh-14086: raise more helpful FileNotFoundError + # GH#29233 "File foo" instead of "File b'foo'" parser = all_parsers path = "{}.csv".format(tm.rands(10)) - msg = "does not exist" if parser.engine == "c" else r"\[Errno 2\]" + msg = f"File {path} does not exist" if parser.engine == "c" else r"\[Errno 2\]" with pytest.raises(FileNotFoundError, match=msg) as e: parser.read_csv(path) filename = e.value.filename - filename = filename.decode() if isinstance(filename, bytes) else filename assert path == filename
- [x] closes #29233 - [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/30246
2019-12-12T21:51:36Z
2019-12-13T14:21:39Z
2019-12-13T14:21:39Z
2019-12-13T15:29:08Z
Implement NA.__array_ufunc__
diff --git a/doc/source/getting_started/dsintro.rst b/doc/source/getting_started/dsintro.rst index 82d4b5e34e4f8..8bd271815549d 100644 --- a/doc/source/getting_started/dsintro.rst +++ b/doc/source/getting_started/dsintro.rst @@ -676,11 +676,11 @@ similar to an ndarray: # only show the first 5 rows df[:5].T +.. _dsintro.numpy_interop: + DataFrame interoperability with NumPy functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. _dsintro.numpy_interop: - Elementwise NumPy ufuncs (log, exp, sqrt, ...) and various other NumPy functions can be used with no issues on Series and DataFrame, assuming the data within are numeric: diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst index da593bcb6e923..abbb6feef6056 100644 --- a/doc/source/user_guide/missing_data.rst +++ b/doc/source/user_guide/missing_data.rst @@ -920,3 +920,29 @@ filling missing values beforehand. A similar situation occurs when using Series or DataFrame objects in ``if`` statements, see :ref:`gotchas.truth`. + +NumPy ufuncs +------------ + +:attr:`pandas.NA` implements NumPy's ``__array_ufunc__`` protocol. Most ufuncs +work with ``NA``, and generally return ``NA``: + +.. ipython:: python + + np.log(pd.NA) + np.add(pd.NA, 1) + +.. warning:: + + Currently, ufuncs involving an ndarray and ``NA`` will return an + object-dtype filled with NA values. + + .. ipython:: python + + a = np.array([1, 2, 3]) + np.greater(a, pd.NA) + + The return type here may change to return a different array type + in the future. + +See :ref:`dsintro.numpy_interop` for more on ufuncs. diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index f1cfa0978c3a0..afaf9115abfd3 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -14,6 +14,7 @@ from pandas._libs.tslibs.np_datetime cimport ( get_timedelta64_value, get_datetime64_value) from pandas._libs.tslibs.nattype cimport ( checknull_with_nat, c_NaT as NaT, is_null_datetimelike) +from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op from pandas.compat import is_platform_32bit @@ -290,16 +291,29 @@ cdef inline bint is_null_period(v): # Implementation of NA singleton -def _create_binary_propagating_op(name, divmod=False): +def _create_binary_propagating_op(name, is_divmod=False): def method(self, other): if (other is C_NA or isinstance(other, str) - or isinstance(other, (numbers.Number, np.bool_))): - if divmod: + or isinstance(other, (numbers.Number, np.bool_)) + or isinstance(other, np.ndarray) and not other.shape): + # Need the other.shape clause to handle NumPy scalars, + # since we do a setitem on `out` below, which + # won't work for NumPy scalars. + if is_divmod: return NA, NA else: return NA + elif isinstance(other, np.ndarray): + out = np.empty(other.shape, dtype=object) + out[:] = NA + + if is_divmod: + return out, out.copy() + else: + return out + return NotImplemented method.__name__ = name @@ -369,8 +383,8 @@ class NAType(C_NAType): __rfloordiv__ = _create_binary_propagating_op("__rfloordiv__") __mod__ = _create_binary_propagating_op("__mod__") __rmod__ = _create_binary_propagating_op("__rmod__") - __divmod__ = _create_binary_propagating_op("__divmod__", divmod=True) - __rdivmod__ = _create_binary_propagating_op("__rdivmod__", divmod=True) + __divmod__ = _create_binary_propagating_op("__divmod__", is_divmod=True) + __rdivmod__ = _create_binary_propagating_op("__rdivmod__", is_divmod=True) # __lshift__ and __rshift__ are not implemented __eq__ = _create_binary_propagating_op("__eq__") @@ -397,6 +411,8 @@ class NAType(C_NAType): return type(other)(1) else: return NA + elif isinstance(other, np.ndarray): + return np.where(other == 0, other.dtype.type(1), NA) return NotImplemented @@ -408,6 +424,8 @@ class NAType(C_NAType): return other else: return NA + elif isinstance(other, np.ndarray): + return np.where((other == 1) | (other == -1), other, NA) return NotImplemented @@ -440,6 +458,31 @@ class NAType(C_NAType): __rxor__ = __xor__ + __array_priority__ = 1000 + _HANDLED_TYPES = (np.ndarray, numbers.Number, str, np.bool_) + + def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): + types = self._HANDLED_TYPES + (NAType,) + for x in inputs: + if not isinstance(x, types): + return NotImplemented + + if method != "__call__": + raise ValueError(f"ufunc method '{method}' not supported for NA") + result = maybe_dispatch_ufunc_to_dunder_op( + self, ufunc, method, *inputs, **kwargs + ) + if result is NotImplemented: + # For a NumPy ufunc that's not a binop, like np.logaddexp + index = [i for i, x in enumerate(inputs) if x is NA][0] + result = np.broadcast_arrays(*inputs)[index] + if result.ndim == 0: + result = result.item() + if ufunc.nout > 1: + result = (NA,) * ufunc.nout + + return result + C_NA = NAType() # C-visible NA = C_NA # Python-visible diff --git a/pandas/_libs/ops_dispatch.pyx b/pandas/_libs/ops_dispatch.pyx new file mode 100644 index 0000000000000..f6ecef2038cf3 --- /dev/null +++ b/pandas/_libs/ops_dispatch.pyx @@ -0,0 +1,94 @@ +DISPATCHED_UFUNCS = { + "add", + "sub", + "mul", + "pow", + "mod", + "floordiv", + "truediv", + "divmod", + "eq", + "ne", + "lt", + "gt", + "le", + "ge", + "remainder", + "matmul", + "or", + "xor", + "and", +} +UFUNC_ALIASES = { + "subtract": "sub", + "multiply": "mul", + "floor_divide": "floordiv", + "true_divide": "truediv", + "power": "pow", + "remainder": "mod", + "divide": "div", + "equal": "eq", + "not_equal": "ne", + "less": "lt", + "less_equal": "le", + "greater": "gt", + "greater_equal": "ge", + "bitwise_or": "or", + "bitwise_and": "and", + "bitwise_xor": "xor", +} + +# For op(., Array) -> Array.__r{op}__ +REVERSED_NAMES = { + "lt": "__gt__", + "le": "__ge__", + "gt": "__lt__", + "ge": "__le__", + "eq": "__eq__", + "ne": "__ne__", +} + + +def maybe_dispatch_ufunc_to_dunder_op( + object self, object ufunc, str method, *inputs, **kwargs +): + """ + Dispatch a ufunc to the equivalent dunder method. + + Parameters + ---------- + self : ArrayLike + The array whose dunder method we dispatch to + ufunc : Callable + A NumPy ufunc + method : {'reduce', 'accumulate', 'reduceat', 'outer', 'at', '__call__'} + inputs : ArrayLike + The input arrays. + kwargs : Any + The additional keyword arguments, e.g. ``out``. + + Returns + ------- + result : Any + The result of applying the ufunc + """ + # special has the ufuncs we dispatch to the dunder op on + + op_name = ufunc.__name__ + op_name = UFUNC_ALIASES.get(op_name, op_name) + + def not_implemented(*args, **kwargs): + return NotImplemented + + if (method == "__call__" + and op_name in DISPATCHED_UFUNCS + and kwargs.get("out") is None): + if isinstance(inputs[0], type(self)): + name = f"__{op_name}__" + return getattr(self, name, not_implemented)(inputs[1]) + else: + name = REVERSED_NAMES.get(op_name, f"__r{op_name}__") + result = getattr(self, name, not_implemented)(inputs[0]) + return result + else: + return NotImplemented diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 1b868f7c10602..f51d71d5507a0 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -10,6 +10,7 @@ import numpy as np from pandas._libs import Timedelta, Timestamp, lib +from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op # noqa:F401 from pandas.util._decorators import Appender from pandas.core.dtypes.common import is_list_like, is_timedelta64_dtype @@ -31,7 +32,6 @@ ) from pandas.core.ops.array_ops import comp_method_OBJECT_ARRAY # noqa:F401 from pandas.core.ops.common import unpack_zerodim_and_defer -from pandas.core.ops.dispatch import maybe_dispatch_ufunc_to_dunder_op # noqa:F401 from pandas.core.ops.dispatch import should_series_dispatch from pandas.core.ops.docstrings import ( _arith_doc_FRAME, diff --git a/pandas/core/ops/dispatch.py b/pandas/core/ops/dispatch.py index f35279378dc65..61a3032c7a02c 100644 --- a/pandas/core/ops/dispatch.py +++ b/pandas/core/ops/dispatch.py @@ -1,12 +1,10 @@ """ Functions for defining unary operations. """ -from typing import Any, Callable, Union +from typing import Any, Union import numpy as np -from pandas._typing import ArrayLike - from pandas.core.dtypes.common import ( is_datetime64_dtype, is_extension_array_dtype, @@ -126,94 +124,3 @@ def dispatch_to_extension_op( # on the ExtensionArray res_values = op(left, right) return res_values - - -def maybe_dispatch_ufunc_to_dunder_op( - self: ArrayLike, ufunc: Callable, method: str, *inputs: ArrayLike, **kwargs: Any -): - """ - Dispatch a ufunc to the equivalent dunder method. - - Parameters - ---------- - self : ArrayLike - The array whose dunder method we dispatch to - ufunc : Callable - A NumPy ufunc - method : {'reduce', 'accumulate', 'reduceat', 'outer', 'at', '__call__'} - inputs : ArrayLike - The input arrays. - kwargs : Any - The additional keyword arguments, e.g. ``out``. - - Returns - ------- - result : Any - The result of applying the ufunc - """ - # special has the ufuncs we dispatch to the dunder op on - special = { - "add", - "sub", - "mul", - "pow", - "mod", - "floordiv", - "truediv", - "divmod", - "eq", - "ne", - "lt", - "gt", - "le", - "ge", - "remainder", - "matmul", - "or", - "xor", - "and", - } - aliases = { - "subtract": "sub", - "multiply": "mul", - "floor_divide": "floordiv", - "true_divide": "truediv", - "power": "pow", - "remainder": "mod", - "divide": "div", - "equal": "eq", - "not_equal": "ne", - "less": "lt", - "less_equal": "le", - "greater": "gt", - "greater_equal": "ge", - "bitwise_or": "or", - "bitwise_and": "and", - "bitwise_xor": "xor", - } - - # For op(., Array) -> Array.__r{op}__ - flipped = { - "lt": "__gt__", - "le": "__ge__", - "gt": "__lt__", - "ge": "__le__", - "eq": "__eq__", - "ne": "__ne__", - } - - op_name = ufunc.__name__ - op_name = aliases.get(op_name, op_name) - - def not_implemented(*args, **kwargs): - return NotImplemented - - if method == "__call__" and op_name in special and kwargs.get("out") is None: - if isinstance(inputs[0], type(self)): - name = f"__{op_name}__" - return getattr(self, name, not_implemented)(inputs[1]) - else: - name = flipped.get(op_name, f"__r{op_name}__") - return getattr(self, name, not_implemented)(inputs[0]) - else: - return NotImplemented diff --git a/pandas/tests/scalar/test_na_scalar.py b/pandas/tests/scalar/test_na_scalar.py index 384bf171738bc..a72378e02bec6 100644 --- a/pandas/tests/scalar/test_na_scalar.py +++ b/pandas/tests/scalar/test_na_scalar.py @@ -58,12 +58,6 @@ def test_comparison_ops(): assert (NA >= other) is NA assert (NA < other) is NA assert (NA <= other) is NA - - if isinstance(other, (np.int64, np.bool_)): - # for numpy scalars we get a deprecation warning and False as result - # for equality or error for larger/lesser than - continue - assert (other == NA) is NA assert (other != NA) is NA assert (other > NA) is NA @@ -87,9 +81,17 @@ def test_comparison_ops(): np.float_(-0), ], ) -def test_pow_special(value): +@pytest.mark.parametrize("asarray", [True, False]) +def test_pow_special(value, asarray): + if asarray: + value = np.array([value]) result = pd.NA ** value - assert isinstance(result, type(value)) + + if asarray: + result = result[0] + else: + # this assertion isn't possible for ndarray. + assert isinstance(result, type(value)) assert result == 1 @@ -108,12 +110,20 @@ def test_pow_special(value): np.float_(-1), ], ) -def test_rpow_special(value): +@pytest.mark.parametrize("asarray", [True, False]) +def test_rpow_special(value, asarray): + if asarray: + value = np.array([value]) result = value ** pd.NA - assert result == value - if not isinstance(value, (np.float_, np.bool_, np.int_)): + + if asarray: + result = result[0] + elif not isinstance(value, (np.float_, np.bool_, np.int_)): + # this assertion isn't possible with asarray=True assert isinstance(result, type(value)) + assert result == value + def test_unary_ops(): assert +NA is NA @@ -162,6 +172,19 @@ def test_logical_not(): assert ~NA is NA +@pytest.mark.parametrize( + "shape", [(3,), (3, 3), (1, 2, 3)], +) +def test_arithmetic_ndarray(shape, all_arithmetic_functions): + op = all_arithmetic_functions + a = np.zeros(shape) + if op.__name__ == "pow": + a += 5 + result = op(pd.NA, a) + expected = np.full(a.shape, pd.NA, dtype=object) + tm.assert_numpy_array_equal(result, expected) + + def test_is_scalar(): assert is_scalar(NA) is True @@ -177,6 +200,55 @@ def test_series_isna(): tm.assert_series_equal(s.isna(), expected) +def test_ufunc(): + assert np.log(pd.NA) is pd.NA + assert np.add(pd.NA, 1) is pd.NA + result = np.divmod(pd.NA, 1) + assert result[0] is pd.NA and result[1] is pd.NA + + result = np.frexp(pd.NA) + assert result[0] is pd.NA and result[1] is pd.NA + + +def test_ufunc_raises(): + with pytest.raises(ValueError, match="ufunc method 'at'"): + np.log.at(pd.NA, 0) + + +def test_binary_input_not_dunder(): + a = np.array([1, 2, 3]) + expected = np.array([pd.NA, pd.NA, pd.NA], dtype=object) + result = np.logaddexp(a, pd.NA) + tm.assert_numpy_array_equal(result, expected) + + result = np.logaddexp(pd.NA, a) + tm.assert_numpy_array_equal(result, expected) + + # all NA, multiple inputs + assert np.logaddexp(pd.NA, pd.NA) is pd.NA + + result = np.modf(pd.NA, pd.NA) + assert len(result) == 2 + assert all(x is pd.NA for x in result) + + +def test_divmod_ufunc(): + # binary in, binary out. + a = np.array([1, 2, 3]) + expected = np.array([pd.NA, pd.NA, pd.NA], dtype=object) + + result = np.divmod(a, pd.NA) + assert isinstance(result, tuple) + for arr in result: + tm.assert_numpy_array_equal(arr, expected) + tm.assert_numpy_array_equal(arr, expected) + + result = np.divmod(pd.NA, a) + for arr in result: + tm.assert_numpy_array_equal(arr, expected) + tm.assert_numpy_array_equal(arr, expected) + + def test_integer_hash_collision_dict(): # GH 30013 result = {NA: "foo", hash(NA): "bar"} diff --git a/setup.py b/setup.py index 489a9602511e8..076b77bf5d4df 100755 --- a/setup.py +++ b/setup.py @@ -596,6 +596,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): }, "_libs.reduction": {"pyxfile": "_libs/reduction"}, "_libs.ops": {"pyxfile": "_libs/ops"}, + "_libs.ops_dispatch": {"pyxfile": "_libs/ops_dispatch"}, "_libs.properties": {"pyxfile": "_libs/properties"}, "_libs.reshape": {"pyxfile": "_libs/reshape", "depends": []}, "_libs.sparse": {"pyxfile": "_libs/sparse", "depends": _pxi_dep["sparse"]},
This gives us consistent comparisons with NumPy scalars. I have a few implementation questions: 1. I wanted to reuse `maybe_dispatch_ufunc_to_dunder_op`. That was in `core/ops/dispatch.py`, but NA is defend in `_libs/missing.pyx`. For now I just moved it to `_libs/missing.pyx`, is there a better home for it? I don't think `_libs/ops.pyx` is an option, as it imports missing. 2. How should we handle comparisons with ndarrays? I see a few options: a. Return an `ndarray[object]`, where each element is NA b. Really take over and return our extension arrays. So `np.array([1, 2]) == pd.NA` would return an `IntegerArray([NA, NA])`. Boolean results would return a BooleanArray. And float results would return a ... PandasArray? (so maybe this isn't a good idea. But worth considering) 3. What scalars should we handle (in `__array_ufunc__` and in the regular methods)? Any of date time, Timestamp, time delta, Period, Interval? One item 2, I seem to have messed something up, as we return just a scalar `NA` right now. Will want to sort that out.
https://api.github.com/repos/pandas-dev/pandas/pulls/30245
2019-12-12T21:48:00Z
2020-01-05T20:43:08Z
2020-01-05T20:43:08Z
2020-01-05T20:43:25Z
TST: Add message checks to tests/arrays/sparse/
diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 75a4f683e92d2..0aaf294378bf7 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -307,11 +307,12 @@ def test_take_filling(self): with pytest.raises(ValueError, match=msg): sparse.take(np.array([1, 0, -5]), allow_fill=True) - with pytest.raises(IndexError): + msg = "out of bounds value in 'indices'" + with pytest.raises(IndexError, match=msg): sparse.take(np.array([1, -6])) - with pytest.raises(IndexError): + with pytest.raises(IndexError, match=msg): sparse.take(np.array([1, 5])) - with pytest.raises(IndexError): + with pytest.raises(IndexError, match=msg): sparse.take(np.array([1, 5]), allow_fill=True) def test_take_filling_fill_value(self): @@ -340,11 +341,12 @@ def test_take_filling_fill_value(self): with pytest.raises(ValueError, match=msg): sparse.take(np.array([1, 0, -5]), allow_fill=True) - with pytest.raises(IndexError): + msg = "out of bounds value in 'indices'" + with pytest.raises(IndexError, match=msg): sparse.take(np.array([1, -6])) - with pytest.raises(IndexError): + with pytest.raises(IndexError, match=msg): sparse.take(np.array([1, 5])) - with pytest.raises(IndexError): + with pytest.raises(IndexError, match=msg): sparse.take(np.array([1, 5]), fill_value=True) def test_take_filling_all_nan(self): @@ -358,11 +360,12 @@ def test_take_filling_all_nan(self): expected = SparseArray([np.nan, np.nan, np.nan], kind="block") tm.assert_sp_array_equal(result, expected) - with pytest.raises(IndexError): + msg = "out of bounds value in 'indices'" + with pytest.raises(IndexError, match=msg): sparse.take(np.array([1, -6])) - with pytest.raises(IndexError): + with pytest.raises(IndexError, match=msg): sparse.take(np.array([1, 5])) - with pytest.raises(IndexError): + with pytest.raises(IndexError, match=msg): sparse.take(np.array([1, 5]), fill_value=True) def test_set_item(self): @@ -670,10 +673,11 @@ def test_getslice_tuple(self): exp = SparseArray(dense[4:,], fill_value=0) # noqa: E231 tm.assert_sp_array_equal(res, exp) - with pytest.raises(IndexError): + msg = "too many indices for array" + with pytest.raises(IndexError, match=msg): sparse[4:, :] - with pytest.raises(IndexError): + with pytest.raises(IndexError, match=msg): # check numpy compat dense[4:, :] diff --git a/pandas/tests/arrays/sparse/test_dtype.py b/pandas/tests/arrays/sparse/test_dtype.py index aa8d2afca11e6..3194498daf825 100644 --- a/pandas/tests/arrays/sparse/test_dtype.py +++ b/pandas/tests/arrays/sparse/test_dtype.py @@ -1,3 +1,5 @@ +import re + import numpy as np import pytest @@ -80,7 +82,9 @@ def test_not_equal(a, b): def test_construct_from_string_raises(): - with pytest.raises(TypeError): + with pytest.raises( + TypeError, match="Could not construct SparseDtype from 'not a dtype'" + ): SparseDtype.construct_from_string("not a dtype") @@ -175,9 +179,20 @@ def test_update_dtype(original, dtype, expected): @pytest.mark.parametrize( - "original, dtype", - [(SparseDtype(float, np.nan), int), (SparseDtype(str, "abc"), int)], + "original, dtype, expected_error_msg", + [ + ( + SparseDtype(float, np.nan), + int, + re.escape("Cannot convert non-finite values (NA or inf) to integer"), + ), + ( + SparseDtype(str, "abc"), + int, + re.escape("invalid literal for int() with base 10: 'abc'"), + ), + ], ) -def test_update_dtype_raises(original, dtype): - with pytest.raises(ValueError): +def test_update_dtype_raises(original, dtype, expected_error_msg): + with pytest.raises(ValueError, match=expected_error_msg): original.update_dtype(dtype)
- [ ] xref #23922 - [ ] 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/30244
2019-12-12T21:44:36Z
2019-12-12T23:09:16Z
2019-12-12T23:09:16Z
2019-12-12T23:16:21Z
Remove yapf references
diff --git a/pandas/core/ops/methods.py b/pandas/core/ops/methods.py index 477c847fb01e6..8c66eea270c76 100644 --- a/pandas/core/ops/methods.py +++ b/pandas/core/ops/methods.py @@ -162,7 +162,6 @@ def _create_methods(cls, arith_method, comp_method, bool_method, special): have_divmod = issubclass(cls, ABCSeries) # divmod is available for Series - # yapf: disable new_methods = dict( add=arith_method(cls, operator.add, special), radd=arith_method(cls, radd, special), @@ -181,8 +180,8 @@ def _create_methods(cls, arith_method, comp_method, bool_method, special): rtruediv=arith_method(cls, rtruediv, special), rfloordiv=arith_method(cls, rfloordiv, special), rpow=arith_method(cls, rpow, special), - rmod=arith_method(cls, rmod, special)) - # yapf: enable + rmod=arith_method(cls, rmod, special), + ) new_methods["div"] = new_methods["truediv"] new_methods["rdiv"] = new_methods["rtruediv"] if have_divmod: diff --git a/setup.cfg b/setup.cfg index f27cd5273c06d..62d9f2e6056bb 100644 --- a/setup.cfg +++ b/setup.cfg @@ -49,13 +49,6 @@ ignore = E402, # module level import not at top of file exclude = doc/source/development/contributing_docstring.rst - -[yapf] -based_on_style = pep8 -split_before_named_assigns = false -split_penalty_after_opening_bracket = 1000000 -split_penalty_logical_operator = 30 - [tool:pytest] # sync minversion with setup.cfg & install.rst minversion = 4.0.2
I'm not aware that we actually use this
https://api.github.com/repos/pandas-dev/pandas/pulls/30243
2019-12-12T21:19:44Z
2019-12-13T13:29:30Z
2019-12-13T13:29:30Z
2020-01-16T00:33:18Z
TST: Add message checks to tests/arrays/categorical/
diff --git a/pandas/tests/arrays/categorical/test_algos.py b/pandas/tests/arrays/categorical/test_algos.py index da142fa0bd63c..870a0a5db175e 100644 --- a/pandas/tests/arrays/categorical/test_algos.py +++ b/pandas/tests/arrays/categorical/test_algos.py @@ -60,17 +60,21 @@ def test_isin_cats(): @pytest.mark.parametrize( - "to_replace, value, result", - [("b", "c", ["a", "c"]), ("c", "d", ["a", "b"]), ("b", None, ["a", None])], + "to_replace, value, result, expected_error_msg", + [ + ("b", "c", ["a", "c"], "Categorical.categories are different"), + ("c", "d", ["a", "b"], None), + ("b", None, ["a", None], "Categorical.categories length are different"), + ], ) -def test_replace(to_replace, value, result): +def test_replace(to_replace, value, result, expected_error_msg): # GH 26988 cat = pd.Categorical(["a", "b"]) expected = pd.Categorical(result) result = cat.replace(to_replace, value) tm.assert_categorical_equal(result, expected) if to_replace == "b": # the "c" test is supposed to be unchanged - with pytest.raises(AssertionError): + with pytest.raises(AssertionError, match=expected_error_msg): # ensure non-inplace call does not affect original tm.assert_categorical_equal(cat, expected) cat.replace(to_replace, value, inplace=True) @@ -104,13 +108,21 @@ def test_take_positive_no_warning(self): def test_take_bounds(self, allow_fill): # https://github.com/pandas-dev/pandas/issues/20664 cat = pd.Categorical(["a", "b", "a"]) - with pytest.raises(IndexError): + if allow_fill: + msg = "indices are out-of-bounds" + else: + msg = "index 4 is out of bounds for size 3" + with pytest.raises(IndexError, match=msg): cat.take([4, 5], allow_fill=allow_fill) def test_take_empty(self, allow_fill): # https://github.com/pandas-dev/pandas/issues/20664 cat = pd.Categorical([], categories=["a", "b"]) - with pytest.raises(IndexError): + if allow_fill: + msg = "indices are out-of-bounds" + else: + msg = "cannot do a non-empty take from an empty axes" + with pytest.raises(IndexError, match=msg): cat.take([0], allow_fill=allow_fill) def test_positional_take(self, ordered_fixture): diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py index 637a47eba0597..d2990cbc890a2 100644 --- a/pandas/tests/arrays/categorical/test_analytics.py +++ b/pandas/tests/arrays/categorical/test_analytics.py @@ -271,40 +271,42 @@ def test_map(self): # GH 12766: Return an index not an array tm.assert_index_equal(result, Index(np.array([1] * 5, dtype=np.int64))) - def test_validate_inplace(self): + @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0]) + def test_validate_inplace_raises(self, value): cat = Categorical(["A", "B", "B", "C", "A"]) - invalid_values = [1, "True", [1, 2, 3], 5.0] - - for value in invalid_values: - with pytest.raises(ValueError): - cat.set_ordered(value=True, inplace=value) + msg = ( + 'For argument "inplace" expected type bool, ' + f"received type {type(value).__name__}" + ) + with pytest.raises(ValueError, match=msg): + cat.set_ordered(value=True, inplace=value) - with pytest.raises(ValueError): - cat.as_ordered(inplace=value) + with pytest.raises(ValueError, match=msg): + cat.as_ordered(inplace=value) - with pytest.raises(ValueError): - cat.as_unordered(inplace=value) + with pytest.raises(ValueError, match=msg): + cat.as_unordered(inplace=value) - with pytest.raises(ValueError): - cat.set_categories(["X", "Y", "Z"], rename=True, inplace=value) + with pytest.raises(ValueError, match=msg): + cat.set_categories(["X", "Y", "Z"], rename=True, inplace=value) - with pytest.raises(ValueError): - cat.rename_categories(["X", "Y", "Z"], inplace=value) + with pytest.raises(ValueError, match=msg): + cat.rename_categories(["X", "Y", "Z"], inplace=value) - with pytest.raises(ValueError): - cat.reorder_categories(["X", "Y", "Z"], ordered=True, inplace=value) + with pytest.raises(ValueError, match=msg): + cat.reorder_categories(["X", "Y", "Z"], ordered=True, inplace=value) - with pytest.raises(ValueError): - cat.add_categories(new_categories=["D", "E", "F"], inplace=value) + with pytest.raises(ValueError, match=msg): + cat.add_categories(new_categories=["D", "E", "F"], inplace=value) - with pytest.raises(ValueError): - cat.remove_categories(removals=["D", "E", "F"], inplace=value) + with pytest.raises(ValueError, match=msg): + cat.remove_categories(removals=["D", "E", "F"], inplace=value) - with pytest.raises(ValueError): - cat.remove_unused_categories(inplace=value) + with pytest.raises(ValueError, match=msg): + cat.remove_unused_categories(inplace=value) - with pytest.raises(ValueError): - cat.sort_values(inplace=value) + with pytest.raises(ValueError, match=msg): + cat.sort_values(inplace=value) def test_isna(self): exp = np.array([False, False, True]) diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py index c80e963d5c409..82f2fe1ab8fb6 100644 --- a/pandas/tests/arrays/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -83,13 +83,15 @@ def test_rename_categories(self): ) tm.assert_index_equal(cat.categories, Index([1, 2, 3])) - # Lengthen - with pytest.raises(ValueError): - cat.rename_categories([1, 2, 3, 4]) - - # Shorten - with pytest.raises(ValueError): - cat.rename_categories([1, 2]) + @pytest.mark.parametrize("new_categories", [[1, 2, 3, 4], [1, 2]]) + def test_rename_categories_wrong_length_raises(self, new_categories): + cat = Categorical(["a", "b", "c", "a"]) + msg = ( + "new categories need to have the same number of items as the" + " old categories!" + ) + with pytest.raises(ValueError, match=msg): + cat.rename_categories(new_categories) def test_rename_categories_series(self): # https://github.com/pandas-dev/pandas/issues/17981 @@ -149,19 +151,19 @@ def test_reorder_categories(self): assert res is None tm.assert_categorical_equal(cat, new) - # not all "old" included in "new" + @pytest.mark.parametrize( + "new_categories", + [ + ["a"], # not all "old" included in "new" + ["a", "b", "d"], # still not all "old" in "new" + ["a", "b", "c", "d"], # all "old" included in "new", but too long + ], + ) + def test_reorder_categories_raises(self, new_categories): cat = Categorical(["a", "b", "c", "a"], ordered=True) - - with pytest.raises(ValueError): - cat.reorder_categories(["a"]) - - # still not all "old" in "new" - with pytest.raises(ValueError): - cat.reorder_categories(["a", "b", "d"]) - - # all "old" included in "new", but too long - with pytest.raises(ValueError): - cat.reorder_categories(["a", "b", "c", "d"]) + msg = "items in new_categories are not the same as in old categories" + with pytest.raises(ValueError, match=msg): + cat.reorder_categories(new_categories) def test_add_categories(self): cat = Categorical(["a", "b", "c", "a"], ordered=True) @@ -184,10 +186,6 @@ def test_add_categories(self): tm.assert_categorical_equal(cat, new) assert res is None - # new is in old categories - with pytest.raises(ValueError): - cat.add_categories(["d"]) - # GH 9927 cat = Categorical(list("abc"), ordered=True) expected = Categorical(list("abc"), categories=list("abcde"), ordered=True) @@ -201,6 +199,13 @@ def test_add_categories(self): res = cat.add_categories(["d", "e"]) tm.assert_categorical_equal(res, expected) + def test_add_categories_existing_raises(self): + # new is in old categories + cat = Categorical(["a", "b", "c", "d"], ordered=True) + msg = re.escape("new categories must not include old categories: {'d'}") + with pytest.raises(ValueError, match=msg): + cat.add_categories(["d"]) + def test_set_categories(self): cat = Categorical(["a", "b", "c", "a"], ordered=True) exp_categories = Index(["c", "b", "a"]) @@ -453,13 +458,13 @@ def test_codes_immutable(self): tm.assert_numpy_array_equal(c.codes, exp) # Assignments to codes should raise - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="cannot set Categorical codes directly"): c.codes = np.array([0, 1, 2, 0, 1], dtype="int8") # changes in the codes array should raise codes = c.codes - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="assignment destination is read-only"): codes[4] = 1 # But even after getting the codes, the original array should still be diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index f929eb24c9f19..37dea53f792cb 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -63,7 +63,8 @@ def test_setitem_different_unordered_raises(self, other): # GH-24142 target = pd.Categorical(["a", "b"], categories=["a", "b"]) mask = np.array([True, False]) - with pytest.raises(ValueError): + msg = "Cannot set a Categorical with another, without identical categories" + with pytest.raises(ValueError, match=msg): target[mask] = other[mask] @pytest.mark.parametrize( @@ -78,8 +79,8 @@ def test_setitem_same_ordered_rasies(self, other): # Gh-24142 target = pd.Categorical(["a", "b"], categories=["a", "b"], ordered=True) mask = np.array([True, False]) - - with pytest.raises(ValueError): + msg = "Cannot set a Categorical with another, without identical categories" + with pytest.raises(ValueError, match=msg): target[mask] = other[mask] @@ -152,13 +153,15 @@ def test_categories_assigments(self): tm.assert_numpy_array_equal(s.__array__(), exp) tm.assert_index_equal(s.categories, Index([1, 2, 3])) - # lengthen - with pytest.raises(ValueError): - s.categories = [1, 2, 3, 4] - - # shorten - with pytest.raises(ValueError): - s.categories = [1, 2] + @pytest.mark.parametrize("new_categories", [[1, 2, 3, 4], [1, 2]]) + def test_categories_assigments_wrong_length_raises(self, new_categories): + cat = Categorical(["a", "b", "c", "a"]) + msg = ( + "new categories need to have the same number of items" + " as the old categories!" + ) + with pytest.raises(ValueError, match=msg): + cat.categories = new_categories # Combinations of sorted/unique: @pytest.mark.parametrize( diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index d62c4f4cf936e..10e33bf70dc66 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -73,19 +73,25 @@ def test_comparisons(self): tm.assert_numpy_array_equal(res, exp) # Only categories with same categories can be compared - with pytest.raises(TypeError): + msg = "Categoricals can only be compared if 'categories' are the same" + with pytest.raises(TypeError, match=msg): cat > cat_rev cat_rev_base2 = Categorical(["b", "b", "b"], categories=["c", "b", "a", "d"]) - with pytest.raises(TypeError): + msg = ( + "Categoricals can only be compared if 'categories' are the same. " + "Categories are different lengths" + ) + with pytest.raises(TypeError, match=msg): cat_rev > cat_rev_base2 # Only categories with same ordering information can be compared cat_unorderd = cat.set_ordered(False) assert not (cat > cat).any() - with pytest.raises(TypeError): + msg = "Categoricals can only be compared if 'ordered' is the same" + with pytest.raises(TypeError, match=msg): cat > cat_unorderd # comparison (in both directions) with Series will raise @@ -131,18 +137,6 @@ def test_compare_frame(self): df = DataFrame(cat) - for op in [ - operator.eq, - operator.ne, - operator.ge, - operator.gt, - operator.le, - operator.lt, - ]: - with pytest.raises(ValueError): - # alignment raises unless we transpose - op(cat, df) - result = cat == df.T expected = DataFrame([[True, True, True, True]]) tm.assert_frame_equal(result, expected) @@ -151,6 +145,15 @@ def test_compare_frame(self): expected = DataFrame([[False, True, True, False]]) tm.assert_frame_equal(result, expected) + def test_compare_frame_raises(self, all_compare_operators): + # alignment raises unless we transpose + op = getattr(operator, all_compare_operators) + cat = Categorical(["a", "b", 2, "a"]) + df = DataFrame(cat) + msg = "Unable to coerce to Series, length must be 1: given 4" + with pytest.raises(ValueError, match=msg): + op(cat, df) + def test_datetime_categorical_comparison(self): dt_cat = Categorical(date_range("2014-01-01", periods=3), ordered=True) tm.assert_numpy_array_equal(dt_cat > dt_cat[0], np.array([False, True, True])) @@ -255,7 +258,8 @@ def test_comparisons(self, data, reverse, base): tm.assert_numpy_array_equal(res_rev.values, exp_rev2) # Only categories with same categories can be compared - with pytest.raises(TypeError): + msg = "Categoricals can only be compared if 'categories' are the same" + with pytest.raises(TypeError, match=msg): cat > cat_rev # categorical cannot be compared to Series or numpy array, and also @@ -367,7 +371,9 @@ def test_numeric_like_ops(self): # numpy ops s = Series(Categorical([1, 2, 3, 4])) - with pytest.raises(TypeError): + with pytest.raises( + TypeError, match="Categorical cannot perform the operation sum" + ): np.sum(s) # numeric ops on a Series @@ -384,7 +390,8 @@ def test_numeric_like_ops(self): getattr(s, op)(2) # invalid ufunc - with pytest.raises(TypeError): + msg = "Object with dtype category cannot perform the numpy op log" + with pytest.raises(TypeError, match=msg): np.log(s) def test_contains(self): @@ -394,7 +401,7 @@ def test_contains(self): assert "b" in c assert "z" not in c assert np.nan not in c - with pytest.raises(TypeError): + with pytest.raises(TypeError, match="unhashable type: 'list'"): assert [1] in c # assert codes NOT in index
- [ ] xref #23922 - [ ] 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/30242
2019-12-12T21:00:04Z
2019-12-15T21:35:54Z
2019-12-15T21:35:54Z
2019-12-16T00:35:03Z
BUG: to_datetime with unit with Int64
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 3810ab37822cc..3f944b8862417 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -796,6 +796,7 @@ Datetimelike - Bug in :meth:`DataFrame.append` would remove the timezone-awareness of new data (:issue:`30238`) - Bug in :meth:`Series.cummin` and :meth:`Series.cummax` with timezone-aware dtype incorrectly dropping its timezone (:issue:`15553`) - Bug in :class:`DatetimeArray`, :class:`TimedeltaArray`, and :class:`PeriodArray` where inplace addition and subtraction did not actually operate inplace (:issue:`24115`) +- Bug in :func:`pandas.to_datetime` when called with ``Series`` storing ``IntegerArray`` raising ``TypeError`` instead of returning ``Series`` (:issue:`30050`) Timedelta ^^^^^^^^^ diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index cbe6dd6c2322d..e0a2b987c98d5 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -296,10 +296,15 @@ def format_array_from_datetime(ndarray[int64_t] values, object tz=None, return result -def array_with_unit_to_datetime(ndarray values, object unit, +def array_with_unit_to_datetime(ndarray values, ndarray mask, object unit, str errors='coerce'): """ - convert the ndarray according to the unit + Convert the ndarray to datetime according to the time unit. + + This function converts an array of objects into a numpy array of + datetime64[ns]. It returns the converted array + and also returns the timezone offset + if errors: - raise: return converted values or raise OutOfBoundsDatetime if out of range on the conversion or @@ -307,6 +312,18 @@ def array_with_unit_to_datetime(ndarray values, object unit, - ignore: return non-convertible values as the same unit - coerce: NaT for non-convertibles + Parameters + ---------- + values : ndarray of object + Date-like objects to convert + mask : ndarray of bool + Not-a-time mask for non-nullable integer types conversion, + can be None + unit : object + Time unit to use during conversion + errors : str, default 'raise' + Error behavior when parsing + Returns ------- result : ndarray of m8 values @@ -316,7 +333,6 @@ def array_with_unit_to_datetime(ndarray values, object unit, Py_ssize_t i, j, n=len(values) int64_t m ndarray[float64_t] fvalues - ndarray mask bint is_ignore = errors=='ignore' bint is_coerce = errors=='coerce' bint is_raise = errors=='raise' @@ -329,9 +345,13 @@ def array_with_unit_to_datetime(ndarray values, object unit, if unit == 'ns': if issubclass(values.dtype.type, np.integer): - return values.astype('M8[ns]'), tz - # This will return a tz - return array_to_datetime(values.astype(object), errors=errors) + result = values.astype('M8[ns]') + else: + result, tz = array_to_datetime(values.astype(object), errors=errors) + if mask is not None: + iresult = result.view('i8') + iresult[mask] = NPY_NAT + return result, tz m = cast_from_unit(None, unit) @@ -343,7 +363,9 @@ def array_with_unit_to_datetime(ndarray values, object unit, if values.dtype.kind == "i": # Note: this condition makes the casting="same_kind" redundant iresult = values.astype('i8', casting='same_kind', copy=False) - mask = iresult == NPY_NAT + # If no mask, fill mask by comparing to NPY_NAT constant + if mask is None: + mask = iresult == NPY_NAT iresult[mask] = 0 fvalues = iresult.astype('f8') * m need_to_iterate = False diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index f193865d90b71..85094ce741134 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -38,6 +38,7 @@ ) from pandas.core.dtypes.missing import notna +from pandas.arrays import IntegerArray from pandas.core import algorithms from pandas.core.algorithms import unique @@ -316,8 +317,21 @@ def _convert_listlike_datetimes( elif unit is not None: if format is not None: raise ValueError("cannot specify both format and unit") - arg = getattr(arg, "values", arg) - result, tz_parsed = tslib.array_with_unit_to_datetime(arg, unit, errors=errors) + arg = getattr(arg, "_values", arg) + + # GH 30050 pass an ndarray to tslib.array_with_unit_to_datetime + # because it expects an ndarray argument + if isinstance(arg, IntegerArray): + # Explicitly pass NaT mask to array_with_unit_to_datetime + mask = arg.isna() + arg = arg._ndarray_values + else: + mask = None + + result, tz_parsed = tslib.array_with_unit_to_datetime( + arg, mask, unit, errors=errors + ) + if errors == "ignore": from pandas import Index diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index 1aaacfc0949c3..807d0b05e8d13 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -2291,3 +2291,25 @@ def test_should_cache_errors(unique_share, check_count, err_message): with pytest.raises(AssertionError, match=err_message): tools.should_cache(arg, unique_share, check_count) + + +def test_nullable_integer_to_datetime(): + # Test for #30050 + ser = pd.Series([1, 2, None, 2 ** 61, None]) + ser = ser.astype("Int64") + ser_copy = ser.copy() + + res = pd.to_datetime(ser, unit="ns") + + expected = pd.Series( + [ + np.datetime64("1970-01-01 00:00:00.000000001"), + np.datetime64("1970-01-01 00:00:00.000000002"), + np.datetime64("NaT"), + np.datetime64("2043-01-25 23:56:49.213693952"), + np.datetime64("NaT"), + ] + ) + tm.assert_series_equal(res, expected) + # Check that ser isn't mutated + tm.assert_series_equal(ser, ser_copy)
- [X] closes #30050 - [X] tests added 1 / passed 1 - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry Test output: ``` $ py.test pandas/tests/tools/test_datetime.py ============================= test session starts ============================= platform win32 -- Python 3.7.3, pytest-5.3.1, py-1.8.0, pluggy-0.13.0 rootdir: C:\git_contrib\pandas\pandas, inifile: setup.cfg plugins: hypothesis-4.50.6, cov-2.8.1, forked-1.1.2, xdist-1.30.0 collected 1 item pandas\tests\tools\test_datetime.py . [100%] ============================== 1 passed in 0.03s ============================== ``` Notes: Hello. The fix introduces one additional type check if the Series passed to `to_datetime` stores anything except and IntegerArray. It does nothing else in this case. If we try to pass an IntegerArray, it pulls all the values that aren't NaN into an ndarray, converts that into datetime and adds NaT in the places where NaNs were. No precision is lost.
https://api.github.com/repos/pandas-dev/pandas/pulls/30241
2019-12-12T20:01:05Z
2020-01-02T20:38:41Z
2020-01-02T20:38:41Z
2020-01-03T06:14:23Z
REF: dont set self.data in pytables take_data
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index fe34f009165ac..18c2a761277f1 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1994,9 +1994,8 @@ def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str): self.values = new_pd_index def take_data(self): - """ return the values & release the memory """ - self.values, values = None, self.values - return values + """ return the values""" + return self.values @property def attrs(self): @@ -2249,9 +2248,8 @@ def set_data(self, data: Union[np.ndarray, ABCExtensionArray]): self.kind = _dtype_to_kind(dtype_name) def take_data(self): - """ return the data & release the memory """ - self.data, data = None, self.data - return data + """ return the data """ + return self.data @classmethod def _get_atom(cls, values: Union[np.ndarray, ABCExtensionArray]) -> "Col":
https://api.github.com/repos/pandas-dev/pandas/pulls/30240
2019-12-12T19:24:41Z
2019-12-12T20:42:33Z
2019-12-12T20:42:33Z
2019-12-12T20:56:36Z
API: Return BoolArray for string ops when backed by StringArray
diff --git a/doc/source/user_guide/text.rst b/doc/source/user_guide/text.rst index 072871f89bdae..032d51c5a388f 100644 --- a/doc/source/user_guide/text.rst +++ b/doc/source/user_guide/text.rst @@ -74,6 +74,7 @@ These are places where the behavior of ``StringDtype`` objects differ from l. For ``StringDtype``, :ref:`string accessor methods<api.series.str>` that return **numeric** output will always return a nullable integer dtype, rather than either int or float dtype, depending on the presence of NA values. + Methods returning **boolean** output will return a nullable boolean dtype. .. ipython:: python @@ -89,7 +90,13 @@ l. For ``StringDtype``, :ref:`string accessor methods<api.series.str>` s.astype(object).str.count("a") s.astype(object).dropna().str.count("a") - When NA values are present, the output dtype is float64. + When NA values are present, the output dtype is float64. Similarly for + methods returning boolean values. + + .. ipython:: python + + s.str.isdigit() + s.str.match("a") 2. Some string methods, like :meth:`Series.str.decode` are not available on ``StringArray`` because ``StringArray`` only holds strings, not diff --git a/pandas/core/strings.py b/pandas/core/strings.py index d4d8be90402b7..6ef42eb185e49 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -2,7 +2,7 @@ from functools import wraps import re import textwrap -from typing import TYPE_CHECKING, Any, Callable, Dict, List +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Type, Union import warnings import numpy as np @@ -140,7 +140,7 @@ def _map_stringarray( The value to use for missing values. By default, this is the original value (NA). dtype : Dtype - The result dtype to use. Specifying this aviods an intermediate + The result dtype to use. Specifying this avoids an intermediate object-dtype allocation. Returns @@ -150,14 +150,20 @@ def _map_stringarray( an ndarray. """ - from pandas.arrays import IntegerArray, StringArray + from pandas.arrays import IntegerArray, StringArray, BooleanArray mask = isna(arr) assert isinstance(arr, StringArray) arr = np.asarray(arr) - if is_integer_dtype(dtype): + if is_integer_dtype(dtype) or is_bool_dtype(dtype): + constructor: Union[Type[IntegerArray], Type[BooleanArray]] + if is_integer_dtype(dtype): + constructor = IntegerArray + else: + constructor = BooleanArray + na_value_is_na = isna(na_value) if na_value_is_na: na_value = 1 @@ -167,13 +173,13 @@ def _map_stringarray( mask.view("uint8"), convert=False, na_value=na_value, - dtype=np.dtype("int64"), + dtype=np.dtype(dtype), ) if not na_value_is_na: mask[:] = False - return IntegerArray(result, mask) + return constructor(result, mask) elif is_string_dtype(dtype) and not is_object_dtype(dtype): # i.e. StringDtype @@ -181,7 +187,6 @@ def _map_stringarray( arr, func, mask.view("uint8"), convert=False, na_value=na_value ) return StringArray(result) - # TODO: BooleanArray else: # This is when the result type is object. We reach this when # -> We know the result type is truly object (e.g. .encode returns bytes @@ -297,7 +302,7 @@ def str_count(arr, pat, flags=0): """ regex = re.compile(pat, flags=flags) f = lambda x: len(regex.findall(x)) - return _na_map(f, arr, dtype=int) + return _na_map(f, arr, dtype="int64") def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True): @@ -1363,7 +1368,7 @@ def str_find(arr, sub, start=0, end=None, side="left"): else: f = lambda x: getattr(x, method)(sub, start, end) - return _na_map(f, arr, dtype=int) + return _na_map(f, arr, dtype="int64") def str_index(arr, sub, start=0, end=None, side="left"): @@ -1383,7 +1388,7 @@ def str_index(arr, sub, start=0, end=None, side="left"): else: f = lambda x: getattr(x, method)(sub, start, end) - return _na_map(f, arr, dtype=int) + return _na_map(f, arr, dtype="int64") def str_pad(arr, width, side="left", fillchar=" "): @@ -3208,7 +3213,7 @@ def rindex(self, sub, start=0, end=None): len, docstring=_shared_docs["len"], forbidden_types=None, - dtype=int, + dtype="int64", returns_string=False, ) diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 584550d562b0d..d8b9c5983618e 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -1825,7 +1825,7 @@ def test_extractall_same_as_extract_subject_index(self): def test_empty_str_methods(self): empty_str = empty = Series(dtype=object) - empty_int = Series(dtype=int) + empty_int = Series(dtype="int64") empty_bool = Series(dtype=bool) empty_bytes = Series(dtype=object) @@ -3524,6 +3524,12 @@ def test_string_array(any_string_method): assert result.dtype == "string" result = result.astype(object) + elif expected.dtype == "object" and lib.is_bool_array( + expected.values, skipna=True + ): + assert result.dtype == "boolean" + result = result.astype(object) + elif expected.dtype == "float" and expected.isna().any(): assert result.dtype == "Int64" result = result.astype("float") @@ -3549,3 +3555,19 @@ def test_string_array_numeric_integer_array(method, expected): result = getattr(s.str, method)("a") expected = Series(expected, dtype="Int64") tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "method,expected", + [ + ("isdigit", [False, None, True]), + ("isalpha", [True, None, False]), + ("isalnum", [True, None, True]), + ("isdigit", [False, None, True]), + ], +) +def test_string_array_boolean_array(method, expected): + s = Series(["a", None, "1"], dtype="string") + result = getattr(s.str, method)() + expected = Series(expected, dtype="boolean") + tm.assert_series_equal(result, expected)
ref https://github.com/pandas-dev/pandas/issues/29556
https://api.github.com/repos/pandas-dev/pandas/pulls/30239
2019-12-12T17:04:50Z
2019-12-19T17:09:21Z
2019-12-19T17:09:21Z
2019-12-19T17:28:38Z
Removed parallel CI
diff --git a/ci/setup_env.sh b/ci/setup_env.sh index a58dbe09dec01..3d79c0cfd7000 100755 --- a/ci/setup_env.sh +++ b/ci/setup_env.sh @@ -121,7 +121,7 @@ conda list pandas # Make sure any error below is reported as such echo "[Build extensions]" -python setup.py build_ext -q -i -j4 +python setup.py build_ext -q -i # XXX: Some of our environments end up with old versions of pip (10.x) # Adding a new enough version of pip to the requirements explodes the
I think this was responsible for some of the Py36 failures showing up in CI this morning, so reverting this piece for now (can still locally use parallel build_ext) until investigated further
https://api.github.com/repos/pandas-dev/pandas/pulls/30237
2019-12-12T16:24:41Z
2019-12-12T17:07:48Z
2019-12-12T17:07:48Z
2019-12-12T17:07:51Z
DOC: Add MultiIndex.get_locs to generated reference
diff --git a/doc/source/reference/indexing.rst b/doc/source/reference/indexing.rst index ec485675771c4..ab6ea5aea6c61 100644 --- a/doc/source/reference/indexing.rst +++ b/doc/source/reference/indexing.rst @@ -313,6 +313,7 @@ MultiIndex selecting :toctree: api/ MultiIndex.get_loc + MultiIndex.get_locs MultiIndex.get_loc_level MultiIndex.get_indexer MultiIndex.get_level_values diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 57c7cd2df81c1..7b0cc871cbcbc 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2879,37 +2879,37 @@ def convert_indexer(start, stop, step, indexer=indexer, codes=level_codes): def get_locs(self, seq): """ - Get location for a given label/slice/list/mask or a sequence of such as - an array of integers. + Get location for a sequence of labels. Parameters ---------- - seq : label/slice/list/mask or a sequence of such + seq : label, slice, list, mask or a sequence of such You should use one of the above for each level. If a level should not be used, set it to ``slice(None)``. Returns ------- - locs : array of integers suitable for passing to iloc + numpy.ndarray + NumPy array of integers suitable for passing to iloc. + + See Also + -------- + MultiIndex.get_loc : Get location for a label or a tuple of labels. + MultiIndex.slice_locs : Get slice location given start label(s) and + end label(s). Examples -------- >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')]) - >>> mi.get_locs('b') + >>> mi.get_locs('b') # doctest: +SKIP array([1, 2], dtype=int64) - >>> mi.get_locs([slice(None), ['e', 'f']]) + >>> mi.get_locs([slice(None), ['e', 'f']]) # doctest: +SKIP array([1, 2], dtype=int64) - >>> mi.get_locs([[True, False, True], slice('e', 'f')]) + >>> mi.get_locs([[True, False, True], slice('e', 'f')]) # doctest: +SKIP array([2], dtype=int64) - - See Also - -------- - MultiIndex.get_loc : Get location for a label or a tuple of labels. - MultiIndex.slice_locs : Get slice location given start label(s) and - end label(s). """ from .numeric import Int64Index
This should fix the failing CI, see https://github.com/pandas-dev/pandas/pull/30226 CLoses #30235
https://api.github.com/repos/pandas-dev/pandas/pulls/30234
2019-12-12T15:57:44Z
2019-12-12T17:39:53Z
2019-12-12T17:39:52Z
2019-12-12T19:26:35Z
CI: restore npdev build
diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml index b5ebb79b0f1ab..55f80bf644ecc 100644 --- a/ci/azure/posix.yml +++ b/ci/azure/posix.yml @@ -44,15 +44,13 @@ jobs: PATTERN: "not slow and not network" LOCALE_OVERRIDE: "zh_CN.UTF-8" - # Disabled for NumPy object-dtype warning. - # https://github.com/pandas-dev/pandas/issues/30043 - # py37_np_dev: - # ENV_FILE: ci/deps/azure-37-numpydev.yaml - # CONDA_PY: "37" - # PATTERN: "not slow and not network" - # TEST_ARGS: "-W error" - # PANDAS_TESTING_MODE: "deprecate" - # EXTRA_APT: "xsel" + py37_np_dev: + ENV_FILE: ci/deps/azure-37-numpydev.yaml + CONDA_PY: "37" + PATTERN: "not slow and not network" + TEST_ARGS: "-W error" + PANDAS_TESTING_MODE: "deprecate" + EXTRA_APT: "xsel" steps: - script: |
https://api.github.com/repos/pandas-dev/pandas/pulls/30233
2019-12-12T15:45:25Z
2019-12-12T21:10:53Z
2019-12-12T21:10:53Z
2019-12-12T21:13:13Z
StringArray comparisions return BooleanArray
diff --git a/doc/source/user_guide/text.rst b/doc/source/user_guide/text.rst index 072871f89bdae..ff0474dbecbb4 100644 --- a/doc/source/user_guide/text.rst +++ b/doc/source/user_guide/text.rst @@ -94,7 +94,11 @@ l. For ``StringDtype``, :ref:`string accessor methods<api.series.str>` 2. Some string methods, like :meth:`Series.str.decode` are not available on ``StringArray`` because ``StringArray`` only holds strings, not bytes. - +3. In comparision operations, :class:`arrays.StringArray` and ``Series`` backed + by a ``StringArray`` will return an object with :class:`BooleanDtype`, + rather than a ``bool`` dtype object. Missing values in a ``StringArray`` + will propagate in comparision operations, rather than always comparing + unequal like :attr:`numpy.nan`. Everything else that follows in the rest of this document applies equally to ``string`` and ``object`` dtype. diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index 2de19a3319cc5..3bad7f0162f44 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -134,6 +134,10 @@ class StringArray(PandasArray): The string methods are available on Series backed by a StringArray. + Notes + ----- + StringArray returns a BooleanArray for comparison methods. + Examples -------- >>> pd.array(['This is', 'some text', None, 'data.'], dtype="string") @@ -148,6 +152,13 @@ class StringArray(PandasArray): Traceback (most recent call last): ... ValueError: StringArray requires an object-dtype ndarray of strings. + + For comparision methods, this returns a :class:`pandas.BooleanArray` + + >>> pd.array(["a", None, "c"], dtype="string") == "a" + <BooleanArray> + [True, NA, False] + Length: 3, dtype: boolean """ # undo the PandasArray hack @@ -255,7 +266,12 @@ def value_counts(self, dropna=False): # Overrride parent because we have different return types. @classmethod def _create_arithmetic_method(cls, op): + # Note: this handles both arithmetic and comparison methods. def method(self, other): + from pandas.arrays import BooleanArray + + assert op.__name__ in ops.ARITHMETIC_BINOPS | ops.COMPARISON_BINOPS + if isinstance(other, (ABCIndexClass, ABCSeries, ABCDataFrame)): return NotImplemented @@ -275,15 +291,16 @@ def method(self, other): other = np.asarray(other) other = other[valid] - result = np.empty_like(self._ndarray, dtype="object") - result[mask] = StringDtype.na_value - result[valid] = op(self._ndarray[valid], other) - - if op.__name__ in {"add", "radd", "mul", "rmul"}: + if op.__name__ in ops.ARITHMETIC_BINOPS: + result = np.empty_like(self._ndarray, dtype="object") + result[mask] = StringDtype.na_value + result[valid] = op(self._ndarray[valid], other) return StringArray(result) else: - dtype = "object" if mask.any() else "bool" - return np.asarray(result, dtype=dtype) + # logical + result = np.zeros(len(self._ndarray), dtype="bool") + result[valid] = op(self._ndarray[valid], other) + return BooleanArray(result, mask) return compat.set_function_name(method, f"__{op.__name__}__", cls) diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index ffa38cbc3d658..14705f4d22e9b 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -5,7 +5,7 @@ """ import datetime import operator -from typing import Tuple, Union +from typing import Set, Tuple, Union import numpy as np @@ -59,6 +59,37 @@ rxor, ) +# ----------------------------------------------------------------------------- +# constants +ARITHMETIC_BINOPS: Set[str] = { + "add", + "sub", + "mul", + "pow", + "mod", + "floordiv", + "truediv", + "divmod", + "radd", + "rsub", + "rmul", + "rpow", + "rmod", + "rfloordiv", + "rtruediv", + "rdivmod", +} + + +COMPARISON_BINOPS: Set[str] = { + "eq", + "ne", + "lt", + "gt", + "le", + "ge", +} + # ----------------------------------------------------------------------------- # Ops Wrapping Utilities diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index 0dfd75a2042b0..0544ee4002890 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -154,6 +154,37 @@ def test_add_frame(): tm.assert_frame_equal(result, expected) +def test_comparison_methods_scalar(all_compare_operators): + op_name = all_compare_operators + + a = pd.array(["a", None, "c"], dtype="string") + other = "a" + result = getattr(a, op_name)(other) + expected = np.array([getattr(item, op_name)(other) for item in a], dtype=object) + expected = pd.array(expected, dtype="boolean") + tm.assert_extension_array_equal(result, expected) + + result = getattr(a, op_name)(pd.NA) + expected = pd.array([None, None, None], dtype="boolean") + tm.assert_extension_array_equal(result, expected) + + +def test_comparison_methods_array(all_compare_operators): + op_name = all_compare_operators + + a = pd.array(["a", None, "c"], dtype="string") + other = [None, None, "c"] + result = getattr(a, op_name)(other) + expected = np.empty_like(a, dtype="object") + expected[-1] = getattr(other[-1], op_name)(a[-1]) + expected = pd.array(expected, dtype="boolean") + tm.assert_extension_array_equal(result, expected) + + result = getattr(a, op_name)(pd.NA) + expected = pd.array([None, None, None], dtype="boolean") + tm.assert_extension_array_equal(result, expected) + + def test_constructor_raises(): with pytest.raises(ValueError, match="sequence of strings"): pd.arrays.StringArray(np.array(["a", "b"], dtype="S1")) diff --git a/pandas/tests/extension/test_string.py b/pandas/tests/extension/test_string.py index 471a1b79d23bc..8519c2999ade3 100644 --- a/pandas/tests/extension/test_string.py +++ b/pandas/tests/extension/test_string.py @@ -91,7 +91,7 @@ class TestCasting(base.BaseCastingTests): class TestComparisonOps(base.BaseComparisonOpsTests): def _compare_other(self, s, data, op_name, other): result = getattr(s, op_name)(other) - expected = getattr(s.astype(object), op_name)(other) + expected = getattr(s.astype(object), op_name)(other).astype("boolean") self.assert_series_equal(result, expected) def test_compare_scalar(self, data, all_compare_operators):
xref https://github.com/pandas-dev/pandas/issues/29556 cc @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/30231
2019-12-12T15:14:37Z
2019-12-18T08:30:27Z
2019-12-18T08:30:27Z
2019-12-18T08:30:33Z
Groupby crash on a single level
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst old mode 100644 new mode 100755 index d0dc3f58379a0..0f0d86e271061 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -824,7 +824,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrameGroupBy.rolling().quantile()` ignoring ``interpolation`` keyword argument (:issue:`28779`) - Bug in :meth:`DataFrame.groupby` where ``any``, ``all``, ``nunique`` and transform functions would incorrectly handle duplicate column labels (:issue:`21668`) - Bug in :meth:`DataFrameGroupBy.agg` with timezone-aware datetime64 column incorrectly casting results to the original dtype (:issue:`29641`) -- +- Bug in :meth:`DataFrame.groupby` when using axis=1 and having a single level columns index (:issue:`30208`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index b0df04f18ff1d..18b08f191770f 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -491,8 +491,11 @@ def get_grouper( raise ValueError("multiple levels only valid with MultiIndex") if isinstance(level, str): - if obj.index.name != level: - raise ValueError(f"level name {level} is not the name of the index") + if obj._get_axis(axis).name != level: + raise ValueError( + f"level name {level} is not the name " + f"of the {obj._get_axis_name(axis)}" + ) elif level > 0 or level < -1: raise ValueError("level > 0 or level < -1 only valid with MultiIndex") diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 2c84c2f034fc6..f2af397357e4f 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -501,15 +501,17 @@ def test_groupby_level(self, sort, mframe, df): with pytest.raises(ValueError, match=msg): df.groupby(level=1) - def test_groupby_level_index_names(self): + def test_groupby_level_index_names(self, axis): # GH4014 this used to raise ValueError since 'exp'>1 (in py2) df = DataFrame({"exp": ["A"] * 3 + ["B"] * 3, "var1": range(6)}).set_index( "exp" ) - df.groupby(level="exp") - msg = "level name foo is not the name of the index" + if axis in (1, "columns"): + df = df.T + df.groupby(level="exp", axis=axis) + msg = f"level name foo is not the name of the {df._get_axis_name(axis)}" with pytest.raises(ValueError, match=msg): - df.groupby(level="foo") + df.groupby(level="foo", axis=axis) @pytest.mark.parametrize("sort", [True, False]) def test_groupby_level_with_nas(self, sort):
- [/] closes #30208 - [/] tests added / passed - [/] passes `black pandas` - [/] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/30229
2019-12-12T14:24:54Z
2019-12-13T17:06:38Z
2019-12-13T17:06:37Z
2019-12-13T17:06:45Z
BUG: min/max on empty categorical fails
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 29060a93923eb..d4f58ec3086b0 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -667,6 +667,7 @@ Categorical same type as if one used the :meth:`.str.` / :meth:`.dt.` on a :class:`Series` of that type. E.g. when accessing :meth:`Series.dt.tz_localize` on a :class:`Categorical` with duplicate entries, the accessor was skipping duplicates (:issue:`27952`) - Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` that would give incorrect results on categorical data (:issue:`26988`) +- Bug where calling :meth:`Categorical.min` or :meth:`Categorical.max` on an empty Categorical would raise a numpy exception (:issue:`30227`) Datetimelike diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 7170aec3820a8..761d9907609c3 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -2116,6 +2116,10 @@ def min(self, skipna=True): Only ordered `Categoricals` have a minimum! + .. versionchanged:: 1.0.0 + + Returns an NA value on empty arrays + Raises ------ TypeError @@ -2126,6 +2130,10 @@ def min(self, skipna=True): min : the minimum of this `Categorical` """ self.check_for_ordered("min") + + if not len(self._codes): + return self.dtype.na_value + good = self._codes != -1 if not good.all(): if skipna: @@ -2143,6 +2151,10 @@ def max(self, skipna=True): Only ordered `Categoricals` have a maximum! + .. versionchanged:: 1.0.0 + + Returns an NA value on empty arrays + Raises ------ TypeError @@ -2153,6 +2165,10 @@ def max(self, skipna=True): max : the maximum of this `Categorical` """ self.check_for_ordered("max") + + if not len(self._codes): + return self.dtype.na_value + good = self._codes != -1 if not good.all(): if skipna: diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py index 637a47eba0597..3c3d9d7a44aec 100644 --- a/pandas/tests/arrays/categorical/test_analytics.py +++ b/pandas/tests/arrays/categorical/test_analytics.py @@ -5,22 +5,23 @@ from pandas.compat import PYPY -from pandas import Categorical, Index, Series +from pandas import Categorical, Index, NaT, Series, date_range from pandas.api.types import is_scalar import pandas.util.testing as tm class TestCategoricalAnalytics: - def test_min_max(self): - + @pytest.mark.parametrize("aggregation", ["min", "max"]) + def test_min_max_not_ordered_raises(self, aggregation): # unordered cats have no min/max cat = Categorical(["a", "b", "c", "d"], ordered=False) msg = "Categorical is not ordered for operation {}" - with pytest.raises(TypeError, match=msg.format("min")): - cat.min() - with pytest.raises(TypeError, match=msg.format("max")): - cat.max() + agg_func = getattr(cat, aggregation) + + with pytest.raises(TypeError, match=msg.format(aggregation)): + agg_func() + def test_min_max_ordered(self): cat = Categorical(["a", "b", "c", "d"], ordered=True) _min = cat.min() _max = cat.max() @@ -35,6 +36,29 @@ def test_min_max(self): assert _min == "d" assert _max == "a" + @pytest.mark.parametrize( + "categories,expected", + [ + (list("ABC"), np.NaN), + ([1, 2, 3], np.NaN), + pytest.param( + Series(date_range("2020-01-01", periods=3), dtype="category"), + NaT, + marks=pytest.mark.xfail( + reason="https://github.com/pandas-dev/pandas/issues/29962" + ), + ), + ], + ) + @pytest.mark.parametrize("aggregation", ["min", "max"]) + def test_min_max_ordered_empty(self, categories, expected, aggregation): + # GH 30227 + cat = Categorical([], categories=list("ABC"), ordered=True) + + agg_func = getattr(cat, aggregation) + result = agg_func() + assert result is expected + @pytest.mark.parametrize("skipna", [True, False]) def test_min_max_with_nan(self, skipna): # GH 25303
- [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Currently on master, the following fails: ```python import pandas as pd # Empty Dataframe df = pd.DataFrame({ "cat": pd.Categorical([], categories=list("ABC"), ordered=True), "val": pd.Series([], dtype="int64") }) df["cat"].max() ``` `ValueError: zero-size array to reduction operation maximum which has no identity` Other dtypes return `NaN` when calling `min()` or `max()` on an empty Series. This PR changes the behavior of Categoricals to be the same. Note that current behavior causes a downstream bug in Dask here: https://github.com/dask/dask/issues/5645, so this PR could fix that bug as well.
https://api.github.com/repos/pandas-dev/pandas/pulls/30227
2019-12-12T11:35:26Z
2019-12-17T15:52:19Z
2019-12-17T15:52:19Z
2019-12-18T07:15:23Z
DOC: Documentation for MultiIndex.get_locs() is missing in v0.25 docs
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index cffd1e99b37f3..57c7cd2df81c1 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -191,6 +191,7 @@ class MultiIndex(Index): swaplevel reorder_levels remove_unused_levels + get_locs See Also --------
Like a comment in #30056. I add "get_locs" to method - [ ] closes #30056 - [ ] 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/30226
2019-12-12T11:29:20Z
2019-12-12T11:55:03Z
2019-12-12T11:55:02Z
2019-12-12T15:57:30Z
BUG: loc-indexing with a slice on a CategoricalIndex
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 29060a93923eb..8539bca231511 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -743,7 +743,7 @@ Indexing - Fix assignment of column via `.loc` with numpy non-ns datetime type (:issue:`27395`) - Bug in :meth:`Float64Index.astype` where ``np.inf`` was not handled properly when casting to an integer dtype (:issue:`28475`) - :meth:`Index.union` could fail when the left contained duplicates (:issue:`28257`) -- Bug when indexing with ``.loc`` where the index was a :class:`CategoricalIndex` with integer and float categories, a ValueError was raised (:issue:`17569`) +- Bug when indexing with ``.loc`` where the index was a :class:`CategoricalIndex` with non-string categories didn't work (:issue:`17569`, :issue:`30225`) - :meth:`Index.get_indexer_non_unique` could fail with `TypeError` in some cases, such as when searching for ints in a string index (:issue:`28257`) - Bug in :meth:`Float64Index.get_loc` incorrectly raising ``TypeError`` instead of ``KeyError`` (:issue:`29189`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index ba0f771e1161f..fc2412ceaca0e 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2982,7 +2982,9 @@ def is_int(v): is_null_slicer = start is None and stop is None is_index_slice = is_int(start) and is_int(stop) - is_positional = is_index_slice and not self.is_integer() + is_positional = is_index_slice and not ( + self.is_integer() or self.is_categorical() + ) if kind == "getitem": """ diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 2cc853ecf568b..dc1cbb6014608 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -753,6 +753,13 @@ def is_dtype_equal(self, other): take_nd = take + @Appender(_index_shared_docs["_maybe_cast_slice_bound"]) + def _maybe_cast_slice_bound(self, label, side, kind): + if kind == "loc": + return label + + return super()._maybe_cast_slice_bound(label, side, kind) + def map(self, mapper): """ Map values using input correspondence (a dict, Series, or function). diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index bc3ee1c59f76c..40fd6575abf44 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -654,22 +654,13 @@ def test_reindexing(self): df.reindex(["a"], limit=2) def test_loc_slice(self): - # slicing - # not implemented ATM # GH9748 - - msg = ( - "cannot do slice indexing on {klass} with these " - r"indexers \[1\] of {kind}".format( - klass=str(CategoricalIndex), kind=str(int) - ) - ) - with pytest.raises(TypeError, match=msg): + with pytest.raises(KeyError, match="1"): self.df.loc[1:5] - # result = df.loc[1:5] - # expected = df.iloc[[1,2,3,4]] - # tm.assert_frame_equal(result, expected) + result = self.df.loc["b":"c"] + expected = self.df.iloc[[2, 3, 4]] + tm.assert_frame_equal(result, expected) def test_loc_and_at_with_categorical_index(self): # GH 20629 @@ -794,6 +785,7 @@ def test_loc_with_non_string_categories(self, idx_values, ordered_fixture): # GH-17569 cat_idx = CategoricalIndex(idx_values, ordered=ordered_fixture) df = DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx) + sl = slice(idx_values[0], idx_values[1]) # scalar selection result = df.loc[idx_values[0]] @@ -805,6 +797,11 @@ def test_loc_with_non_string_categories(self, idx_values, ordered_fixture): expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"]) tm.assert_frame_equal(result, expected) + # slice selection + result = df.loc[sl] + expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"]) + tm.assert_frame_equal(result, expected) + # scalar assignment result = df.copy() result.loc[idx_values[0]] = "qux" @@ -816,3 +813,9 @@ def test_loc_with_non_string_categories(self, idx_values, ordered_fixture): result.loc[idx_values[:2], "A"] = ["qux", "qux2"] expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx) tm.assert_frame_equal(result, expected) + + # slice assignment + result = df.copy() + result.loc[sl, "A"] = ["qux", "qux2"] + expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx) + tm.assert_frame_equal(result, expected)
- [x] followup to #29922 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry #29922 didn't handle loc-indexing using a slice on non-string CategoricalIndexes. This fixes that. E.g. we had: ```python >>> cat_idx = pd.CategoricalIndex([1,2,3], ordered=True) >>> df = pd.DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx) >>> df.loc[1:2, "A"] TypeError: cannot do slice indexing on... ``` The above works now.
https://api.github.com/repos/pandas-dev/pandas/pulls/30225
2019-12-12T10:12:01Z
2019-12-12T13:39:54Z
2019-12-12T13:39:53Z
2019-12-12T15:04:22Z
CLN: changed .format to f string in construction.py, dtypes/base.py, and dtypes/cast.py
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index c7dec9e1234d2..a6c489b95952f 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -265,8 +265,8 @@ def array( ) if lib.is_scalar(data): - msg = "Cannot pass scalar '{}' to 'pandas.array'." - raise ValueError(msg.format(data)) + msg = f"Cannot pass scalar '{data}' to 'pandas.array'." + raise ValueError(msg) if dtype is None and isinstance( data, (ABCSeries, ABCIndexClass, ABCExtensionArray) diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index 063014cbe970d..ae544376c452e 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -231,17 +231,13 @@ def construct_from_string(cls, string: str): ... if match: ... return cls(**match.groupdict()) ... else: - ... raise TypeError("Cannot construct a '{}' from " - ... "'{}'".format(cls.__name__, string)) + ... raise TypeError(f"Cannot construct a '{cls.__name__}' from + ... " "'{string}'") """ if not isinstance(string, str): - raise TypeError("Expects a string, got {typ}".format(typ=type(string))) + raise TypeError(f"Expects a string, got {type(string).__name__}") if string != cls.name: - raise TypeError( - "Cannot construct a '{cls}' from '{string}'".format( - cls=cls.__name__, string=string - ) - ) + raise TypeError(f"Cannot construct a '{cls.__name__}' from '{string}'") return cls() @classmethod diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index acf8b6ca4e312..0de7a2e745531 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -802,8 +802,7 @@ def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False): return arr.astype(dtype) raise TypeError( - "cannot astype a datetimelike from [{from_dtype}] " - "to [{to_dtype}]".format(from_dtype=arr.dtype, to_dtype=dtype) + f"cannot astype a datetimelike from [{arr.dtype}] " f"to [{dtype}]" ) elif is_timedelta64_dtype(arr): @@ -825,8 +824,7 @@ def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False): return arr.astype(_TD_DTYPE, copy=copy) raise TypeError( - "cannot astype a timedelta from [{from_dtype}] " - "to [{to_dtype}]".format(from_dtype=arr.dtype, to_dtype=dtype) + f"cannot astype a timedelta from [{arr.dtype}] " f"to [{dtype}]" ) elif np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer): @@ -853,8 +851,11 @@ def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False): return astype_nansafe(to_timedelta(arr).values, dtype, copy=copy) if dtype.name in ("datetime64", "timedelta64"): - msg = "The '{dtype}' dtype has no unit. Please pass in '{dtype}[ns]' instead." - raise ValueError(msg.format(dtype=dtype.name)) + msg = ( + f"The '{dtype.name}' dtype has no unit. Please pass in " + f"'{dtype.name}[ns]' instead." + ) + raise ValueError(msg) if copy or is_object_dtype(arr) or is_object_dtype(dtype): # Explicit copy, or required since NumPy can't view from / to object. @@ -1124,8 +1125,8 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"): # Force the dtype if needed. msg = ( - "The '{dtype}' dtype has no unit. " - "Please pass in '{dtype}[ns]' instead." + f"The '{dtype.name}' dtype has no unit. " + f"Please pass in '{dtype.name}[ns]' instead." ) if is_datetime64 and not is_dtype_equal(dtype, _NS_DTYPE): @@ -1134,13 +1135,10 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"): # e.g., [ps], [fs], [as] if dtype <= np.dtype("M8[ns]"): if dtype.name == "datetime64": - raise ValueError(msg.format(dtype=dtype.name)) + raise ValueError(msg) dtype = _NS_DTYPE else: - raise TypeError( - "cannot convert datetimelike to " - "dtype [{dtype}]".format(dtype=dtype) - ) + raise TypeError(f"cannot convert datetimelike to dtype [{dtype}]") elif is_datetime64tz: # our NaT doesn't support tz's @@ -1155,13 +1153,10 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"): # e.g., [ps], [fs], [as] if dtype <= np.dtype("m8[ns]"): if dtype.name == "timedelta64": - raise ValueError(msg.format(dtype=dtype.name)) + raise ValueError(msg) dtype = _TD_DTYPE else: - raise TypeError( - "cannot convert timedeltalike to " - "dtype [{dtype}]".format(dtype=dtype) - ) + raise TypeError(f"cannot convert timedeltalike to dtype [{dtype}]") if is_scalar(value): if value == iNaT or isna(value): @@ -1213,7 +1208,7 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"): return tslib.ints_to_pydatetime(ints) # we have a non-castable dtype that was passed - raise TypeError("Cannot cast datetime64 to {dtype}".format(dtype=dtype)) + raise TypeError(f"Cannot cast datetime64 to {dtype}") else: @@ -1477,7 +1472,7 @@ def maybe_cast_to_integer_array(arr, dtype, copy: bool = False): except OverflowError: raise OverflowError( "The elements provided in the data cannot all be " - "casted to the dtype {dtype}".format(dtype=dtype) + f"casted to the dtype {dtype}" ) if np.array_equal(arr, casted):
- [X] ref [#29547](https://github.com/pandas-dev/pandas/issues/29547) - [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/30223
2019-12-12T08:10:25Z
2019-12-12T13:14:12Z
2019-12-12T13:14:11Z
2019-12-12T13:14:15Z
TST: tests for needs-test issues
diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 16dfae847e0eb..d6ef3a7600abb 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -929,6 +929,14 @@ def test_filter_corner(self): result = empty.filter(like="foo") tm.assert_frame_equal(result, empty) + def test_filter_regex_non_string(self): + # GH#5798 trying to filter on non-string columns should drop, + # not raise + df = pd.DataFrame(np.random.random((3, 2)), columns=["STRING", 123]) + result = df.filter(regex="STRING") + expected = df[["STRING"]] + tm.assert_frame_equal(result, expected) + def test_take(self, float_frame): # homogeneous order = [3, 1, 2, 0] diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 08dbeb9e585f1..90ff7a585a323 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -1726,10 +1726,16 @@ def test_constructor_with_datetimes(self): tm.assert_frame_equal(df, expected) def test_constructor_datetimes_with_nulls(self): - # gh-15869 + # gh-15869, GH#11220 for arr in [ np.array([None, None, None, None, datetime.now(), None]), np.array([None, None, datetime.now(), None]), + [[np.datetime64("NaT")], [None]], + [[np.datetime64("NaT")], [pd.NaT]], + [[None], [np.datetime64("NaT")]], + [[None], [pd.NaT]], + [[pd.NaT], [np.datetime64("NaT")]], + [[pd.NaT], [None]], ]: result = DataFrame(arr).dtypes expected = Series([np.dtype("datetime64[ns]")]) diff --git a/pandas/tests/frame/test_quantile.py b/pandas/tests/frame/test_quantile.py index 5ca7dd32200ee..c25b24121d481 100644 --- a/pandas/tests/frame/test_quantile.py +++ b/pandas/tests/frame/test_quantile.py @@ -7,6 +7,16 @@ class TestDataFrameQuantile: + def test_quantile_sparse(self): + # GH#17198 + s = pd.Series(pd.SparseArray([1, 2])) + s1 = pd.Series(pd.SparseArray([3, 4])) + df = pd.DataFrame({0: s, 1: s1}) + result = df.quantile() + + expected = pd.Series([1.5, 3.5], name=0.5) + tm.assert_series_equal(result, expected) + def test_quantile(self, datetime_frame): from numpy import percentile diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index cad1fd60ca2a9..f6d2f58a63b53 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -609,6 +609,14 @@ def test_first_last_valid( assert expected_first == df.first_valid_index() assert expected_last == df.last_valid_index() + @pytest.mark.parametrize("klass", [Series, DataFrame]) + def test_first_valid_index_all_nan(self, klass): + # GH#9752 Series/DataFrame should both return None, not raise + obj = klass([np.nan]) + + assert obj.first_valid_index() is None + assert obj.iloc[:0].first_valid_index() is None + def test_first_subset(self): ts = tm.makeTimeDataFrame(freq="12h") result = ts.first("10d") diff --git a/pandas/tests/indexes/multi/test_constructor.py b/pandas/tests/indexes/multi/test_constructor.py index 90e993a807bd2..0e4d144c0fd34 100644 --- a/pandas/tests/indexes/multi/test_constructor.py +++ b/pandas/tests/indexes/multi/test_constructor.py @@ -577,6 +577,17 @@ def test_from_product_respects_none_names(): tm.assert_index_equal(result, expected) +def test_from_product_readonly(): + # GH#15286 passing read-only array to from_product + a = np.array(range(3)) + b = ["a", "b"] + expected = MultiIndex.from_product([a, b]) + + a.setflags(write=False) + result = MultiIndex.from_product([a, b]) + tm.assert_index_equal(result, expected) + + def test_create_index_existing_name(idx): # GH11193, when an existing index is passed, and a new name is not diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 6fd813c086982..d8604774777a6 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1106,6 +1106,15 @@ def test_truncate_with_different_dtypes(self): assert "None" in result assert "NaN" not in result + def test_truncate_with_different_dtypes_multiindex(self): + # GH#13000 + df = DataFrame({"Vals": range(100)}) + frame = pd.concat([df], keys=["Sweep"], names=["Sweep", "Index"]) + result = repr(frame) + + result2 = repr(frame.iloc[:5]) + assert result.startswith(result2) + def test_datetimelike_frame(self): # GH 12211 diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 72f08876e71ae..8e1fee4d542e7 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -473,6 +473,13 @@ def test_fillna_consistency(self): s2[1] = "foo" tm.assert_series_equal(s2, expected) + def test_where_sparse(self): + # GH#17198 make sure we dont get an AttributeError for sp_index + ser = pd.Series(pd.SparseArray([1, 2])) + result = ser.where(ser >= 2, 0) + expected = pd.Series(pd.SparseArray([0, 2])) + tm.assert_series_equal(result, expected) + def test_datetime64tz_fillna_round_issue(self): # GH 14872 diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index 72b72b31d8faa..227055eb222f8 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -418,3 +418,11 @@ def test_rolling_window_as_string(): expected = Series(expData, index=Index(days, name="DateCol"), name="metric") tm.assert_series_equal(result, expected) + + +def test_min_periods1(): + # GH#6795 + df = pd.DataFrame([0, 1, 2, 1, 0], columns=["a"]) + result = df["a"].rolling(3, center=True, min_periods=1).max() + expected = pd.Series([1.0, 2.0, 2.0, 2.0, 1.0], name="a") + tm.assert_series_equal(result, expected)
- [x] closes #5798 - [x] closes #6795 - [x] closes #9752 - [x] closes #11220 - [x] closes #13000 - [x] closes #15286 - [x] closes #17198 - [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/30222
2019-12-12T01:06:29Z
2019-12-12T21:05:10Z
2019-12-12T21:05:08Z
2019-12-12T23:01:17Z
CLN: remove keep_null_freq in ops
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index f3c01efed6d43..ffa38cbc3d658 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -462,7 +462,8 @@ def wrapper(left, right): res_name = get_op_result_name(left, right) lvalues = extract_array(left, extract_numpy=True) - result = arithmetic_op(lvalues, right, op, str_rep) + rvalues = extract_array(right, extract_numpy=True) + result = arithmetic_op(lvalues, rvalues, op, str_rep) return _construct_result(left, result, index=left.index, name=res_name) diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py index 414e241af7bbd..de34258f863d0 100644 --- a/pandas/core/ops/array_ops.py +++ b/pandas/core/ops/array_ops.py @@ -24,17 +24,14 @@ ) from pandas.core.dtypes.generic import ( ABCDatetimeArray, - ABCDatetimeIndex, ABCExtensionArray, ABCIndex, ABCIndexClass, ABCSeries, ABCTimedeltaArray, - ABCTimedeltaIndex, ) from pandas.core.dtypes.missing import isna, notna -from pandas.core.construction import extract_array from pandas.core.ops import missing from pandas.core.ops.dispatch import dispatch_to_extension_op, should_extension_dispatch from pandas.core.ops.invalid import invalid_comparison @@ -178,22 +175,10 @@ def arithmetic_op( from pandas.core.ops import maybe_upcast_for_op - keep_null_freq = isinstance( - right, - ( - ABCDatetimeIndex, - ABCDatetimeArray, - ABCTimedeltaIndex, - ABCTimedeltaArray, - Timestamp, - ), - ) - - # NB: We assume that extract_array has already been called on `left`, but - # cannot make the same assumption about `right`. This is because we need - # to define `keep_null_freq` before calling extract_array on it. + # NB: We assume that extract_array has already been called + # on `left` and `right`. lvalues = left - rvalues = extract_array(right, extract_numpy=True) + rvalues = right rvalues = maybe_upcast_for_op(rvalues, lvalues.shape) @@ -203,7 +188,7 @@ def arithmetic_op( # TimedeltaArray, DatetimeArray, and Timestamp are included here # because they have `freq` attribute which is handled correctly # by dispatch_to_extension_op. - res_values = dispatch_to_extension_op(op, lvalues, rvalues, keep_null_freq) + res_values = dispatch_to_extension_op(op, lvalues, rvalues) else: with np.errstate(all="ignore"): diff --git a/pandas/core/ops/dispatch.py b/pandas/core/ops/dispatch.py index 016a89eb56da3..6a2aba4264874 100644 --- a/pandas/core/ops/dispatch.py +++ b/pandas/core/ops/dispatch.py @@ -5,8 +5,6 @@ import numpy as np -from pandas.errors import NullFrequencyError - from pandas.core.dtypes.common import ( is_datetime64_dtype, is_extension_array_dtype, @@ -97,10 +95,7 @@ def should_series_dispatch(left, right, op): def dispatch_to_extension_op( - op, - left: Union[ABCExtensionArray, np.ndarray], - right: Any, - keep_null_freq: bool = False, + op, left: Union[ABCExtensionArray, np.ndarray], right: Any, ): """ Assume that left or right is a Series backed by an ExtensionArray, @@ -111,9 +106,6 @@ def dispatch_to_extension_op( op : binary operator left : ExtensionArray or np.ndarray right : object - keep_null_freq : bool, default False - Whether to re-raise a NullFrequencyError unchanged, as opposed to - catching and raising TypeError. Returns ------- @@ -131,20 +123,7 @@ def dispatch_to_extension_op( # The op calls will raise TypeError if the op is not defined # on the ExtensionArray - - try: - res_values = op(left, right) - except NullFrequencyError: - # DatetimeIndex and TimedeltaIndex with freq == None raise ValueError - # on add/sub of integers (or int-like). We re-raise as a TypeError. - if keep_null_freq: - # TODO: remove keep_null_freq after Timestamp+int deprecation - # GH#22535 is enforced - raise - raise TypeError( - "incompatible type for a datetime/timedelta " - "operation [{name}]".format(name=op.__name__) - ) + res_values = op(left, right) return res_values diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 90a41d43a2a88..b77c9a2bddcfa 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -1844,6 +1844,7 @@ def test_dt64_mul_div_numeric_invalid(self, one, dt64_series): with pytest.raises(TypeError, match=msg): one / dt64_series + # TODO: parametrize over box @pytest.mark.parametrize("op", ["__add__", "__radd__", "__sub__", "__rsub__"]) @pytest.mark.parametrize("tz", [None, "Asia/Tokyo"]) def test_dt64_series_add_intlike(self, tz, op): diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 8ea38170bb489..4a37a56f5029c 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -1046,6 +1046,58 @@ def test_td64arr_add_sub_numeric_arr_invalid(self, box_with_array, vec, dtype): with pytest.raises(TypeError): vector - tdser + # TODO: parameterize over box and de-duplicate + def test_tdi_add_sub_int(self, one): + # Variants of `one` for #19012, deprecated GH#22535 + rng = timedelta_range("1 days 09:00:00", freq="H", periods=10) + msg = "Addition/subtraction of integers" + + with pytest.raises(TypeError, match=msg): + rng + one + with pytest.raises(TypeError, match=msg): + rng += one + with pytest.raises(TypeError, match=msg): + rng - one + with pytest.raises(TypeError, match=msg): + rng -= one + + # TODO: parameterize over box and de-duplicate + @pytest.mark.parametrize("box", [np.array, pd.Index]) + def test_tdi_add_sub_integer_array(self, box): + # GH#19959, deprecated GH#22535 + rng = timedelta_range("1 days 09:00:00", freq="H", periods=3) + other = box([4, 3, 2]) + msg = "Addition/subtraction of integers and integer-arrays" + + with pytest.raises(TypeError, match=msg): + rng + other + + with pytest.raises(TypeError, match=msg): + other + rng + + with pytest.raises(TypeError, match=msg): + rng - other + + with pytest.raises(TypeError, match=msg): + other - rng + + # TODO: parameterize over box and de-duplicate + @pytest.mark.parametrize("box", [np.array, pd.Index]) + def test_tdi_addsub_integer_array_no_freq(self, box): + # GH#19959 + tdi = TimedeltaIndex(["1 Day", "NaT", "3 Hours"]) + other = box([14, -1, 16]) + msg = "Addition/subtraction of integers" + + with pytest.raises(TypeError, match=msg): + tdi + other + with pytest.raises(TypeError, match=msg): + other + tdi + with pytest.raises(TypeError, match=msg): + tdi - other + with pytest.raises(TypeError, match=msg): + other - tdi + # ------------------------------------------------------------------ # Operations with timedelta-like others diff --git a/pandas/tests/indexes/datetimes/test_arithmetic.py b/pandas/tests/indexes/datetimes/test_shift.py similarity index 99% rename from pandas/tests/indexes/datetimes/test_arithmetic.py rename to pandas/tests/indexes/datetimes/test_shift.py index 6dd7bee8207d3..6f8315debdfa9 100644 --- a/pandas/tests/indexes/datetimes/test_arithmetic.py +++ b/pandas/tests/indexes/datetimes/test_shift.py @@ -10,7 +10,7 @@ import pandas.util.testing as tm -class TestDatetimeIndexArithmetic: +class TestDatetimeIndexShift: # ------------------------------------------------------------- # DatetimeIndex.shift is used in integer addition diff --git a/pandas/tests/indexes/period/test_arithmetic.py b/pandas/tests/indexes/period/test_shift.py similarity index 99% rename from pandas/tests/indexes/period/test_arithmetic.py rename to pandas/tests/indexes/period/test_shift.py index f8274a82f1b6f..7543f85c6d138 100644 --- a/pandas/tests/indexes/period/test_arithmetic.py +++ b/pandas/tests/indexes/period/test_shift.py @@ -6,7 +6,7 @@ import pandas.util.testing as tm -class TestPeriodIndexArithmetic: +class TestPeriodIndexShift: # --------------------------------------------------------------- # PeriodIndex.shift is used by __add__ and __sub__ diff --git a/pandas/tests/indexes/timedeltas/test_arithmetic.py b/pandas/tests/indexes/timedeltas/test_arithmetic.py index 3603719eab036..680593b93eebc 100644 --- a/pandas/tests/indexes/timedeltas/test_arithmetic.py +++ b/pandas/tests/indexes/timedeltas/test_arithmetic.py @@ -97,61 +97,6 @@ def test_shift_no_freq(self): with pytest.raises(NullFrequencyError): tdi.shift(2) - # ------------------------------------------------------------- - # Binary operations TimedeltaIndex and integer - - def test_tdi_add_sub_int(self, one): - # Variants of `one` for #19012, deprecated GH#22535 - rng = timedelta_range("1 days 09:00:00", freq="H", periods=10) - msg = "Addition/subtraction of integers" - - with pytest.raises(TypeError, match=msg): - rng + one - with pytest.raises(TypeError, match=msg): - rng += one - with pytest.raises(TypeError, match=msg): - rng - one - with pytest.raises(TypeError, match=msg): - rng -= one - - # ------------------------------------------------------------- - # __add__/__sub__ with integer arrays - - @pytest.mark.parametrize("box", [np.array, pd.Index]) - def test_tdi_add_sub_integer_array(self, box): - # GH#19959, deprecated GH#22535 - rng = timedelta_range("1 days 09:00:00", freq="H", periods=3) - other = box([4, 3, 2]) - msg = "Addition/subtraction of integers and integer-arrays" - - with pytest.raises(TypeError, match=msg): - rng + other - - with pytest.raises(TypeError, match=msg): - other + rng - - with pytest.raises(TypeError, match=msg): - rng - other - - with pytest.raises(TypeError, match=msg): - other - rng - - @pytest.mark.parametrize("box", [np.array, pd.Index]) - def test_tdi_addsub_integer_array_no_freq(self, box): - # GH#19959 - tdi = TimedeltaIndex(["1 Day", "NaT", "3 Hours"]) - other = box([14, -1, 16]) - msg = "Addition/subtraction of integers" - - with pytest.raises(TypeError, match=msg): - tdi + other - with pytest.raises(TypeError, match=msg): - other + tdi - with pytest.raises(TypeError, match=msg): - tdi - other - with pytest.raises(TypeError, match=msg): - other - tdi - # ------------------------------------------------------------- # Binary operations TimedeltaIndex and timedelta-like # Note: add and sub are tested in tests.test_arithmetic, in-place
This cleanup is viable now that integer-addition has been disallowed for dt64/td64.
https://api.github.com/repos/pandas-dev/pandas/pulls/30221
2019-12-12T00:11:20Z
2019-12-12T23:08:45Z
2019-12-12T23:08:45Z
2019-12-12T23:36:59Z
CLN: no need for mixin, move non-index timedelta arithmetic test
diff --git a/pandas/tests/indexes/test_frozen.py b/pandas/tests/indexes/test_frozen.py index 40f69ee868a90..2e53e29c3fab1 100644 --- a/pandas/tests/indexes/test_frozen.py +++ b/pandas/tests/indexes/test_frozen.py @@ -5,14 +5,20 @@ from pandas.core.indexes.frozen import FrozenList -class CheckImmutableMixin: - mutable_regex = re.compile("does not support mutable operations") +class TestFrozenList: + + unicode_container = FrozenList(["\u05d0", "\u05d1", "c"]) + + def setup_method(self, _): + self.lst = [1, 2, 3, 4, 5] + self.container = FrozenList(self.lst) def check_mutable_error(self, *args, **kwargs): # Pass whatever function you normally would to pytest.raises # (after the Exception kind). + mutable_regex = re.compile("does not support mutable operations") with pytest.raises(TypeError): - self.mutable_regex(*args, **kwargs) + mutable_regex(*args, **kwargs) def test_no_mutable_funcs(self): def setitem(): @@ -34,7 +40,8 @@ def delslice(): del self.container[0:3] self.check_mutable_error(delslice) - mutable_methods = getattr(self, "mutable_methods", []) + + mutable_methods = ("extend", "pop", "remove", "insert") for meth in mutable_methods: self.check_mutable_error(getattr(self.container, meth)) @@ -44,34 +51,19 @@ def test_slicing_maintains_type(self): expected = self.lst[1:2] self.check_result(result, expected) - def check_result(self, result, expected, klass=None): - klass = klass or self.klass - assert isinstance(result, klass) + def check_result(self, result, expected): + assert isinstance(result, FrozenList) assert result == expected - -class CheckStringMixin: def test_string_methods_dont_fail(self): repr(self.container) str(self.container) bytes(self.container) def test_tricky_container(self): - if not hasattr(self, "unicode_container"): - pytest.skip("Need unicode_container to test with this") repr(self.unicode_container) str(self.unicode_container) - -class TestFrozenList(CheckImmutableMixin, CheckStringMixin): - mutable_methods = ("extend", "pop", "remove", "insert") - unicode_container = FrozenList(["\u05d0", "\u05d1", "c"]) - - def setup_method(self, _): - self.lst = [1, 2, 3, 4, 5] - self.container = FrozenList(self.lst) - self.klass = FrozenList - def test_add(self): result = self.container + (1, 2, 3) expected = FrozenList(self.lst + [1, 2, 3]) diff --git a/pandas/tests/indexes/timedeltas/test_arithmetic.py b/pandas/tests/indexes/timedeltas/test_arithmetic.py index 3603719eab036..b35ad579b377d 100644 --- a/pandas/tests/indexes/timedeltas/test_arithmetic.py +++ b/pandas/tests/indexes/timedeltas/test_arithmetic.py @@ -173,57 +173,6 @@ def test_tdi_isub_timedeltalike(self, delta): # ------------------------------------------------------------- - # TODO: after #24365 this probably belongs in scalar tests - def test_ops_ndarray(self): - td = Timedelta("1 day") - - # timedelta, timedelta - other = pd.to_timedelta(["1 day"]).values - expected = pd.to_timedelta(["2 days"]).values - tm.assert_numpy_array_equal(td + other, expected) - tm.assert_numpy_array_equal(other + td, expected) - msg = r"unsupported operand type\(s\) for \+: 'Timedelta' and 'int'" - with pytest.raises(TypeError, match=msg): - td + np.array([1]) - msg = r"unsupported operand type\(s\) for \+: 'numpy.ndarray' and 'Timedelta'" - with pytest.raises(TypeError, match=msg): - np.array([1]) + td - - expected = pd.to_timedelta(["0 days"]).values - tm.assert_numpy_array_equal(td - other, expected) - tm.assert_numpy_array_equal(-other + td, expected) - msg = r"unsupported operand type\(s\) for -: 'Timedelta' and 'int'" - with pytest.raises(TypeError, match=msg): - td - np.array([1]) - msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timedelta'" - with pytest.raises(TypeError, match=msg): - np.array([1]) - td - - expected = pd.to_timedelta(["2 days"]).values - tm.assert_numpy_array_equal(td * np.array([2]), expected) - tm.assert_numpy_array_equal(np.array([2]) * td, expected) - msg = ( - "ufunc '?multiply'? cannot use operands with types" - r" dtype\('<m8\[ns\]'\) and dtype\('<m8\[ns\]'\)" - ) - with pytest.raises(TypeError, match=msg): - td * other - with pytest.raises(TypeError, match=msg): - other * td - - tm.assert_numpy_array_equal(td / other, np.array([1], dtype=np.float64)) - tm.assert_numpy_array_equal(other / td, np.array([1], dtype=np.float64)) - - # timedelta, datetime - other = pd.to_datetime(["2000-01-01"]).values - expected = pd.to_datetime(["2000-01-02"]).values - tm.assert_numpy_array_equal(td + other, expected) - tm.assert_numpy_array_equal(other + td, expected) - - expected = pd.to_datetime(["1999-12-31"]).values - tm.assert_numpy_array_equal(-td + other, expected) - tm.assert_numpy_array_equal(other - td, expected) - def test_tdi_ops_attributes(self): rng = timedelta_range("2 days", periods=5, freq="2D", name="x") diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index 57e0b1d743984..fed613b910c55 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -241,6 +241,57 @@ def test_td_add_mixed_timedeltalike_object_dtype_array(self, op): res = op(arr, Timedelta("1D")) tm.assert_numpy_array_equal(res, exp) + # TODO: moved from index tests following #24365, may need de-duplication + def test_ops_ndarray(self): + td = Timedelta("1 day") + + # timedelta, timedelta + other = pd.to_timedelta(["1 day"]).values + expected = pd.to_timedelta(["2 days"]).values + tm.assert_numpy_array_equal(td + other, expected) + tm.assert_numpy_array_equal(other + td, expected) + msg = r"unsupported operand type\(s\) for \+: 'Timedelta' and 'int'" + with pytest.raises(TypeError, match=msg): + td + np.array([1]) + msg = r"unsupported operand type\(s\) for \+: 'numpy.ndarray' and 'Timedelta'" + with pytest.raises(TypeError, match=msg): + np.array([1]) + td + + expected = pd.to_timedelta(["0 days"]).values + tm.assert_numpy_array_equal(td - other, expected) + tm.assert_numpy_array_equal(-other + td, expected) + msg = r"unsupported operand type\(s\) for -: 'Timedelta' and 'int'" + with pytest.raises(TypeError, match=msg): + td - np.array([1]) + msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timedelta'" + with pytest.raises(TypeError, match=msg): + np.array([1]) - td + + expected = pd.to_timedelta(["2 days"]).values + tm.assert_numpy_array_equal(td * np.array([2]), expected) + tm.assert_numpy_array_equal(np.array([2]) * td, expected) + msg = ( + "ufunc '?multiply'? cannot use operands with types" + r" dtype\('<m8\[ns\]'\) and dtype\('<m8\[ns\]'\)" + ) + with pytest.raises(TypeError, match=msg): + td * other + with pytest.raises(TypeError, match=msg): + other * td + + tm.assert_numpy_array_equal(td / other, np.array([1], dtype=np.float64)) + tm.assert_numpy_array_equal(other / td, np.array([1], dtype=np.float64)) + + # timedelta, datetime + other = pd.to_datetime(["2000-01-01"]).values + expected = pd.to_datetime(["2000-01-02"]).values + tm.assert_numpy_array_equal(td + other, expected) + tm.assert_numpy_array_equal(other + td, expected) + + expected = pd.to_datetime(["1999-12-31"]).values + tm.assert_numpy_array_equal(-td + other, expected) + tm.assert_numpy_array_equal(other - td, expected) + class TestTimedeltaMultiplicationDivision: """
https://api.github.com/repos/pandas-dev/pandas/pulls/30220
2019-12-11T23:29:13Z
2019-12-13T14:09:10Z
2019-12-13T14:09:10Z
2019-12-13T15:30:43Z
DEPR: deprecate label kwarg to lreshape, closes #29742
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 29060a93923eb..eb642a178bb4e 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -490,6 +490,7 @@ Deprecations - :func:`eval` keyword argument "truediv" is deprecated and will be removed in a future version (:issue:`29812`) - :meth:`Categorical.take_nd` is deprecated, use :meth:`Categorical.take` instead (:issue:`27745`) - The parameter ``numeric_only`` of :meth:`Categorical.min` and :meth:`Categorical.max` is deprecated and replaced with ``skipna`` (:issue:`25303`) +- The parameter ``label`` in :func:`lreshape` has been deprecated and will be removed in a future version (:issue:`29742`) - .. _whatsnew_1000.prior_deprecations: diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 8e9edfa5f1409..38bda94489d01 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -3,7 +3,7 @@ import numpy as np -from pandas.util._decorators import Appender +from pandas.util._decorators import Appender, deprecate_kwarg from pandas.core.dtypes.common import is_extension_array_dtype, is_list_like from pandas.core.dtypes.concat import concat_compat @@ -122,6 +122,7 @@ def melt( return frame._constructor(mdata, columns=mcolumns) +@deprecate_kwarg(old_arg_name="label", new_arg_name=None) def lreshape(data: DataFrame, groups, dropna: bool = True, label=None) -> DataFrame: """ Reshape long-format data to wide. Generalized inverse of DataFrame.pivot @@ -132,8 +133,6 @@ def lreshape(data: DataFrame, groups, dropna: bool = True, label=None) -> DataFr groups : dict {new_name : list_of_columns} dropna : boolean, default True - label : object, default None - Dummy kwarg, not used. Examples -------- diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index d6946ea41ed84..2c03c48209fea 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -553,6 +553,9 @@ def test_pairs(self): exp = DataFrame(exp_data, columns=result.columns) tm.assert_frame_equal(result, exp) + with tm.assert_produces_warning(FutureWarning): + result = lreshape(df, spec, dropna=False, label="foo") + spec = { "visitdt": ["visitdt{i:d}".format(i=i) for i in range(1, 3)], "wt": ["wt{i:d}".format(i=i) for i in range(1, 4)],
- [x] closes #29742 - [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/30219
2019-12-11T22:17:45Z
2019-12-12T13:10:42Z
2019-12-12T13:10:42Z
2019-12-12T15:31:49Z
Parallelized Build / CI
diff --git a/ci/setup_env.sh b/ci/setup_env.sh index 3d79c0cfd7000..a58dbe09dec01 100755 --- a/ci/setup_env.sh +++ b/ci/setup_env.sh @@ -121,7 +121,7 @@ conda list pandas # Make sure any error below is reported as such echo "[Build extensions]" -python setup.py build_ext -q -i +python setup.py build_ext -q -i -j4 # XXX: Some of our environments end up with old versions of pip (10.x) # Adding a new enough version of pip to the requirements explodes the diff --git a/setup.py b/setup.py index e6a95d4e7afd8..f7eb467cca8bc 100755 --- a/setup.py +++ b/setup.py @@ -6,6 +6,7 @@ BSD license. Parts are from lxml (https://github.com/lxml/lxml) """ +import argparse from distutils.sysconfig import get_config_vars from distutils.version import LooseVersion import os @@ -129,12 +130,7 @@ def build_extensions(self): if cython: self.render_templates(_pxifiles) - numpy_incl = pkg_resources.resource_filename("numpy", "core/include") - - for ext in self.extensions: - if hasattr(ext, "include_dirs") and numpy_incl not in ext.include_dirs: - ext.include_dirs.append(numpy_incl) - _build_ext.build_extensions(self) + super().build_extensions() DESCRIPTION = "Powerful data structures for data analysis, time series, and statistics" @@ -530,6 +526,19 @@ def maybe_cythonize(extensions, *args, **kwargs): if hasattr(ext, "include_dirs") and numpy_incl not in ext.include_dirs: ext.include_dirs.append(numpy_incl) + # reuse any parallel arguments provided for compliation to cythonize + parser = argparse.ArgumentParser() + parser.add_argument("-j", type=int) + parser.add_argument("--parallel", type=int) + parsed, _ = parser.parse_known_args() + + nthreads = 0 + if parsed.parallel: + nthreads = parsed.parallel + elif parsed.j: + nthreads = parsed.j + + kwargs["nthreads"] = nthreads build_ext.render_templates(_pxifiles) return cythonize(extensions, *args, **kwargs) @@ -686,7 +695,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "_libs.window.aggregations": { "pyxfile": "_libs/window/aggregations", "language": "c++", - "suffix": ".cpp" + "suffix": ".cpp", }, "_libs.window.indexers": {"pyxfile": "_libs/window/indexers"}, "_libs.writers": {"pyxfile": "_libs/writers"},
Modeled after https://github.com/cython/cython/pull/3187 which in 0.29.14 added parallel support A very slight boost to timing from a clean directory (bottleneck is in the Cythonize calls in both cases) ```sh # Master $ time python setup.py build_ext --inplace -j 4 : 62.93s user 3.18s system 97% cpu 1:07.77 total # this branch $ time python setup.py build_ext --inplace -j 4: 58.87s user 3.32s system 105% cpu 59.030 total ```
https://api.github.com/repos/pandas-dev/pandas/pulls/30214
2019-12-11T17:39:00Z
2019-12-12T13:42:32Z
2019-12-12T13:42:32Z
2019-12-19T20:06:48Z
ENH: Support string arguments for partition_cols in pandas.to_parquet
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 29060a93923eb..4f4ace502d443 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -204,6 +204,7 @@ Other enhancements - Roundtripping DataFrames with nullable integer or string data types to parquet (:meth:`~DataFrame.to_parquet` / :func:`read_parquet`) using the `'pyarrow'` engine now preserve those data types with pyarrow >= 1.0.0 (:issue:`20612`). +- The ``partition_cols`` argument in :meth:`DataFrame.to_parquet` now accepts a string (:issue:`27117`) Build Changes ^^^^^^^^^^^^^ diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index a044cfcdf6a01..51eac8d481231 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -234,7 +234,7 @@ def to_parquet( .. versionadded:: 0.24.0 - partition_cols : list, optional, default None + partition_cols : str or list, optional, default None Column names by which to partition the dataset Columns are partitioned in the order they are given @@ -243,6 +243,8 @@ def to_parquet( kwargs Additional keyword arguments passed to the engine """ + if isinstance(partition_cols, str): + partition_cols = [partition_cols] impl = get_engine(engine) return impl.write( df, diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index a98c93c250070..251548e7caaab 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -499,6 +499,19 @@ def test_partition_cols_supported(self, pa, df_full): assert len(dataset.partitions.partition_names) == 2 assert dataset.partitions.partition_names == set(partition_cols) + def test_partition_cols_string(self, pa, df_full): + # GH #27117 + partition_cols = "bool" + partition_cols_list = [partition_cols] + df = df_full + with tm.ensure_clean_dir() as path: + df.to_parquet(path, partition_cols=partition_cols, compression=None) + import pyarrow.parquet as pq + + dataset = pq.ParquetDataset(path, validate_schema=False) + assert len(dataset.partitions.partition_names) == 1 + assert dataset.partitions.partition_names == set(partition_cols_list) + def test_empty_dataframe(self, pa): # GH #27339 df = pd.DataFrame() @@ -595,6 +608,23 @@ def test_partition_cols_supported(self, fp, df_full): actual_partition_cols = fastparquet.ParquetFile(path, False).cats assert len(actual_partition_cols) == 2 + def test_partition_cols_string(self, fp, df_full): + # GH #27117 + partition_cols = "bool" + df = df_full + with tm.ensure_clean_dir() as path: + df.to_parquet( + path, + engine="fastparquet", + partition_cols=partition_cols, + compression=None, + ) + assert os.path.exists(path) + import fastparquet # noqa: F811 + + actual_partition_cols = fastparquet.ParquetFile(path, False).cats + assert len(actual_partition_cols) == 1 + def test_partition_on_supported(self, fp, df_full): # GH #23283 partition_cols = ["bool", "int"]
- [x] closes #27117 - [x] tests added - [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/30213
2019-12-11T17:25:45Z
2019-12-14T07:59:16Z
2019-12-14T07:59:15Z
2019-12-14T07:59:26Z
Fix IntegerArray pow for special cases
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index d0dc3f58379a0..9814f92e0739b 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -869,7 +869,8 @@ Other - Bug in :meth:`DataFrame.append` that raised ``IndexError`` when appending with empty list (:issue:`28769`) - Fix :class:`AbstractHolidayCalendar` to return correct results for years after 2030 (now goes up to 2200) (:issue:`27790`) -- Fixed :class:`IntegerArray` returning ``NA`` rather than ``inf`` for operations dividing by 0 (:issue:`27398`) +- Fixed :class:`IntegerArray` returning ``inf`` rather than ``NaN`` for operations dividing by 0 (:issue:`27398`) +- Fixed ``pow`` operations for :class:`IntegerArray` when the other value is ``0`` or ``1`` (:issue:`29997`) - Bug in :meth:`Series.count` raises if use_inf_as_na is enabled (:issue:`29478`) diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index d47e7e3df27e1..3469f782c733a 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -718,13 +718,13 @@ def _create_arithmetic_method(cls, op): @unpack_zerodim_and_defer(op.__name__) def integer_arithmetic_method(self, other): - mask = None + omask = None if getattr(other, "ndim", 0) > 1: raise NotImplementedError("can only perform ops with 1-d structures") if isinstance(other, IntegerArray): - other, mask = other._data, other._mask + other, omask = other._data, other._mask elif is_list_like(other): other = np.asarray(other) @@ -742,17 +742,28 @@ def integer_arithmetic_method(self, other): raise TypeError("can only perform ops with numeric values") # nans propagate - if mask is None: + if omask is None: mask = self._mask.copy() else: - mask = self._mask | mask + mask = self._mask | omask - # 1 ** np.nan is 1. So we have to unmask those. if op_name == "pow": - mask = np.where(self == 1, False, mask) + # 1 ** x is 1. + mask = np.where((self._data == 1) & ~self._mask, False, mask) + # x ** 0 is 1. + if omask is not None: + mask = np.where((other == 0) & ~omask, False, mask) + else: + mask = np.where(other == 0, False, mask) elif op_name == "rpow": - mask = np.where(other == 1, False, mask) + # 1 ** x is 1. + if omask is not None: + mask = np.where((other == 1) & ~omask, False, mask) + else: + mask = np.where(other == 1, False, mask) + # x ** 0 is 1. + mask = np.where((self._data == 0) & ~self._mask, False, mask) with np.errstate(all="ignore"): result = op(self._data, other) diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py index d36b42ec87e51..7bb0b065df1da 100644 --- a/pandas/tests/arrays/test_integer.py +++ b/pandas/tests/arrays/test_integer.py @@ -346,22 +346,54 @@ def test_divide_by_zero(self, zero, negative): result = a / zero expected = np.array([np.nan, np.inf, -np.inf, np.nan]) if negative: - values = [np.nan, -np.inf, np.inf, np.nan] - else: - values = [np.nan, np.inf, -np.inf, np.nan] - expected = np.array(values) + expected *= -1 tm.assert_numpy_array_equal(result, expected) - def test_pow(self): - # https://github.com/pandas-dev/pandas/issues/22022 - a = integer_array([1, np.nan, np.nan, 1]) - b = integer_array([1, np.nan, 1, np.nan]) + def test_pow_scalar(self): + a = pd.array([0, 1, None, 2], dtype="Int64") + result = a ** 0 + expected = pd.array([1, 1, 1, 1], dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + result = a ** 1 + expected = pd.array([0, 1, None, 2], dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + # result = a ** pd.NA + # expected = pd.array([None, 1, None, None], dtype="Int64") + # tm.assert_extension_array_equal(result, expected) + + result = a ** np.nan + expected = np.array([np.nan, 1, np.nan, np.nan], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + # reversed + result = 0 ** a + expected = pd.array([1, 0, None, 0], dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + result = 1 ** a + expected = pd.array([1, 1, 1, 1], dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + # result = pd.NA ** a + # expected = pd.array([1, None, None, None], dtype="Int64") + # tm.assert_extension_array_equal(result, expected) + + result = np.nan ** a + expected = np.array([1, np.nan, np.nan, np.nan], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + def test_pow_array(self): + a = integer_array([0, 0, 0, 1, 1, 1, None, None, None]) + b = integer_array([0, 1, None, 0, 1, None, 0, 1, None]) result = a ** b - expected = pd.core.arrays.integer_array([1, np.nan, np.nan, 1]) + expected = integer_array([1, 0, None, 1, 1, 1, 1, None, None]) tm.assert_extension_array_equal(result, expected) def test_rpow_one_to_na(self): # https://github.com/pandas-dev/pandas/issues/22022 + # https://github.com/pandas-dev/pandas/issues/29997 arr = integer_array([np.nan, np.nan]) result = np.array([1.0, 2.0]) ** arr expected = np.array([1.0, np.nan])
Split from #29964 Only https://github.com/pandas-dev/pandas/commit/9e5a69c3a32aad746ef3df29e43df352f4551f4d is relevant. The rest is https://github.com/pandas-dev/pandas/pull/30183, but pushing this up now.
https://api.github.com/repos/pandas-dev/pandas/pulls/30210
2019-12-11T16:11:20Z
2019-12-14T07:55:29Z
2019-12-14T07:55:28Z
2019-12-14T07:55:29Z
ENH: show percentiles in timestamp describe (#30164)
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 8133e54c934ad..905348fd6db42 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -21,6 +21,17 @@ Other enhancements - - +.. --------------------------------------------------------------------------- + +.. _whatsnew_110.api.other: + +Other API changes +^^^^^^^^^^^^^^^^^ + +- :meth:`Series.describe` will now show distribution percentiles for ``datetime`` dtypes, statistics ``first`` and ``last`` + will now be ``min`` and ``max`` to match with numeric dtypes in :meth:`DataFrame.describe` (:issue:`30164`) +- +- .. --------------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6332ff45c59d0..7bf7c8b7ae75f 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9626,26 +9626,8 @@ def describe_categorical_1d(data): dtype = None if result[1] > 0: top, freq = objcounts.index[0], objcounts.iloc[0] - - if is_datetime64_any_dtype(data): - tz = data.dt.tz - asint = data.dropna().values.view("i8") - top = Timestamp(top) - if top.tzinfo is not None and tz is not None: - # Don't tz_localize(None) if key is already tz-aware - top = top.tz_convert(tz) - else: - top = top.tz_localize(tz) - names += ["top", "freq", "first", "last"] - result += [ - top, - freq, - Timestamp(asint.min(), tz=tz), - Timestamp(asint.max(), tz=tz), - ] - else: - names += ["top", "freq"] - result += [top, freq] + names += ["top", "freq"] + result += [top, freq] # If the DataFrame is empty, set 'top' and 'freq' to None # to maintain output shape consistency @@ -9656,11 +9638,23 @@ def describe_categorical_1d(data): return pd.Series(result, index=names, name=data.name, dtype=dtype) + def describe_timestamp_1d(data): + # GH-30164 + stat_index = ["count", "mean", "min"] + formatted_percentiles + ["max"] + d = ( + [data.count(), data.mean(), data.min()] + + data.quantile(percentiles).tolist() + + [data.max()] + ) + return pd.Series(d, index=stat_index, name=data.name) + def describe_1d(data): if is_bool_dtype(data): return describe_categorical_1d(data) elif is_numeric_dtype(data): return describe_numeric_1d(data) + elif is_datetime64_any_dtype(data): + return describe_timestamp_1d(data) elif is_timedelta64_dtype(data): return describe_numeric_1d(data) else: diff --git a/pandas/tests/frame/methods/test_describe.py b/pandas/tests/frame/methods/test_describe.py index 251563e51e15a..127233ed2713e 100644 --- a/pandas/tests/frame/methods/test_describe.py +++ b/pandas/tests/frame/methods/test_describe.py @@ -253,52 +253,19 @@ def test_describe_tz_values(self, tz_naive_fixture): expected = DataFrame( { - "s1": [ - 5, - np.nan, - np.nan, - np.nan, - np.nan, - np.nan, - 2, - 1.581139, - 0, - 1, - 2, - 3, - 4, - ], + "s1": [5, 2, 0, 1, 2, 3, 4, 1.581139], "s2": [ 5, - 5, - s2.value_counts().index[0], - 1, + Timestamp(2018, 1, 3).tz_localize(tz), start.tz_localize(tz), + s2[1], + s2[2], + s2[3], end.tz_localize(tz), np.nan, - np.nan, - np.nan, - np.nan, - np.nan, - np.nan, - np.nan, ], }, - index=[ - "count", - "unique", - "top", - "freq", - "first", - "last", - "mean", - "std", - "min", - "25%", - "50%", - "75%", - "max", - ], + index=["count", "mean", "min", "25%", "50%", "75%", "max", "std"], ) result = df.describe(include="all") tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/methods/test_describe.py b/pandas/tests/series/methods/test_describe.py index b147a04b11090..4e59c6995f4f2 100644 --- a/pandas/tests/series/methods/test_describe.py +++ b/pandas/tests/series/methods/test_describe.py @@ -1,6 +1,6 @@ import numpy as np -from pandas import Series, Timestamp, date_range +from pandas import Period, Series, Timedelta, Timestamp, date_range import pandas._testing as tm @@ -29,6 +29,36 @@ def test_describe(self): ) tm.assert_series_equal(result, expected) + s = Series( + [ + Timedelta("1 days"), + Timedelta("2 days"), + Timedelta("3 days"), + Timedelta("4 days"), + Timedelta("5 days"), + ], + name="timedelta_data", + ) + result = s.describe() + expected = Series( + [5, s[2], s.std(), s[0], s[1], s[2], s[3], s[4]], + name="timedelta_data", + index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"], + ) + tm.assert_series_equal(result, expected) + + s = Series( + [Period("2020-01", "M"), Period("2020-01", "M"), Period("2019-12", "M")], + name="period_data", + ) + result = s.describe() + expected = Series( + [3, 2, s[0], 2], + name="period_data", + index=["count", "unique", "top", "freq"], + ) + tm.assert_series_equal(result, expected) + def test_describe_empty_object(self): # https://github.com/pandas-dev/pandas/issues/27183 s = Series([None, None], dtype=object) @@ -57,13 +87,14 @@ def test_describe_with_tz(self, tz_naive_fixture): expected = Series( [ 5, - 5, - s.value_counts().index[0], - 1, + Timestamp(2018, 1, 3).tz_localize(tz), start.tz_localize(tz), + s[1], + s[2], + s[3], end.tz_localize(tz), ], name=name, - index=["count", "unique", "top", "freq", "first", "last"], + index=["count", "mean", "min", "25%", "50%", "75%", "max"], ) tm.assert_series_equal(result, expected)
closes https://github.com/pandas-dev/pandas/issues/30164 When creating a pandas Series of timestamps and calling `describe` on it, it will not show the percentiles of the data, even if these are specified as arguments (`s.describe(percentiles = [0.25, 0.5, 0.75])`). This PR solves the issue by introducing a new describe logic for timestamps that would: * Add the percentiles in the same way as for numeric. * Rename `first` and `last` to `min` and `max` in order to match numeric types. * Add the mean of the series. * ~~Show datetime columns alongside numerics by default in the describe method for DataFrames.~~ (just realized there were other issues in which this was deemed to be the desirable behavior) After this, it more or less matches the functionality of R's `summary` on `POSIXct` and `Date` types. Why I think this is a good idea: I oftentimes find myself trying to inspect tables of mixed types, and want to get a quick overview of which kind of ranges and variations are there in each column, including timestamps. Currently this is very inconvenient in pandas, and they are not displayed alongside numeric columns by default and don't match the names if passing `include = "all"`, which is what I want to see when I call `DataFrame.describe`. Examples: ```python import numpy as np, pandas as pd dt_list = [ "2019-01-01 00:01:00", "2019-01-01 00:02:00", "2019-01-01 00:02:10", "2019-01-01 00:10:01", "2019-01-01 00:11:00" ] s = pd.to_datetime(pd.Series(dt_list)) s.describe() ``` ```python pd.DataFrame({ "col1" : s, "col2" : np.arange(s.shape[0]) }).describe(include = "all") ``` Update: corrected the coding style to comply with `black` and pass the automatic test.
https://api.github.com/repos/pandas-dev/pandas/pulls/30209
2019-12-11T13:27:36Z
2020-01-20T23:37:56Z
2020-01-20T23:37:56Z
2020-01-20T23:38:33Z
PERF: Fix performance regression in infer_dtype
diff --git a/asv_bench/benchmarks/dtypes.py b/asv_bench/benchmarks/dtypes.py index 24cc1c6f9fa70..bd17b710b108d 100644 --- a/asv_bench/benchmarks/dtypes.py +++ b/asv_bench/benchmarks/dtypes.py @@ -5,6 +5,7 @@ from .pandas_vb_common import ( datetime_dtypes, extension_dtypes, + lib, numeric_dtypes, string_dtypes, ) @@ -40,4 +41,25 @@ def time_pandas_dtype_invalid(self, dtype): pass +class InferDtypes: + param_names = ["dtype"] + data_dict = { + "np-object": np.array([1] * 100000, dtype="O"), + "py-object": [1] * 100000, + "np-null": np.array([1] * 50000 + [np.nan] * 50000), + "py-null": [1] * 50000 + [None] * 50000, + "np-int": np.array([1] * 100000, dtype=int), + "np-floating": np.array([1.0] * 100000, dtype=float), + "empty": [], + "bytes": [b"a"] * 100000, + } + params = list(data_dict.keys()) + + def time_infer_skipna(self, dtype): + lib.infer_dtype(self.data_dict[dtype], skipna=True) + + def time_infer(self, dtype): + lib.infer_dtype(self.data_dict[dtype], skipna=False) + + from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index c288a008777cf..a24e06d735447 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -659,6 +659,7 @@ Performance improvements - Performance improvement when checking if values in a :class:`Categorical` are equal, equal or larger or larger than a given scalar. The improvement is not present if checking if the :class:`Categorical` is less than or less than or equal than the scalar (:issue:`29820`) - Performance improvement in :meth:`Index.equals` and :meth:`MultiIndex.equals` (:issue:`29134`) +- Performance improvement in :func:`~pandas.api.types.infer_dtype` when ``skipna`` is ``True`` (:issue:`28814`) .. _whatsnew_1000.bug_fixes: diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index e9a486894fbf0..ac73cf5e7ec9a 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1259,9 +1259,6 @@ def infer_dtype(value: object, skipna: bool = True) -> str: # make contiguous values = values.ravel() - if skipna: - values = values[~isnaobj(values)] - val = _try_infer_map(values) if val is not None: return val @@ -1269,6 +1266,9 @@ def infer_dtype(value: object, skipna: bool = True) -> str: if values.dtype != np.object_: values = values.astype('O') + if skipna: + values = values[~isnaobj(values)] + n = len(values) if n == 0: return 'empty'
Fixes major performance regression in `infer_dtype` introduced in aaaac86ee019675119cb0ae9c3fb7a2b7eef9959 - [x] closes #28814 - [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/30202
2019-12-11T06:34:54Z
2019-12-23T17:02:23Z
2019-12-23T17:02:23Z
2019-12-23T17:02:37Z
Cleaned Up setup.py includes
diff --git a/setup.py b/setup.py index 618cad331c25a..01d41ea5241f2 100755 --- a/setup.py +++ b/setup.py @@ -545,12 +545,10 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): return pjoin("pandas", subdir, name + suffix) -common_include = ["pandas/_libs/src/klib", "pandas/_libs/src"] -ts_include = ["pandas/_libs/tslibs/src", "pandas/_libs/tslibs"] - - lib_depends = ["pandas/_libs/src/parse_helper.h"] +klib_include = ["pandas/_libs/src/klib"] + np_datetime_headers = [ "pandas/_libs/tslibs/src/datetime/np_datetime.h", "pandas/_libs/tslibs/src/datetime/np_datetime_strings.h", @@ -564,36 +562,42 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): ext_data = { - "_libs.algos": {"pyxfile": "_libs/algos", "depends": _pxi_dep["algos"]}, + "_libs.algos": { + "pyxfile": "_libs/algos", + "include": klib_include, + "depends": _pxi_dep["algos"], + }, "_libs.groupby": {"pyxfile": "_libs/groupby"}, - "_libs.hashing": {"pyxfile": "_libs/hashing", "include": [], "depends": []}, + "_libs.hashing": {"pyxfile": "_libs/hashing", "depends": []}, "_libs.hashtable": { "pyxfile": "_libs/hashtable", + "include": klib_include, "depends": (["pandas/_libs/src/klib/khash_python.h"] + _pxi_dep["hashtable"]), }, "_libs.index": { "pyxfile": "_libs/index", - "include": common_include + ts_include, + "include": klib_include, "depends": _pxi_dep["index"], "sources": np_datetime_sources, }, "_libs.indexing": {"pyxfile": "_libs/indexing"}, "_libs.internals": {"pyxfile": "_libs/internals"}, - "_libs.interval": {"pyxfile": "_libs/interval", "depends": _pxi_dep["interval"]}, - "_libs.join": {"pyxfile": "_libs/join"}, + "_libs.interval": { + "pyxfile": "_libs/interval", + "include": klib_include, + "depends": _pxi_dep["interval"], + }, + "_libs.join": {"pyxfile": "_libs/join", "include": klib_include}, "_libs.lib": { "pyxfile": "_libs/lib", - "include": common_include + ts_include, "depends": lib_depends + tseries_depends, + "include": klib_include, # due to tokenizer import "sources": ["pandas/_libs/src/parser/tokenizer.c"], }, - "_libs.missing": { - "pyxfile": "_libs/missing", - "include": common_include + ts_include, - "depends": tseries_depends, - }, + "_libs.missing": {"pyxfile": "_libs/missing", "depends": tseries_depends}, "_libs.parsers": { "pyxfile": "_libs/parsers", + "include": klib_include + ["pandas/_libs/src"], "depends": [ "pandas/_libs/src/parser/tokenizer.h", "pandas/_libs/src/parser/io.h", @@ -605,87 +609,76 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): }, "_libs.reduction": {"pyxfile": "_libs/reduction"}, "_libs.ops": {"pyxfile": "_libs/ops"}, - "_libs.properties": {"pyxfile": "_libs/properties", "include": []}, + "_libs.properties": {"pyxfile": "_libs/properties"}, "_libs.reshape": {"pyxfile": "_libs/reshape", "depends": []}, "_libs.sparse": {"pyxfile": "_libs/sparse", "depends": _pxi_dep["sparse"]}, "_libs.tslib": { "pyxfile": "_libs/tslib", - "include": ts_include, "depends": tseries_depends, "sources": np_datetime_sources, }, "_libs.tslibs.c_timestamp": { "pyxfile": "_libs/tslibs/c_timestamp", - "include": ts_include, "depends": tseries_depends, "sources": np_datetime_sources, }, - "_libs.tslibs.ccalendar": {"pyxfile": "_libs/tslibs/ccalendar", "include": []}, + "_libs.tslibs.ccalendar": {"pyxfile": "_libs/tslibs/ccalendar"}, "_libs.tslibs.conversion": { "pyxfile": "_libs/tslibs/conversion", - "include": ts_include, "depends": tseries_depends, "sources": np_datetime_sources, }, "_libs.tslibs.fields": { "pyxfile": "_libs/tslibs/fields", - "include": ts_include, "depends": tseries_depends, "sources": np_datetime_sources, }, - "_libs.tslibs.frequencies": {"pyxfile": "_libs/tslibs/frequencies", "include": []}, - "_libs.tslibs.nattype": {"pyxfile": "_libs/tslibs/nattype", "include": []}, + "_libs.tslibs.frequencies": {"pyxfile": "_libs/tslibs/frequencies"}, + "_libs.tslibs.nattype": {"pyxfile": "_libs/tslibs/nattype"}, "_libs.tslibs.np_datetime": { "pyxfile": "_libs/tslibs/np_datetime", - "include": ts_include, "depends": np_datetime_headers, "sources": np_datetime_sources, }, "_libs.tslibs.offsets": { "pyxfile": "_libs/tslibs/offsets", - "include": ts_include, "depends": tseries_depends, "sources": np_datetime_sources, }, "_libs.tslibs.parsing": { "pyxfile": "_libs/tslibs/parsing", + "include": klib_include, "depends": ["pandas/_libs/src/parser/tokenizer.h"], "sources": ["pandas/_libs/src/parser/tokenizer.c"], }, "_libs.tslibs.period": { "pyxfile": "_libs/tslibs/period", - "include": ts_include, "depends": tseries_depends, "sources": np_datetime_sources, }, "_libs.tslibs.resolution": { "pyxfile": "_libs/tslibs/resolution", - "include": ts_include, "depends": tseries_depends, "sources": np_datetime_sources, }, "_libs.tslibs.strptime": { "pyxfile": "_libs/tslibs/strptime", - "include": ts_include, "depends": tseries_depends, "sources": np_datetime_sources, }, "_libs.tslibs.timedeltas": { "pyxfile": "_libs/tslibs/timedeltas", - "include": ts_include, "depends": np_datetime_headers, "sources": np_datetime_sources, }, "_libs.tslibs.timestamps": { "pyxfile": "_libs/tslibs/timestamps", - "include": ts_include, "depends": tseries_depends, "sources": np_datetime_sources, }, - "_libs.tslibs.timezones": {"pyxfile": "_libs/tslibs/timezones", "include": []}, + "_libs.tslibs.timezones": {"pyxfile": "_libs/tslibs/timezones"}, "_libs.tslibs.tzconversion": { "pyxfile": "_libs/tslibs/tzconversion", - "include": ts_include, "depends": tseries_depends, "sources": np_datetime_sources, }, @@ -709,7 +702,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): sources.extend(data.get("sources", [])) - include = data.get("include", common_include) + include = data.get("include") obj = Extension( "pandas.{name}".format(name=name),
Looking to make these more explicit and remove where not required
https://api.github.com/repos/pandas-dev/pandas/pulls/30201
2019-12-11T04:57:52Z
2019-12-12T21:07:17Z
2019-12-12T21:07:17Z
2019-12-12T21:07:21Z
Fixed broken link
diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst index 3052ee3001681..aefb5f0d3d2df 100644 --- a/doc/source/user_guide/missing_data.rst +++ b/doc/source/user_guide/missing_data.rst @@ -472,7 +472,7 @@ at the new values. .. _scipy: https://scipy.org/ .. _documentation: https://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation -.. _guide: https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html +.. _guide: https://docs.scipy.org/doc/scipy/tutorial/interpolate.html .. _missing_data.interp_limits:
- [x] Added the correct link in the missing data documentation for the interpolation guide
https://api.github.com/repos/pandas-dev/pandas/pulls/49351
2022-10-27T08:44:24Z
2022-10-27T15:14:00Z
2022-10-27T15:14:00Z
2022-11-08T17:17:41Z
DOC: Removed line about %S parses all the way up to nanosecond even if no
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 7791ea804a52a..22406d2871482 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -782,15 +782,7 @@ def to_datetime( `strftime documentation <https://docs.python.org/3/library/datetime.html #strftime-and-strptime-behavior>`_ for more information on choices, though - note the following differences: - - - :const:`"%f"` will parse all the way - up to nanoseconds; - - - :const:`"%S"` without :const:`"%f"` will capture all the way - up to nanoseconds if present as decimal places, and will also handle - the case where the number of seconds is an integer. - + note that :const:`"%f"` will parse all the way up to nanoseconds. exact : bool, default True Control how `format` is used: @@ -969,13 +961,6 @@ def to_datetime( ... format='%Y-%m-%d %H:%M:%S.%f') Timestamp('2018-10-26 12:00:00.000000001') - :const:`"%S"` without :const:`"%f"` will capture all the way - up to nanoseconds if present as decimal places. - - >>> pd.to_datetime('2017-03-22 15:16:45.433502912', - ... format='%Y-%m-%d %H:%M:%S') - Timestamp('2017-03-22 15:16:45.433502912') - **Non-convertible date/times** If a date does not meet the `timestamp limitations
…decimal place present from docstring - [ ] closes #49231 - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/49349
2022-10-27T04:19:36Z
2022-10-28T13:19:13Z
2022-10-28T13:19:13Z
2022-10-31T05:43:47Z
API: allow mixed-datetimes-and-ints in to_datetime, DatetimeIndex
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 2daba0752a987..b568275e7e14e 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -245,6 +245,7 @@ Other API changes - The ``other`` argument in :meth:`DataFrame.mask` and :meth:`Series.mask` now defaults to ``no_default`` instead of ``np.nan`` consistent with :meth:`DataFrame.where` and :meth:`Series.where`. Entries will be filled with the corresponding NULL value (``np.nan`` for numpy dtypes, ``pd.NA`` for extension dtypes). (:issue:`49111`) - When creating a :class:`Series` with a object-dtype :class:`Index` of datetime objects, pandas no longer silently converts the index to a :class:`DatetimeIndex` (:issue:`39307`, :issue:`23598`) - :meth:`Series.unique` with dtype "timedelta64[ns]" or "datetime64[ns]" now returns :class:`TimedeltaArray` or :class:`DatetimeArray` instead of ``numpy.ndarray`` (:issue:`49176`) +- :func:`to_datetime` and :class:`DatetimeIndex` now allow sequences containing both ``datetime`` objects and numeric entries, matching :class:`Series` behavior (:issue:`49037`) - :func:`pandas.api.dtypes.is_string_dtype` now only returns ``True`` for array-likes with ``dtype=object`` when the elements are inferred to be strings (:issue:`15585`) - Passing a sequence containing ``datetime`` objects and ``date`` objects to :class:`Series` constructor will return with ``object`` dtype instead of ``datetime64[ns]`` dtype, consistent with :class:`Index` behavior (:issue:`49341`) - Passing strings that cannot be parsed as datetimes to :class:`Series` or :class:`DataFrame` with ``dtype="datetime64[ns]"`` will raise instead of silently ignoring the keyword and returning ``object`` dtype (:issue:`24435`) diff --git a/pandas/_libs/tslib.pyi b/pandas/_libs/tslib.pyi index ac8d5bac7c6e7..f3a24a707c530 100644 --- a/pandas/_libs/tslib.pyi +++ b/pandas/_libs/tslib.pyi @@ -24,7 +24,6 @@ def array_to_datetime( yearfirst: bool = ..., utc: bool = ..., require_iso8601: bool = ..., - allow_mixed: bool = ..., ) -> tuple[np.ndarray, tzinfo | None]: ... # returned ndarray may be object dtype or datetime64[ns] diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 6d6e90673f030..e1a7c5d23fac0 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -446,7 +446,6 @@ cpdef array_to_datetime( bint yearfirst=False, bint utc=False, bint require_iso8601=False, - bint allow_mixed=False, ): """ Converts a 1D array of date-like values to a numpy array of either: @@ -475,8 +474,6 @@ cpdef array_to_datetime( indicator whether the dates should be UTC require_iso8601 : bool, default False indicator whether the datetime string should be iso8601 - allow_mixed : bool, default False - Whether to allow mixed datetimes and integers. Returns ------- @@ -710,12 +707,6 @@ cpdef array_to_datetime( val = values[i] if is_integer_object(val) or is_float_object(val): result[i] = NPY_NAT - elif allow_mixed: - pass - elif is_raise: - raise ValueError("mixed datetimes and integers in passed array") - else: - return _array_to_datetime_object(values, errors, dayfirst, yearfirst) if seen_datetime_offset and not utc_convert: # GH#17697 diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 71002377293b7..0d15ec0fff80e 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1936,10 +1936,7 @@ def sequence_to_datetimes(data) -> DatetimeArray: """ Parse/convert the passed data to either DatetimeArray or np.ndarray[object]. """ - result, tz, freq = _sequence_to_dt64ns( - data, - allow_mixed=True, - ) + result, tz, freq = _sequence_to_dt64ns(data) unit = np.datetime_data(result.dtype)[0] dtype = tz_to_dtype(tz, unit) @@ -1955,7 +1952,6 @@ def _sequence_to_dt64ns( dayfirst: bool = False, yearfirst: bool = False, ambiguous: TimeAmbiguous = "raise", - allow_mixed: bool = False, ): """ Parameters @@ -1967,8 +1963,6 @@ def _sequence_to_dt64ns( yearfirst : bool, default False ambiguous : str, bool, or arraylike, default 'raise' See pandas._libs.tslibs.tzconversion.tz_localize_to_utc. - allow_mixed : bool, default False - Interpret integers as timestamps when datetime objects are also present. Returns ------- @@ -2019,7 +2013,6 @@ def _sequence_to_dt64ns( dayfirst=dayfirst, yearfirst=yearfirst, allow_object=False, - allow_mixed=allow_mixed, ) if tz and inferred_tz: # two timezones: convert to intended from base UTC repr @@ -2108,7 +2101,6 @@ def objects_to_datetime64ns( errors: DateTimeErrorChoices = "raise", require_iso8601: bool = False, allow_object: bool = False, - allow_mixed: bool = False, ): """ Convert data to array of timestamps. @@ -2125,8 +2117,6 @@ def objects_to_datetime64ns( allow_object : bool Whether to return an object-dtype ndarray instead of raising if the data contains more than one timezone. - allow_mixed : bool, default False - Interpret integers as timestamps when datetime objects are also present. Returns ------- @@ -2155,7 +2145,6 @@ def objects_to_datetime64ns( dayfirst=dayfirst, yearfirst=yearfirst, require_iso8601=require_iso8601, - allow_mixed=allow_mixed, ) result = result.reshape(data.shape, order=order) except OverflowError as err: diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 0ae0b11a12445..81c536fedf535 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -63,7 +63,6 @@ is_complex, is_complex_dtype, is_datetime64_dtype, - is_dtype_equal, is_extension_array_dtype, is_float, is_float_dtype, @@ -1243,7 +1242,7 @@ def maybe_cast_to_datetime( Caller is responsible for handling ExtensionDtype cases and non dt64/td64 cases. """ - from pandas.core.arrays.datetimes import sequence_to_datetimes + from pandas.core.arrays.datetimes import DatetimeArray from pandas.core.arrays.timedeltas import TimedeltaArray assert dtype.kind in ["m", "M"] @@ -1259,36 +1258,24 @@ def maybe_cast_to_datetime( res = TimedeltaArray._from_sequence(value, dtype=dtype) return res - if is_datetime64_dtype(dtype): - # Incompatible types in assignment (expression has type - # "Union[dtype[Any], ExtensionDtype]", variable has type - # "Optional[dtype[Any]]") + else: + # error: Incompatible types in assignment (expression has type + # "Union[dtype[Any], ExtensionDtype]", variable has type "Optional[dtype[Any]]") dtype = _ensure_nanosecond_dtype(dtype) # type: ignore[assignment] - value = np.array(value, copy=False) - - # we have an array of datetime or timedeltas & nulls - if value.size or not is_dtype_equal(value.dtype, dtype): - _disallow_mismatched_datetimelike(value, dtype) - - dta = sequence_to_datetimes(value) - # GH 25843: Remove tz information since the dtype - # didn't specify one - - if dta.tz is not None: + try: + dta = DatetimeArray._from_sequence(value, dtype=dtype) + except ValueError as err: + # We can give a Series-specific exception message. + if "cannot supply both a tz and a timezone-naive dtype" in str(err): raise ValueError( "Cannot convert timezone-aware data to " "timezone-naive dtype. Use " "pd.Series(values).dt.tz_localize(None) instead." - ) - - # TODO(2.0): Do this astype in sequence_to_datetimes to - # avoid potential extra copy? - dta = dta.astype(dtype, copy=False) - return dta + ) from err + raise - # at this point we have converted or raised in all cases where we had a list - return cast(ArrayLike, value) + return dta def sanitize_to_nanoseconds(values: np.ndarray, copy: bool = False) -> np.ndarray: diff --git a/pandas/tests/frame/methods/test_combine_first.py b/pandas/tests/frame/methods/test_combine_first.py index 30aef0bc0ec98..e838c8fabf456 100644 --- a/pandas/tests/frame/methods/test_combine_first.py +++ b/pandas/tests/frame/methods/test_combine_first.py @@ -6,10 +6,8 @@ from pandas.compat import pa_version_under7p0 from pandas.errors import PerformanceWarning -from pandas.core.dtypes.cast import ( - find_common_type, - is_dtype_equal, -) +from pandas.core.dtypes.cast import find_common_type +from pandas.core.dtypes.common import is_dtype_equal import pandas as pd from pandas import ( diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index d14f419888023..6f864a893c273 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -3100,14 +3100,11 @@ def test_from_scalar_datetimelike_mismatched(self, constructor, cls): scalar = cls("NaT", "ns") dtype = {np.datetime64: "m8[ns]", np.timedelta64: "M8[ns]"}[cls] - msg = "Cannot cast" if cls is np.datetime64: - msg = "|".join( - [ - r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]", - "Cannot cast", - ] - ) + msg1 = r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]" + else: + msg1 = r"dtype timedelta64\[ns\] cannot be converted to datetime64\[ns\]" + msg = "|".join(["Cannot cast", msg1]) with pytest.raises(TypeError, match=msg): constructor(scalar, dtype=dtype) diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index c3b4159c2cbfc..27fe4e2d5e0b6 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1434,9 +1434,14 @@ def test_unit_mixed(self, cache, exp, arr): result = to_datetime(arr, errors="coerce", cache=cache) tm.assert_index_equal(result, expected) - msg = "mixed datetimes and integers in passed array" - with pytest.raises(ValueError, match=msg): - to_datetime(arr, errors="raise", cache=cache) + # GH#49037 pre-2.0 this raised, but it always worked with Series, + # was never clear why it was disallowed + result = to_datetime(arr, errors="raise", cache=cache) + expected = Index([Timestamp(x) for x in arr], dtype="M8[ns]") + tm.assert_index_equal(result, expected) + + result = DatetimeIndex(arr) + tm.assert_index_equal(result, expected) def test_unit_rounding(self, cache): # GH 14156 & GH 20445: argument will incur floating point errors
- [x] closes #49037 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. cc @jreback this goes a long way towards getting Series/Index constructors to match, but i dont see the reason for the current behavior, do you remember?
https://api.github.com/repos/pandas-dev/pandas/pulls/49348
2022-10-26T23:35:25Z
2022-11-17T00:53:59Z
2022-11-17T00:53:59Z
2022-11-17T01:39:33Z
REF: simplify sanitize_array
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index c7db58fe8c6a3..c381496164630 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -545,8 +545,25 @@ def sanitize_array( data = construct_1d_arraylike_from_scalar(data, len(index), dtype) return data + elif isinstance(data, ABCExtensionArray): + # it is already ensured above this is not a PandasArray + # Until GH#49309 is fixed this check needs to come before the + # ExtensionDtype check + if dtype is not None: + subarr = data.astype(dtype, copy=copy) + elif copy: + subarr = data.copy() + else: + subarr = data + + elif isinstance(dtype, ExtensionDtype): + # create an extension array from its dtype + _sanitize_non_ordered(data) + cls = dtype.construct_array_type() + subarr = cls._from_sequence(data, dtype=dtype, copy=copy) + # GH#846 - if isinstance(data, np.ndarray): + elif isinstance(data, np.ndarray): if isinstance(data, np.matrix): data = data.A @@ -556,7 +573,10 @@ def sanitize_array( # GH 47391 numpy > 1.24 will raise a RuntimeError for nan -> int # casting aligning with IntCastingNaNError below with np.errstate(invalid="ignore"): - subarr = _try_cast(data, dtype, copy) + # GH#15832: Check if we are requesting a numeric dtype and + # that we can convert the data to the requested dtype. + subarr = maybe_cast_to_integer_array(data, dtype) + except IntCastingNaNError: warnings.warn( "In a future version, passing float-dtype values containing NaN " @@ -582,28 +602,27 @@ def sanitize_array( # we will try to copy by-definition here subarr = _try_cast(data, dtype, copy) - elif isinstance(data, ABCExtensionArray): - # it is already ensured above this is not a PandasArray - subarr = data - - if dtype is not None: - subarr = subarr.astype(dtype, copy=copy) - elif copy: - subarr = subarr.copy() + elif hasattr(data, "__array__"): + # e.g. dask array GH#38645 + data = np.array(data, copy=copy) + return sanitize_array( + data, + index=index, + dtype=dtype, + copy=False, + allow_2d=allow_2d, + ) else: - if isinstance(data, (set, frozenset)): - # Raise only for unordered sets, e.g., not for dict_keys - raise TypeError(f"'{type(data).__name__}' type is unordered") - + _sanitize_non_ordered(data) # materialize e.g. generators, convert e.g. tuples, abc.ValueView - if hasattr(data, "__array__"): - # e.g. dask array GH#38645 - data = np.array(data, copy=copy) - else: - data = list(data) + data = list(data) - if dtype is not None or len(data) == 0: + if len(data) == 0 and dtype is None: + # We default to float64, matching numpy + subarr = np.array([], dtype=np.float64) + + elif dtype is not None: try: subarr = _try_cast(data, dtype, copy) except ValueError: @@ -658,6 +677,14 @@ def range_to_ndarray(rng: range) -> np.ndarray: return arr +def _sanitize_non_ordered(data) -> None: + """ + Raise only for unordered sets, e.g., not for dict_keys + """ + if isinstance(data, (set, frozenset)): + raise TypeError(f"'{type(data).__name__}' type is unordered") + + def _sanitize_ndim( result: ArrayLike, data, @@ -728,7 +755,7 @@ def _maybe_repeat(arr: ArrayLike, index: Index | None) -> ArrayLike: def _try_cast( arr: list | np.ndarray, - dtype: DtypeObj | None, + dtype: np.dtype | None, copy: bool, ) -> ArrayLike: """ @@ -738,7 +765,7 @@ def _try_cast( ---------- arr : ndarray or list Excludes: ExtensionArray, Series, Index. - dtype : np.dtype, ExtensionDtype or None + dtype : np.dtype or None copy : bool If False, don't copy the data if not needed. @@ -771,12 +798,6 @@ def _try_cast( return varr return maybe_infer_to_datetimelike(varr) - elif isinstance(dtype, ExtensionDtype): - # create an extension array from its dtype - array_type = dtype.construct_array_type()._from_sequence - subarr = array_type(arr, dtype=dtype, copy=copy) - return subarr - elif is_object_dtype(dtype): if not is_ndarray: subarr = construct_1d_object_array_from_listlike(arr) diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 8f3c93259f0c6..ee7026663b2b6 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -22,6 +22,7 @@ ArrayLike, DtypeObj, Manager, + npt, ) from pandas.util._exceptions import find_stack_level @@ -1032,7 +1033,7 @@ def _validate_or_indexify_columns( def _convert_object_array( - content: list[np.ndarray], dtype: DtypeObj | None + content: list[npt.NDArray[np.object_]], dtype: DtypeObj | None ) -> list[ArrayLike]: """ Internal function to convert object array. @@ -1059,6 +1060,7 @@ def convert(arr): arr = cls._from_sequence(arr, dtype=dtype, copy=False) else: arr = maybe_cast_to_datetime(arr, dtype) + return arr arrays = [convert(arr) for arr in content]
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49347
2022-10-26T23:12:22Z
2022-10-27T16:23:52Z
2022-10-27T16:23:52Z
2022-11-01T23:06:30Z
DEPR: to_datetime('now') match Timestamp('now')
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 78ea78ec97a3a..8ebd611468f7d 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -252,6 +252,7 @@ Removal of prior version deprecations/changes - Removed the ``display.column_space`` option in favor of ``df.to_string(col_space=...)`` (:issue:`47280`) - Removed the deprecated method ``mad`` from pandas classes (:issue:`11787`) - Removed the deprecated method ``tshift`` from pandas classes (:issue:`11631`) +- Changed the behavior of :func:`to_datetime` with argument "now" with ``utc=False`` to match ``Timestamp("now")`` (:issue:`18705`) - Changed behavior of :class:`DataFrame` constructor given floating-point ``data`` and an integer ``dtype``, when the data cannot be cast losslessly, the floating point dtype is retained, matching :class:`Series` behavior (:issue:`41170`) - Changed behavior of :class:`DataFrame` constructor when passed a ``dtype`` (other than int) that the data cannot be cast to; it now raises instead of silently ignoring the dtype (:issue:`41733`) - Changed the behavior of :class:`Series` constructor, it will no longer infer a datetime64 or timedelta64 dtype from string entries (:issue:`41731`) diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 03331f54db892..d7c0c91332e02 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -1,5 +1,3 @@ -import warnings - cimport cython from cpython.datetime cimport ( PyDate_Check, @@ -9,8 +7,6 @@ from cpython.datetime cimport ( tzinfo, ) -from pandas.util._exceptions import find_stack_level - # import datetime C API import_datetime() @@ -855,17 +851,12 @@ cdef inline bint _parse_today_now(str val, int64_t* iresult, bint utc): # We delay this check for as long as possible # because it catches relatively rare cases if val == "now": - iresult[0] = Timestamp.utcnow().value - if not utc: + if utc: + iresult[0] = Timestamp.utcnow().value + else: # GH#18705 make sure to_datetime("now") matches Timestamp("now") - warnings.warn( - "The parsing of 'now' in pd.to_datetime without `utc=True` is " - "deprecated. In a future version, this will match Timestamp('now') " - "and Timestamp.now()", - FutureWarning, - stacklevel=find_stack_level(), - ) - + # Note using Timestamp.now() is faster than Timestamp("now") + iresult[0] = Timestamp.now().value return True elif val == "today": iresult[0] = Timestamp.today().value diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index f524bc18793d8..c3b4159c2cbfc 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -626,20 +626,15 @@ def test_to_datetime_unparsable_ignore(self): def test_to_datetime_now(self): # See GH#18666 with tm.set_timezone("US/Eastern"): - msg = "The parsing of 'now' in pd.to_datetime" - with tm.assert_produces_warning( - FutureWarning, match=msg, check_stacklevel=False - ): - # checking stacklevel is tricky because we go through cython code - # GH#18705 - npnow = np.datetime64("now").astype("datetime64[ns]") - pdnow = to_datetime("now") - pdnow2 = to_datetime(["now"])[0] + # GH#18705 + now = Timestamp("now") + pdnow = to_datetime("now") + pdnow2 = to_datetime(["now"])[0] # These should all be equal with infinite perf; this gives # a generous margin of 10 seconds - assert abs(pdnow.value - npnow.astype(np.int64)) < 1e10 - assert abs(pdnow2.value - npnow.astype(np.int64)) < 1e10 + assert abs(pdnow.value - now.value) < 1e10 + assert abs(pdnow2.value - now.value) < 1e10 assert pdnow.tzinfo is None assert pdnow2.tzinfo is None @@ -673,12 +668,7 @@ def test_to_datetime_today(self, tz): @pytest.mark.parametrize("arg", ["now", "today"]) def test_to_datetime_today_now_unicode_bytes(self, arg): - warn = FutureWarning if arg == "now" else None - msg = "The parsing of 'now' in pd.to_datetime" - with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False): - # checking stacklevel is tricky because we go through cython code - # GH#18705 - to_datetime([arg]) + to_datetime([arg]) @pytest.mark.parametrize( "dt", [np.datetime64("2000-01-01"), np.datetime64("2000-01-02")]
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49346
2022-10-26T23:08:19Z
2022-10-28T03:36:41Z
2022-10-28T03:36:40Z
2022-10-28T14:38:57Z
DEPR: Enforce disallowing loc with positionals
diff --git a/asv_bench/benchmarks/io/sql.py b/asv_bench/benchmarks/io/sql.py index fb8b7dafa0ade..c1f378e8075e9 100644 --- a/asv_bench/benchmarks/io/sql.py +++ b/asv_bench/benchmarks/io/sql.py @@ -38,7 +38,7 @@ def setup(self, connection): }, index=tm.makeStringIndex(N), ) - self.df.loc[1000:3000, "float_with_nan"] = np.nan + self.df.iloc[1000:3000, 1] = np.nan self.df["date"] = self.df["datetime"].dt.date self.df["time"] = self.df["datetime"].dt.time self.df["datetime_string"] = self.df["datetime"].astype(str) @@ -88,7 +88,7 @@ def setup(self, connection, dtype): }, index=tm.makeStringIndex(N), ) - self.df.loc[1000:3000, "float_with_nan"] = np.nan + self.df.iloc[1000:3000, 1] = np.nan self.df["date"] = self.df["datetime"].dt.date self.df["time"] = self.df["datetime"].dt.time self.df["datetime_string"] = self.df["datetime"].astype(str) @@ -117,7 +117,7 @@ def setup(self): }, index=tm.makeStringIndex(N), ) - self.df.loc[1000:3000, "float_with_nan"] = np.nan + self.df.iloc[1000:3000, 1] = np.nan self.df["date"] = self.df["datetime"].dt.date self.df["time"] = self.df["datetime"].dt.time self.df["datetime_string"] = self.df["datetime"].astype(str) @@ -164,7 +164,7 @@ def setup(self, dtype): }, index=tm.makeStringIndex(N), ) - self.df.loc[1000:3000, "float_with_nan"] = np.nan + self.df.iloc[1000:3000, 1] = np.nan self.df["date"] = self.df["datetime"].dt.date self.df["time"] = self.df["datetime"].dt.time self.df["datetime_string"] = self.df["datetime"].astype(str) diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 5aa753dffcf7f..0004bc92b349e 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -256,6 +256,7 @@ Removal of prior version deprecations/changes - Enforced disallowing passing an integer ``fill_value`` to :meth:`DataFrame.shift` and :meth:`Series.shift`` with datetime64, timedelta64, or period dtypes (:issue:`32591`) - Enforced disallowing a string column label into ``times`` in :meth:`DataFrame.ewm` (:issue:`43265`) - Enforced disallowing a tuple of column labels into :meth:`.DataFrameGroupBy.__getitem__` (:issue:`30546`) +- Enforced disallowing setting values with ``.loc`` using a positional slice. Use ``.loc`` with labels or ``.iloc`` with positions instead (:issue:`31840`) - Removed setting Categorical._codes directly (:issue:`41429`) - Enforced :meth:`Rolling.count` with ``min_periods=None`` to default to the size of the window (:issue:`31302`) - Renamed ``fname`` to ``path`` in :meth:`DataFrame.to_parquet`, :meth:`DataFrame.to_stata` and :meth:`DataFrame.to_feather` (:issue:`30338`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 7571525363447..d8300bb29c274 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4189,12 +4189,9 @@ def is_int(v): elif is_positional: if kind == "loc": # GH#16121, GH#24612, GH#31810 - warnings.warn( - "Slicing a positional slice with .loc is not supported, " - "and will raise TypeError in a future version. " + raise TypeError( + "Slicing a positional slice with .loc is not allowed, " "Use .loc with labels or .iloc with positions instead.", - FutureWarning, - stacklevel=find_stack_level(), ) indexer = key else: diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 3490d05f13e9d..88ae431fb1baf 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -2795,16 +2795,13 @@ def test_loc_mixed_int_float(): assert result == 0 -def test_loc_with_positional_slice_deprecation(): +def test_loc_with_positional_slice_raises(): # GH#31840 ser = Series(range(4), index=["A", "B", "C", "D"]) - with tm.assert_produces_warning(FutureWarning): + with pytest.raises(TypeError, match="Slicing a positional slice with .loc"): ser.loc[:3] = 2 - expected = Series([2, 2, 2, 3], index=["A", "B", "C", "D"]) - tm.assert_series_equal(ser, expected) - def test_loc_slice_disallows_positional(): # GH#16121, GH#24612, GH#31810 @@ -2822,15 +2819,15 @@ def test_loc_slice_disallows_positional(): with pytest.raises(TypeError, match=msg): obj.loc[1:3] - with tm.assert_produces_warning(FutureWarning): - # GH#31840 deprecated incorrect behavior + with pytest.raises(TypeError, match="Slicing a positional slice with .loc"): + # GH#31840 enforce incorrect behavior obj.loc[1:3] = 1 with pytest.raises(TypeError, match=msg): df.loc[1:3, 1] - with tm.assert_produces_warning(FutureWarning): - # GH#31840 deprecated incorrect behavior + with pytest.raises(TypeError, match="Slicing a positional slice with .loc"): + # GH#31840 enforce incorrect behavior df.loc[1:3, 1] = 2
Introduced in https://github.com/pandas-dev/pandas/pull/31840
https://api.github.com/repos/pandas-dev/pandas/pulls/49345
2022-10-26T22:37:08Z
2022-10-28T23:16:55Z
2022-10-28T23:16:55Z
2022-10-28T23:17:28Z
REF: simplify maybe_infer_to_datetimelike
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 8395d54224f1d..1768bb7507dd9 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1985,14 +1985,13 @@ def std( # Constructor Helpers -def sequence_to_datetimes(data, require_iso8601: bool = False) -> DatetimeArray: +def sequence_to_datetimes(data) -> DatetimeArray: """ Parse/convert the passed data to either DatetimeArray or np.ndarray[object]. """ result, tz, freq = _sequence_to_dt64ns( data, allow_mixed=True, - require_iso8601=require_iso8601, ) unit = np.datetime_data(result.dtype)[0] diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index cabd85aed1bbe..65112fc19ae56 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1232,22 +1232,20 @@ def maybe_infer_to_datetimelike( if not len(v): return value - def try_datetime(v: np.ndarray) -> ArrayLike: + def try_datetime(v: np.ndarray) -> np.ndarray | DatetimeArray: # Coerce to datetime64, datetime64tz, or in corner cases # object[datetimes] from pandas.core.arrays.datetimes import sequence_to_datetimes try: - # GH#19671 we pass require_iso8601 to be relatively strict - # when parsing strings. - dta = sequence_to_datetimes(v, require_iso8601=True) - except (ValueError, TypeError): - # e.g. <class 'numpy.timedelta64'> is not convertible to datetime - return v.reshape(shape) - else: + dta = sequence_to_datetimes(v) + except (ValueError, OutOfBoundsDatetime): + # ValueError for e.g. mixed tzs # GH#19761 we may have mixed timezones, in which cast 'dta' is # an ndarray[object]. Only 1 test # relies on this behavior, see GH#40111 + return v.reshape(shape) + else: return dta.reshape(shape) def try_timedelta(v: np.ndarray) -> np.ndarray: @@ -1259,12 +1257,14 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: # `np.asarray(to_timedelta(v))`, but using a lower-level API that # does not require a circular import. td_values = array_to_timedelta64(v).view("m8[ns]") - except (ValueError, OverflowError): + except OutOfBoundsTimedelta: return v.reshape(shape) else: return td_values.reshape(shape) - # TODO: can we just do lib.maybe_convert_objects for this entire function? + # TODO: this is _almost_ equivalent to lib.maybe_convert_objects, + # the main differences are described in GH#49340 and GH#49341 + # and maybe_convert_objects doesn't catch OutOfBoundsDatetime inferred_type = lib.infer_datetimelike_array(ensure_object(v)) if inferred_type in ["period", "interval"]: @@ -1276,31 +1276,21 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: ) if inferred_type == "datetime": - # error: Incompatible types in assignment (expression has type "ExtensionArray", - # variable has type "Union[ndarray, List[Any]]") + # Incompatible types in assignment (expression has type + # "Union[ndarray[Any, Any], DatetimeArray]", variable has type + # "ndarray[Any, Any]") value = try_datetime(v) # type: ignore[assignment] elif inferred_type == "timedelta": value = try_timedelta(v) elif inferred_type == "nat": + # if all NaT, return as datetime # only reached if we have at least 1 NaT and the rest (NaT or None or np.nan) - # if all NaT, return as datetime - if isna(v).all(): - # error: Incompatible types in assignment (expression has type - # "ExtensionArray", variable has type "Union[ndarray, List[Any]]") - value = try_datetime(v) # type: ignore[assignment] - else: - # We have at least a NaT and a string - # try timedelta first to avoid spurious datetime conversions - # e.g. '00:00:01' is a timedelta but technically is also a datetime - value = try_timedelta(v) - if lib.infer_dtype(value, skipna=False) in ["mixed"]: - # cannot skip missing values, as NaT implies that the string - # is actually a datetime - - # error: Incompatible types in assignment (expression has type - # "ExtensionArray", variable has type "Union[ndarray, List[Any]]") - value = try_datetime(v) # type: ignore[assignment] + # Incompatible types in assignment (expression has type + # "Union[ndarray[Any, Any], DatetimeArray]", variable has type + # "ndarray[Any, Any]") + value = try_datetime(v) # type: ignore[assignment] + assert value.dtype == "M8[ns]" return value
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49344
2022-10-26T22:01:52Z
2022-10-27T16:25:58Z
2022-10-27T16:25:58Z
2022-10-27T18:07:29Z
DEPR: Enforce diallowing indexing with single item slice
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 78ea78ec97a3a..252c444b2e60c 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -248,6 +248,7 @@ Removal of prior version deprecations/changes - Removed setting Categorical._codes directly (:issue:`41429`) - Enforced :meth:`Rolling.count` with ``min_periods=None`` to default to the size of the window (:issue:`31302`) - Renamed ``fname`` to ``path`` in :meth:`DataFrame.to_parquet`, :meth:`DataFrame.to_stata` and :meth:`DataFrame.to_feather` (:issue:`30338`) +- Enforced disallowing indexing a :class:`Series` with a single item list with a slice (e.g. ``ser[[slice(0, 2)]]``). Either convert the list to tuple, or pass the slice directly instead (:issue:`31333`) - Enforced the ``display.max_colwidth`` option to not accept negative integers (:issue:`31569`) - Removed the ``display.column_space`` option in favor of ``df.to_string(col_space=...)`` (:issue:`47280`) - Removed the deprecated method ``mad`` from pandas classes (:issue:`11787`) diff --git a/pandas/core/indexers/utils.py b/pandas/core/indexers/utils.py index 0f3cdc4195c85..50b53ecb63082 100644 --- a/pandas/core/indexers/utils.py +++ b/pandas/core/indexers/utils.py @@ -367,12 +367,9 @@ def unpack_1tuple(tup): if isinstance(tup, list): # GH#31299 - warnings.warn( + raise ValueError( "Indexing with a single-item list containing a " - "slice is deprecated and will raise in a future " - "version. Pass a tuple instead.", - FutureWarning, - stacklevel=find_stack_level(), + "slice is not allowed. Pass a tuple instead.", ) return tup[0] diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index 993c056045ae0..e3a38fcd10642 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -284,14 +284,13 @@ def test_getitem_slice_2d(self, datetime_series): @pytest.mark.filterwarnings("ignore:Using a non-tuple:FutureWarning") def test_getitem_median_slice_bug(self): index = date_range("20090415", "20090519", freq="2B") - s = Series(np.random.randn(13), index=index) + ser = Series(np.random.randn(13), index=index) indexer = [slice(6, 7, None)] - with tm.assert_produces_warning(FutureWarning): + msg = "Indexing with a single-item list" + with pytest.raises(ValueError, match=msg): # GH#31299 - result = s[indexer] - expected = s[indexer[0]] - tm.assert_series_equal(result, expected) + ser[indexer] @pytest.mark.parametrize( "slc, positions", diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index e3df9671e6c64..7e4912ec88d36 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -194,12 +194,11 @@ def test_basic_getitem_setitem_corner(datetime_series): with pytest.raises(KeyError, match=msg): datetime_series[:, 2] = 2 - # weird lists. [slice(0, 5)] will work but not two slices - with tm.assert_produces_warning(FutureWarning): + # weird lists. [slice(0, 5)] raises but not two slices + msg = "Indexing with a single-item list" + with pytest.raises(ValueError, match=msg): # GH#31299 - result = datetime_series[[slice(None, 5)]] - expected = datetime_series[:5] - tm.assert_series_equal(result, expected) + datetime_series[[slice(None, 5)]] # OK msg = r"unhashable type(: 'slice')?"
Introduced in #31333
https://api.github.com/repos/pandas-dev/pandas/pulls/49343
2022-10-26T21:35:44Z
2022-10-27T00:09:08Z
2022-10-27T00:09:08Z
2022-10-27T02:00:40Z
DEPR: Enforce empty Series returning object dtype
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 5aa753dffcf7f..021d7b095b7dc 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -264,6 +264,7 @@ Removal of prior version deprecations/changes - Removed the ``display.column_space`` option in favor of ``df.to_string(col_space=...)`` (:issue:`47280`) - Removed the deprecated method ``mad`` from pandas classes (:issue:`11787`) - Removed the deprecated method ``tshift`` from pandas classes (:issue:`11631`) +- Changed behavior of empty data passed into :class:`Series`; the default dtype will be ``object`` instead of ``float64`` (:issue:`29405`) - Changed the behavior of :func:`to_datetime` with argument "now" with ``utc=False`` to match ``Timestamp("now")`` (:issue:`18705`) - Changed behavior of :class:`DataFrame` constructor given floating-point ``data`` and an integer ``dtype``, when the data cannot be cast losslessly, the floating point dtype is retained, matching :class:`Series` behavior (:issue:`41170`) - Changed behavior of :class:`DataFrame` constructor when passed a ``dtype`` (other than int) that the data cannot be cast to; it now raises instead of silently ignoring the dtype (:issue:`41733`) diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 4f9af2d0c01d6..5c35b509ba00a 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -58,10 +58,7 @@ from pandas.core.algorithms import safe_sort from pandas.core.base import SelectionMixin import pandas.core.common as com -from pandas.core.construction import ( - create_series_with_explicit_dtype, - ensure_wrapped_if_datetimelike, -) +from pandas.core.construction import ensure_wrapped_if_datetimelike if TYPE_CHECKING: from pandas import ( @@ -906,14 +903,12 @@ def wrap_results(self, results: ResType, res_index: Index) -> DataFrame | Series # dict of scalars - # the default dtype of an empty Series will be `object`, but this + # the default dtype of an empty Series is `object`, but this # code can be hit by df.mean() where the result should have dtype # float64 even if it's an empty Series. constructor_sliced = self.obj._constructor_sliced - if constructor_sliced is Series: - result = create_series_with_explicit_dtype( - results, dtype_if_empty=np.float64 - ) + if len(results) == 0 and constructor_sliced is Series: + result = constructor_sliced(results, dtype=np.float64) else: result = constructor_sliced(results) result.index = res_index diff --git a/pandas/core/base.py b/pandas/core/base.py index 5e0694ea91360..e88ad801062c9 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -71,7 +71,6 @@ from pandas.core.arraylike import OpsMixin from pandas.core.arrays import ExtensionArray from pandas.core.construction import ( - create_series_with_explicit_dtype, ensure_wrapped_if_datetimelike, extract_array, ) @@ -842,9 +841,12 @@ def _map_values(self, mapper, na_action=None): # expected to be pd.Series(np.nan, ...). As np.nan is # of dtype float64 the return value of this method should # be float64 as well - mapper = create_series_with_explicit_dtype( - mapper, dtype_if_empty=np.float64 - ) + from pandas import Series + + if len(mapper) == 0: + mapper = Series(mapper, dtype=np.float64) + else: + mapper = Series(mapper) if isinstance(mapper, ABCSeries): if na_action not in (None, "ignore"): diff --git a/pandas/core/construction.py b/pandas/core/construction.py index c381496164630..259fd81911782 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -8,7 +8,6 @@ from typing import ( TYPE_CHECKING, - Any, Optional, Sequence, Union, @@ -830,62 +829,3 @@ def _try_cast( subarr = np.array(arr, dtype=dtype, copy=copy) return subarr - - -def is_empty_data(data: Any) -> bool: - """ - Utility to check if a Series is instantiated with empty data, - which does not contain dtype information. - - Parameters - ---------- - data : array-like, Iterable, dict, or scalar value - Contains data stored in Series. - - Returns - ------- - bool - """ - is_none = data is None - is_list_like_without_dtype = is_list_like(data) and not hasattr(data, "dtype") - is_simple_empty = is_list_like_without_dtype and not data - return is_none or is_simple_empty - - -def create_series_with_explicit_dtype( - data: Any = None, - index: ArrayLike | Index | None = None, - dtype: Dtype | None = None, - name: str | None = None, - copy: bool = False, - fastpath: bool = False, - dtype_if_empty: Dtype = object, -) -> Series: - """ - Helper to pass an explicit dtype when instantiating an empty Series. - - This silences a DeprecationWarning described in GitHub-17261. - - Parameters - ---------- - data : Mirrored from Series.__init__ - index : Mirrored from Series.__init__ - dtype : Mirrored from Series.__init__ - name : Mirrored from Series.__init__ - copy : Mirrored from Series.__init__ - fastpath : Mirrored from Series.__init__ - dtype_if_empty : str, numpy.dtype, or ExtensionDtype - This dtype will be passed explicitly if an empty Series will - be instantiated. - - Returns - ------- - Series - """ - from pandas.core.series import Series - - if is_empty_data(data) and dtype is None: - dtype = dtype_if_empty - return Series( - data=data, index=index, dtype=dtype, name=name, copy=copy, fastpath=fastpath - ) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 05494e37256df..cf492f0716ef5 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -145,10 +145,7 @@ from pandas.core.array_algos.replace import should_use_regex from pandas.core.arrays import ExtensionArray from pandas.core.base import PandasObject -from pandas.core.construction import ( - create_series_with_explicit_dtype, - extract_array, -) +from pandas.core.construction import extract_array from pandas.core.describe import describe_ndframe from pandas.core.flags import Flags from pandas.core.indexes.api import ( @@ -6843,9 +6840,9 @@ def fillna( if inplace: return None return self.copy() - value = create_series_with_explicit_dtype( - value, dtype_if_empty=object - ) + from pandas import Series + + value = Series(value) value = value.reindex(self.index, copy=False) value = value._values elif not is_list_like(value): diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 4c06ee60d3f6a..2ea88e4135d41 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -80,7 +80,6 @@ ) from pandas.core.arrays.categorical import Categorical import pandas.core.common as com -from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.frame import DataFrame from pandas.core.groupby import base from pandas.core.groupby.groupby import ( @@ -295,9 +294,7 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) # result is a dict whose keys are the elements of result_index index = self.grouper.result_index - return create_series_with_explicit_dtype( - result, index=index, dtype_if_empty=object - ) + return Series(result, index=index) agg = aggregate @@ -1294,10 +1291,8 @@ def _wrap_applied_output_series( key_index, override_group_keys: bool, ) -> DataFrame | Series: - # this is to silence a DeprecationWarning - # TODO(2.0): Remove when default dtype of empty Series is object kwargs = first_not_none._construct_axes_dict() - backup = create_series_with_explicit_dtype(dtype_if_empty=object, **kwargs) + backup = Series(**kwargs) values = [x if (x is not None) else backup for x in values] all_indexed_same = all_indexes_same(x.index for x in values) diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index ee7026663b2b6..0b42a4a3cd0c1 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -601,7 +601,7 @@ def _homogenize(data, index: Index, dtype: DtypeObj | None) -> list[ArrayLike]: else: if isinstance(val, dict): # GH#41785 this _should_ be equivalent to (but faster than) - # val = create_series_with_explicit_dtype(val, index=index)._values + # val = Series(val, index=index)._values if oindex is None: oindex = index.astype("O") diff --git a/pandas/core/series.py b/pandas/core/series.py index 9bfb2a0561532..9fe5cd0e4da9a 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -119,9 +119,7 @@ from pandas.core.arrays.categorical import CategoricalAccessor from pandas.core.arrays.sparse import SparseAccessor from pandas.core.construction import ( - create_series_with_explicit_dtype, extract_array, - is_empty_data, sanitize_array, ) from pandas.core.generic import NDFrame @@ -389,18 +387,6 @@ def __init__( name = ibase.maybe_extract_name(name, data, type(self)) - if is_empty_data(data) and dtype is None: - # gh-17261 - warnings.warn( - "The default dtype for empty Series will be 'object' instead " - "of 'float64' in a future version. Specify a dtype explicitly " - "to silence this warning.", - FutureWarning, - stacklevel=find_stack_level(), - ) - # uncomment the line below when removing the FutureWarning - # dtype = np.dtype(object) - if index is not None: index = ensure_index(index) @@ -458,6 +444,9 @@ def __init__( pass else: data = com.maybe_iterable_to_list(data) + if is_list_like(data) and not len(data) and dtype is None: + # GH 29405: Pre-2.0, this defaulted to float. + dtype = np.dtype(object) if index is None: if not is_list_like(data): @@ -531,15 +520,10 @@ def _init_dict( # Input is now list-like, so rely on "standard" construction: - # TODO: passing np.float64 to not break anything yet. See GH-17261 - s = create_series_with_explicit_dtype( - # error: Argument "index" to "create_series_with_explicit_dtype" has - # incompatible type "Tuple[Any, ...]"; expected "Union[ExtensionArray, - # ndarray, Index, None]" + s = self._constructor( values, - index=keys, # type: ignore[arg-type] + index=keys, dtype=dtype, - dtype_if_empty=np.float64, ) # Now we just make sure the order is respected, if any diff --git a/pandas/io/html.py b/pandas/io/html.py index a08b73d94250b..67c120a30280c 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -32,9 +32,9 @@ from pandas.core.dtypes.common import is_list_like from pandas import isna -from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.indexes.base import Index from pandas.core.indexes.multi import MultiIndex +from pandas.core.series import Series from pandas.io.common import ( file_exists, @@ -858,7 +858,7 @@ def _parse_tfoot_tr(self, table): def _expand_elements(body) -> None: data = [len(elem) for elem in body] - lens = create_series_with_explicit_dtype(data, dtype_if_empty=object) + lens = Series(data) lens_max = lens.max() not_max = lens[lens != lens_max] diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index 15e7da1b8525e..43de9093587a7 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -49,7 +49,6 @@ notna, to_datetime, ) -from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.reshape.concat import concat from pandas.core.shared_docs import _shared_docs @@ -1221,9 +1220,9 @@ def _parse(self) -> None: if self.orient == "split": decoded = {str(k): v for k, v in data.items()} self.check_keys_split(decoded) - self.obj = create_series_with_explicit_dtype(**decoded) + self.obj = Series(**decoded) else: - self.obj = create_series_with_explicit_dtype(data, dtype_if_empty=object) + self.obj = Series(data) def _try_convert_types(self) -> None: if self.obj is None: diff --git a/pandas/tests/frame/constructors/test_from_dict.py b/pandas/tests/frame/constructors/test_from_dict.py index 7c2b009673bb7..6cba95e42463d 100644 --- a/pandas/tests/frame/constructors/test_from_dict.py +++ b/pandas/tests/frame/constructors/test_from_dict.py @@ -10,7 +10,6 @@ Series, ) import pandas._testing as tm -from pandas.core.construction import create_series_with_explicit_dtype class TestFromDict: @@ -79,9 +78,7 @@ def test_constructor_list_of_series(self): OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]), OrderedDict([["b", 3], ["c", 4], ["d", 6]]), ] - data = [ - create_series_with_explicit_dtype(d, dtype_if_empty=object) for d in data - ] + data = [Series(d) for d in data] result = DataFrame(data) sdict = OrderedDict(zip(range(len(data)), data)) diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index d15199e84f7ac..ea526c95f20e0 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -30,7 +30,6 @@ ) import pandas._testing as tm from pandas.core.arrays import SparseArray -from pandas.core.construction import create_series_with_explicit_dtype from pandas.tests.extension.decimal import to_decimal @@ -519,7 +518,7 @@ def test_concat_no_unnecessary_upcast(dt, frame_or_series): assert x.values.dtype == dt -@pytest.mark.parametrize("pdt", [create_series_with_explicit_dtype, DataFrame]) +@pytest.mark.parametrize("pdt", [Series, DataFrame]) @pytest.mark.parametrize("dt", np.sctypes["int"]) def test_concat_will_upcast(dt, pdt): with catch_warnings(record=True): diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index 9b57f0f634a6c..462de7e28d42b 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -106,8 +106,7 @@ def test_astype_empty_constructor_equality(self, dtype): "m", # Generic timestamps raise a ValueError. Already tested. ): init_empty = Series([], dtype=dtype) - with tm.assert_produces_warning(FutureWarning): - as_type_empty = Series([]).astype(dtype) + as_type_empty = Series([]).astype(dtype) tm.assert_series_equal(init_empty, as_type_empty) @pytest.mark.parametrize("dtype", [str, np.str_]) diff --git a/pandas/tests/series/methods/test_is_unique.py b/pandas/tests/series/methods/test_is_unique.py index 960057cb3d646..db77f77467b42 100644 --- a/pandas/tests/series/methods/test_is_unique.py +++ b/pandas/tests/series/methods/test_is_unique.py @@ -2,7 +2,6 @@ import pytest from pandas import Series -from pandas.core.construction import create_series_with_explicit_dtype @pytest.mark.parametrize( @@ -19,7 +18,7 @@ ) def test_is_unique(data, expected): # GH#11946 / GH#25180 - ser = create_series_with_explicit_dtype(data, dtype_if_empty=object) + ser = Series(data) assert ser.is_unique is expected diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index 77c9cf4013bd7..5850cd2907675 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -309,8 +309,7 @@ def test_replace_with_empty_dictlike(self): s = pd.Series(list("abcd")) tm.assert_series_equal(s, s.replace({})) - with tm.assert_produces_warning(FutureWarning): - empty_series = pd.Series([]) + empty_series = pd.Series([]) tm.assert_series_equal(s, s.replace(empty_series)) def test_replace_string_with_number(self): diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 9817c758759d5..e75d5d8dd9638 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -74,9 +74,8 @@ class TestSeriesConstructors: ) def test_empty_constructor(self, constructor, check_index_type): # TODO: share with frame test of the same name - with tm.assert_produces_warning(FutureWarning): - expected = Series() - result = constructor() + expected = Series() + result = constructor() assert len(result.index) == 0 tm.assert_series_equal(result, expected, check_index_type=check_index_type) @@ -119,8 +118,7 @@ def test_scalar_extension_dtype(self, ea_scalar_and_dtype): tm.assert_series_equal(ser, expected) def test_constructor(self, datetime_series): - with tm.assert_produces_warning(FutureWarning): - empty_series = Series() + empty_series = Series() assert datetime_series.index._is_all_dates # Pass in Series @@ -137,8 +135,7 @@ def test_constructor(self, datetime_series): assert mixed[1] is np.NaN assert not empty_series.index._is_all_dates - with tm.assert_produces_warning(FutureWarning): - assert not Series().index._is_all_dates + assert not Series().index._is_all_dates # exception raised is of type ValueError GH35744 with pytest.raises(ValueError, match="Data must be 1-dimensional"): @@ -163,9 +160,8 @@ def test_constructor_index_ndim_gt_1_raises(self): @pytest.mark.parametrize("input_class", [list, dict, OrderedDict]) def test_constructor_empty(self, input_class): - with tm.assert_produces_warning(FutureWarning): - empty = Series() - empty2 = Series(input_class()) + empty = Series() + empty2 = Series(input_class()) # these are Index() and RangeIndex() which don't compare type equal # but are just .equals @@ -183,9 +179,8 @@ def test_constructor_empty(self, input_class): if input_class is not list: # With index: - with tm.assert_produces_warning(FutureWarning): - empty = Series(index=range(10)) - empty2 = Series(input_class(), index=range(10)) + empty = Series(index=range(10)) + empty2 = Series(input_class(), index=range(10)) tm.assert_series_equal(empty, empty2) # With index and dtype float64: @@ -217,8 +212,7 @@ def test_constructor_dtype_only(self, dtype, index): assert len(result) == 0 def test_constructor_no_data_index_order(self): - with tm.assert_produces_warning(FutureWarning): - result = Series(index=["b", "a", "c"]) + result = Series(index=["b", "a", "c"]) assert result.index.tolist() == ["b", "a", "c"] def test_constructor_no_data_string_type(self): @@ -696,8 +690,7 @@ def test_constructor_limit_copies(self, index): assert s._mgr.blocks[0].values is not index def test_constructor_pass_none(self): - with tm.assert_produces_warning(FutureWarning): - s = Series(None, index=range(5)) + s = Series(None, index=range(5)) assert s.dtype == np.float64 s = Series(None, index=range(5), dtype=object) @@ -705,9 +698,8 @@ def test_constructor_pass_none(self): # GH 7431 # inference on the index - with tm.assert_produces_warning(FutureWarning): - s = Series(index=np.array([None])) - expected = Series(index=Index([None])) + s = Series(index=np.array([None])) + expected = Series(index=Index([None])) tm.assert_series_equal(s, expected) def test_constructor_pass_nan_nat(self): diff --git a/pandas/tests/series/test_subclass.py b/pandas/tests/series/test_subclass.py index fd6f4e0083b08..a5620de7de65b 100644 --- a/pandas/tests/series/test_subclass.py +++ b/pandas/tests/series/test_subclass.py @@ -35,8 +35,7 @@ def test_subclass_unstack(self): tm.assert_frame_equal(res, exp) def test_subclass_empty_repr(self): - with tm.assert_produces_warning(FutureWarning): - sub_series = tm.SubclassedSeries() + sub_series = tm.SubclassedSeries() assert "SubclassedSeries" in repr(sub_series) def test_asof(self):
Introduced in #29405
https://api.github.com/repos/pandas-dev/pandas/pulls/49342
2022-10-26T21:19:10Z
2022-10-31T21:46:53Z
2022-10-31T21:46:53Z
2022-10-31T21:46:57Z
STYLE: fix pylint simplifiable-if-expression warnings
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index b3650173e41ef..980e8b4936c4e 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -133,7 +133,7 @@ def _cat_compare_op(op): opname = f"__{op.__name__}__" - fill_value = True if op is operator.ne else False + fill_value = op is operator.ne @unpack_zerodim_and_defer(opname) def func(self, other): diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 9e5437a084695..fb308fd8ba620 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -1002,7 +1002,7 @@ def mean(self, *args, update=None, update_times=None, **kwargs): 1 0.75 5.75 """ result_kwargs = {} - is_frame = True if self._selected_obj.ndim == 2 else False + is_frame = self._selected_obj.ndim == 2 if update_times is not None: raise NotImplementedError("update_times is not implemented.") else: diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 0e7174c6ad765..f3c58ac2ad18d 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -2958,10 +2958,7 @@ def hide( setattr( self, f"hide_{objs}_", - [ - True if lev in levels_ else False - for lev in range(getattr(self, objs).nlevels) - ], + [lev in levels_ for lev in range(getattr(self, objs).nlevels)], ) else: if axis == 0: diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py index d917a3c79aa97..6abd54db3bf4a 100644 --- a/pandas/tests/copy_view/test_indexing.py +++ b/pandas/tests/copy_view/test_indexing.py @@ -339,10 +339,9 @@ def test_subset_set_column_with_loc(using_copy_on_write, using_array_manager, dt with pd.option_context("chained_assignment", "warn"): # The (i)loc[:, col] inplace deprecation gets triggered here, ignore those # warnings and only assert the SettingWithCopyWarning - raise_on_extra_warnings = False if using_array_manager else True with tm.assert_produces_warning( SettingWithCopyWarning, - raise_on_extra_warnings=raise_on_extra_warnings, + raise_on_extra_warnings=not using_array_manager, ): subset.loc[:, "a"] = np.array([10, 11], dtype="int64") @@ -376,10 +375,9 @@ def test_subset_set_column_with_loc2(using_copy_on_write, using_array_manager): with pd.option_context("chained_assignment", "warn"): # The (i)loc[:, col] inplace deprecation gets triggered here, ignore those # warnings and only assert the SettingWithCopyWarning - raise_on_extra_warnings = False if using_array_manager else True with tm.assert_produces_warning( SettingWithCopyWarning, - raise_on_extra_warnings=raise_on_extra_warnings, + raise_on_extra_warnings=not using_array_manager, ): subset.loc[:, "a"] = 0 diff --git a/pyproject.toml b/pyproject.toml index b6c657dfd8b15..b38a3f3de21c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -124,7 +124,6 @@ disable = [ "no-else-return", "no-self-use", "redefined-argument-from-local", - "simplifiable-if-expression", "too-few-public-methods", "too-many-ancestors", "too-many-arguments",
Related to https://github.com/pandas-dev/pandas/issues/48855 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49339
2022-10-26T18:02:38Z
2022-10-26T22:38:58Z
2022-10-26T22:38:58Z
2022-10-27T13:32:39Z
STYLE fix: pylint "consider-using-from"
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index b30e0ff8b099e..4af2caf0cdb93 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -74,7 +74,7 @@ from pandas._libs.util cimport ( UINT64_MAX, ) -import pandas._libs.lib as lib +from pandas._libs import lib from pandas._libs.khash cimport ( kh_destroy_float64, diff --git a/pandas/conftest.py b/pandas/conftest.py index 825aa4b51ebaa..61915b4070945 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1727,7 +1727,7 @@ def any_skipna_inferred_dtype(request): Examples -------- - >>> import pandas._libs.lib as lib + >>> from pandas._libs import lib >>> >>> def test_something(any_skipna_inferred_dtype): ... inferred_dtype, values = any_skipna_inferred_dtype diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 980e8b4936c4e..80933a3611e73 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -87,6 +87,7 @@ ) from pandas.core import ( + algorithms, arraylike, ops, ) @@ -94,7 +95,6 @@ PandasDelegate, delegate_names, ) -import pandas.core.algorithms as algorithms from pandas.core.algorithms import ( factorize, take_nd, diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 38d3e0d73ef2c..88e94b3c93e5c 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -78,7 +78,10 @@ notna, ) -from pandas.core import arraylike +from pandas.core import ( + arraylike, + ops, +) import pandas.core.algorithms as algos from pandas.core.array_algos.quantile import quantile_with_mask from pandas.core.arraylike import OpsMixin @@ -96,9 +99,8 @@ ) from pandas.core.missing import interpolate_2d from pandas.core.nanops import check_below_min_count -import pandas.core.ops as ops -import pandas.io.formats.printing as printing +from pandas.io.formats import printing # See https://github.com/python/typing/issues/684 if TYPE_CHECKING: diff --git a/pandas/core/base.py b/pandas/core/base.py index 4b147dc619692..3bf228cc9d8f0 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -21,7 +21,7 @@ import numpy as np -import pandas._libs.lib as lib +from pandas._libs import lib from pandas._typing import ( Axis, AxisInt, diff --git a/pandas/core/computation/engines.py b/pandas/core/computation/engines.py index 2ea5a5367611f..833bc3143b968 100644 --- a/pandas/core/computation/engines.py +++ b/pandas/core/computation/engines.py @@ -17,7 +17,7 @@ REDUCTIONS, ) -import pandas.io.formats.printing as printing +from pandas.io.formats import printing if TYPE_CHECKING: from pandas.core.computation.expr import Expr diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index c91cfd65e3c40..e7474ea5dd9f8 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -44,7 +44,7 @@ ) from pandas.core.computation.scope import Scope -import pandas.io.formats.printing as printing +from pandas.io.formats import printing def _rewrite_assign(tok: tuple[int, str]) -> tuple[int, str]: diff --git a/pandas/core/construction.py b/pandas/core/construction.py index c381496164630..4ceafa6d4462e 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -18,7 +18,7 @@ import warnings import numpy as np -import numpy.ma as ma +from numpy import ma from pandas._libs import lib from pandas._libs.tslibs.period import Period diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2809aa9eaa37d..cb38648d81135 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -33,7 +33,7 @@ import warnings import numpy as np -import numpy.ma as ma +from numpy import ma from pandas._config import get_option @@ -685,7 +685,7 @@ def __init__( # GH#38939 de facto copy defaults to False only in non-dict cases mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager) elif isinstance(data, ma.MaskedArray): - import numpy.ma.mrecords as mrecords + from numpy.ma import mrecords # masked recarray if isinstance(data, mrecords.MaskedRecords): @@ -8036,7 +8036,7 @@ def combine_first(self, other: DataFrame) -> DataFrame: 1 0.0 3.0 1.0 2 NaN 3.0 1.0 """ - import pandas.core.computation.expressions as expressions + from pandas.core.computation import expressions def combiner(x, y): mask = extract_array(isna(x)) @@ -8179,7 +8179,7 @@ def update( 1 2 500.0 2 3 6.0 """ - import pandas.core.computation.expressions as expressions + from pandas.core.computation import expressions # TODO: Support other joins if join != "left": # pragma: no cover diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index a0f83e13c4ece..369fd37bf3a92 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -88,9 +88,12 @@ class providing the base-class of operations. notna, ) -from pandas.core import nanops +from pandas.core import ( + algorithms, + nanops, + sample, +) from pandas.core._numba import executor -import pandas.core.algorithms as algorithms from pandas.core.arrays import ( BaseMaskedArray, BooleanArray, @@ -121,7 +124,6 @@ class providing the base-class of operations. RangeIndex, ) from pandas.core.internals.blocks import ensure_block_shape -import pandas.core.sample as sample from pandas.core.series import Series from pandas.core.sorting import get_group_index_sorter from pandas.core.util.numba_ import ( diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 7ae6495f15541..7110c74e34473 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -31,7 +31,7 @@ is_scalar, ) -import pandas.core.algorithms as algorithms +from pandas.core import algorithms from pandas.core.arrays import ( Categorical, ExtensionArray, diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 83c1ca0084724..6a0b95489ef5c 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -77,6 +77,7 @@ na_value_for_dtype, ) +from pandas.core import missing import pandas.core.algorithms as algos from pandas.core.array_algos.putmask import ( extract_bool_array, @@ -104,13 +105,12 @@ from pandas.core.arrays.sparse import SparseDtype from pandas.core.base import PandasObject import pandas.core.common as com -import pandas.core.computation.expressions as expressions +from pandas.core.computation import expressions from pandas.core.construction import ( ensure_wrapped_if_datetimelike, extract_array, ) from pandas.core.indexers import check_setitem_lengths -import pandas.core.missing as missing if TYPE_CHECKING: from pandas import ( diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index ee7026663b2b6..861e0798f37f9 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -15,7 +15,7 @@ import warnings import numpy as np -import numpy.ma as ma +from numpy import ma from pandas._libs import lib from pandas._typing import ( diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 326e6c4251152..50ebf5c2032be 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -519,12 +519,12 @@ def nanany( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, 2]) >>> nanops.nanany(s) True - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([np.nan]) >>> nanops.nanany(s) False @@ -565,12 +565,12 @@ def nanall( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, 2, np.nan]) >>> nanops.nanall(s) True - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, 0]) >>> nanops.nanall(s) False @@ -616,7 +616,7 @@ def nansum( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, 2, np.nan]) >>> nanops.nansum(s) 3.0 @@ -684,7 +684,7 @@ def nanmean( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, 2, np.nan]) >>> nanops.nanmean(s) 1.5 @@ -740,7 +740,7 @@ def nanmedian(values, *, axis: AxisInt | None = None, skipna: bool = True, mask= Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, np.nan, 2, 2]) >>> nanops.nanmedian(s) 2.0 @@ -901,7 +901,7 @@ def nanstd( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, np.nan, 2, 3]) >>> nanops.nanstd(s) 1.0 @@ -948,7 +948,7 @@ def nanvar( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, np.nan, 2, 3]) >>> nanops.nanvar(s) 1.0 @@ -1023,7 +1023,7 @@ def nansem( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, np.nan, 2, 3]) >>> nanops.nansem(s) 0.5773502691896258 @@ -1100,7 +1100,7 @@ def nanargmax( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> arr = np.array([1, 2, 3, np.nan, 4]) >>> nanops.nanargmax(arr) 4 @@ -1146,7 +1146,7 @@ def nanargmin( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> arr = np.array([1, 2, 3, np.nan, 4]) >>> nanops.nanargmin(arr) 0 @@ -1200,7 +1200,7 @@ def nanskew( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, np.nan, 1, 2]) >>> nanops.nanskew(s) 1.7320508075688787 @@ -1288,7 +1288,7 @@ def nankurt( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, np.nan, 1, 3, 2]) >>> nanops.nankurt(s) -1.2892561983471076 @@ -1380,7 +1380,7 @@ def nanprod( Examples -------- - >>> import pandas.core.nanops as nanops + >>> from pandas.core import nanops >>> s = pd.Series([1, 2, 3, np.nan]) >>> nanops.nanprod(s) 6.0 diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py index 6a1c586d90b6e..4a3707bbf1070 100644 --- a/pandas/core/ops/array_ops.py +++ b/pandas/core/ops/array_ops.py @@ -47,7 +47,7 @@ notna, ) -import pandas.core.computation.expressions as expressions +from pandas.core.computation import expressions from pandas.core.construction import ensure_wrapped_if_datetimelike from pandas.core.ops import ( missing, diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 94705790e40bd..3372fa64d86fe 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -43,8 +43,8 @@ to_datetime, to_timedelta, ) +from pandas.core import nanops import pandas.core.algorithms as algos -import pandas.core.nanops as nanops def cut( diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index ff9c72b74e5eb..0888fa6985560 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -14,7 +14,7 @@ import numpy as np -import pandas._libs.lib as lib +from pandas._libs import lib from pandas._typing import ( AlignJoin, DtypeObj, diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index 3e8cdc12e7216..d45cfa8de6f3e 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -11,7 +11,7 @@ import numpy as np -import pandas._libs.lib as lib +from pandas._libs import lib import pandas._libs.missing as libmissing import pandas._libs.ops as libops from pandas._typing import ( diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index fb308fd8ba620..a5ee93aded420 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -27,7 +27,7 @@ ) from pandas.core.dtypes.missing import isna -import pandas.core.common as common # noqa: PDF018 +from pandas.core import common # noqa: PDF018 from pandas.core.indexers.objects import ( BaseIndexer, ExponentialMovingWindowIndexer, diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py index 5603c601e2c45..7c90178226408 100644 --- a/pandas/io/excel/_odswriter.py +++ b/pandas/io/excel/_odswriter.py @@ -10,7 +10,7 @@ cast, ) -import pandas._libs.json as json +from pandas._libs import json from pandas._typing import ( FilePath, StorageOptions, diff --git a/pandas/io/excel/_xlsxwriter.py b/pandas/io/excel/_xlsxwriter.py index 8d11896cb7374..dd583c41a90d0 100644 --- a/pandas/io/excel/_xlsxwriter.py +++ b/pandas/io/excel/_xlsxwriter.py @@ -5,7 +5,7 @@ Any, ) -import pandas._libs.json as json +from pandas._libs import json from pandas._typing import ( FilePath, StorageOptions, diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index 15e7da1b8525e..67c81db8d3a8f 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -21,7 +21,7 @@ import numpy as np -import pandas._libs.json as json +from pandas._libs import json from pandas._libs.tslibs import iNaT from pandas._typing import ( CompressionOptions, diff --git a/pandas/io/json/_table_schema.py b/pandas/io/json/_table_schema.py index 0d6cab20f2a59..e1b8388788143 100644 --- a/pandas/io/json/_table_schema.py +++ b/pandas/io/json/_table_schema.py @@ -12,7 +12,7 @@ ) import warnings -import pandas._libs.json as json +from pandas._libs import json from pandas._typing import ( DtypeObj, JSONSerializable, diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index 5b54ac56d48c8..63c7e8047407d 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -26,9 +26,11 @@ import numpy as np -import pandas._libs.lib as lib +from pandas._libs import ( + lib, + parsers, +) import pandas._libs.ops as libops -import pandas._libs.parsers as parsers from pandas._libs.parsers import STR_NA_VALUES from pandas._libs.tslibs import parsing from pandas._typing import ( diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py index 106f4df4370b3..8ce671bcb03a2 100644 --- a/pandas/io/parsers/c_parser_wrapper.py +++ b/pandas/io/parsers/c_parser_wrapper.py @@ -11,7 +11,7 @@ import numpy as np -import pandas._libs.parsers as parsers +from pandas._libs import parsers from pandas._typing import ( ArrayLike, DtypeArg, diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index ddd73375f8871..4f15443ed5610 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -24,7 +24,7 @@ import numpy as np -import pandas._libs.lib as lib +from pandas._libs import lib from pandas._typing import ( ArrayLike, ReadCsvBuffer, diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index abd1182214f5f..e043afd404ee9 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -22,7 +22,7 @@ import numpy as np -import pandas._libs.lib as lib +from pandas._libs import lib from pandas._libs.parsers import STR_NA_VALUES from pandas._typing import ( CompressionOptions, diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 0f24e3f31cc4b..8bcee36cbef2b 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -25,7 +25,7 @@ import numpy as np -import pandas._libs.lib as lib +from pandas._libs import lib from pandas._typing import ( DateTimeErrorChoices, DtypeArg, diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index 4d5feafb5ebd2..28279ff4ee710 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -17,14 +17,16 @@ ) from dateutil.relativedelta import relativedelta -import matplotlib.dates as dates +from matplotlib import ( + dates, + units, +) from matplotlib.ticker import ( AutoLocator, Formatter, Locator, ) from matplotlib.transforms import nonsingular -import matplotlib.units as units import numpy as np from pandas._libs import lib diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index 633cb63664823..b18264c655903 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -6,8 +6,8 @@ Hashable, ) +from matplotlib import patches import matplotlib.lines as mlines -import matplotlib.patches as patches import numpy as np from pandas.core.dtypes.missing import notna diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index 2878f4dbf279c..f060255c4e9c5 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -10,7 +10,7 @@ import warnings import matplotlib as mpl -import matplotlib.cm as cm +from matplotlib import cm import matplotlib.colors import numpy as np diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index d3c16a6d53916..1749c05a555a1 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -9,8 +9,8 @@ ) import warnings +from matplotlib import ticker import matplotlib.table -import matplotlib.ticker as ticker import numpy as np from pandas.util._exceptions import find_stack_level diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py index 5b9780e390775..092cbc6c7997f 100644 --- a/pandas/tests/arrays/integer/test_arithmetic.py +++ b/pandas/tests/arrays/integer/test_arithmetic.py @@ -5,8 +5,8 @@ import pandas as pd import pandas._testing as tm +from pandas.core import ops from pandas.core.arrays import FloatingArray -import pandas.core.ops as ops # Basic test for the arithmetic array ops # ----------------------------------------------------------------------------- diff --git a/pandas/tests/computation/test_compat.py b/pandas/tests/computation/test_compat.py index cfc08426f84e3..f3566e040dc85 100644 --- a/pandas/tests/computation/test_compat.py +++ b/pandas/tests/computation/test_compat.py @@ -3,8 +3,8 @@ from pandas.compat._optional import VERSIONS import pandas as pd +from pandas.core.computation import expr from pandas.core.computation.engines import ENGINES -import pandas.core.computation.expr as expr from pandas.util.version import Version diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 7fce4e9d9c38e..b0a182ffe4933 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -30,9 +30,11 @@ date_range, ) import pandas._testing as tm -from pandas.core.computation import pytables +from pandas.core.computation import ( + expr, + pytables, +) from pandas.core.computation.engines import ENGINES -import pandas.core.computation.expr as expr from pandas.core.computation.expr import ( BaseExprVisitor, PandasExprVisitor, diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 10b1f8406025a..5a83c4997b33c 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -14,8 +14,8 @@ import warnings import numpy as np -import numpy.ma as ma -import numpy.ma.mrecords as mrecords +from numpy import ma +from numpy.ma import mrecords import pytest import pytz diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 963ed24cb434b..de2b062e427e7 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -28,8 +28,10 @@ to_timedelta, ) import pandas._testing as tm -import pandas.core.algorithms as algorithms -import pandas.core.nanops as nanops +from pandas.core import ( + algorithms, + nanops, +) def assert_stat_op_calc( diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 2b583431dcd71..7a9d540ae08c4 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -17,7 +17,7 @@ date_range, ) import pandas._testing as tm -import pandas.core.nanops as nanops +from pandas.core import nanops from pandas.tests.groupby import get_groupby_method_args from pandas.util import _test_decorators as td diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index b3e2e81e95613..6ab45de35fecf 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -45,8 +45,8 @@ ) import pandas._testing as tm +from pandas.io.formats import printing import pandas.io.formats.format as fmt -import pandas.io.formats.printing as printing use_32bit_repr = is_platform_windows() or not IS64 diff --git a/pandas/tests/io/formats/test_printing.py b/pandas/tests/io/formats/test_printing.py index 4fc8a46bad777..5ab7ff085f539 100644 --- a/pandas/tests/io/formats/test_printing.py +++ b/pandas/tests/io/formats/test_printing.py @@ -5,8 +5,8 @@ import pandas as pd +from pandas.io.formats import printing import pandas.io.formats.format as fmt -import pandas.io.formats.printing as printing def test_adjoin(): diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 9adada8afb2c2..e1811114107c8 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -55,7 +55,7 @@ ) import pandas._testing as tm -import pandas.io.sql as sql +from pandas.io import sql from pandas.io.sql import ( SQLAlchemyEngine, SQLDatabase, diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index 55a5473ce7d0f..6567504894236 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -47,7 +47,7 @@ def plt(self): @cache_readonly def colorconverter(self): - import matplotlib.colors as colors + from matplotlib import colors return colors.colorConverter diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index 455bc177d43e2..476f0a89980ea 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -22,6 +22,7 @@ Series, bdate_range, date_range, + plotting, ) import pandas._testing as tm from pandas.tests.plotting.common import ( @@ -30,7 +31,6 @@ ) from pandas.io.formats.printing import pprint_thing -import pandas.plotting as plotting try: from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 @@ -1833,7 +1833,7 @@ def test_memory_leak(self): def test_df_gridspec_patterns(self): # GH 10819 - import matplotlib.gridspec as gridspec + from matplotlib import gridspec import matplotlib.pyplot as plt ts = Series(np.random.randn(10), index=date_range("1/1/2000", periods=10)) diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 9112d5cb3368f..ab7b2855768db 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -13,6 +13,7 @@ MultiIndex, Series, date_range, + plotting, timedelta_range, ) import pandas._testing as tm @@ -22,7 +23,6 @@ ) from pandas.io.formats.printing import pprint_thing -import pandas.plotting as plotting @td.skip_if_no_mpl diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 93da7f71f51f9..67486ec2a17b6 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -11,6 +11,7 @@ Series, Timestamp, interval_range, + plotting, ) import pandas._testing as tm from pandas.tests.plotting.common import ( @@ -18,8 +19,6 @@ _check_plot_works, ) -import pandas.plotting as plotting - @td.skip_if_mpl def test_import_error_message(): diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 816ce95dbb83a..d8004ad563196 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -12,6 +12,7 @@ DataFrame, Series, date_range, + plotting, ) import pandas._testing as tm from pandas.tests.plotting.common import ( @@ -19,8 +20,6 @@ _check_plot_works, ) -import pandas.plotting as plotting - try: from pandas.plotting._matplotlib.compat import mpl_ge_3_6_0 except ImportError: @@ -652,7 +651,7 @@ def test_standard_colors(self, c): assert result == [c] * 3 def test_standard_colors_all(self): - import matplotlib.colors as colors + from matplotlib import colors from pandas.plotting._matplotlib.style import get_standard_colors diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index e82ffdfef7b15..769fd2d4a05eb 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -32,7 +32,7 @@ _get_timestamp_range_edges, ) -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets from pandas.tseries.offsets import Minute diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index 4da1f4c589c56..91804b5833465 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -27,7 +27,7 @@ ) from pandas.core.resample import _get_period_range_edges -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets @pytest.fixture() diff --git a/pandas/tests/series/methods/test_cov_corr.py b/pandas/tests/series/methods/test_cov_corr.py index 58a332ace244f..be3483c773143 100644 --- a/pandas/tests/series/methods/test_cov_corr.py +++ b/pandas/tests/series/methods/test_cov_corr.py @@ -58,7 +58,7 @@ def test_cov_ddof(self, test_ddof): class TestSeriesCorr: @td.skip_if_no_scipy def test_corr(self, datetime_series): - import scipy.stats as stats + from scipy import stats # full overlap tm.assert_almost_equal(datetime_series.corr(datetime_series), 1) @@ -88,7 +88,7 @@ def test_corr(self, datetime_series): @td.skip_if_no_scipy def test_corr_rank(self): - import scipy.stats as stats + from scipy import stats # kendall and spearman A = tm.makeTimeSeries() diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 9817c758759d5..4a4b5bd3edc6c 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -7,7 +7,7 @@ from dateutil.tz import tzoffset import numpy as np -import numpy.ma as ma +from numpy import ma import pytest from pandas._libs import ( diff --git a/pandas/tests/strings/conftest.py b/pandas/tests/strings/conftest.py index 15cc5af97a2d6..1f87608a79f98 100644 --- a/pandas/tests/strings/conftest.py +++ b/pandas/tests/strings/conftest.py @@ -160,7 +160,7 @@ def any_allowed_skipna_inferred_dtype(request): Examples -------- - >>> import pandas._libs.lib as lib + >>> from pandas._libs import lib >>> >>> def test_something(any_allowed_skipna_inferred_dtype): ... inferred_dtype, values = any_allowed_skipna_inferred_dtype diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index 005ef6747da95..0e64181bd46a7 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -15,8 +15,8 @@ isna, ) import pandas._testing as tm +from pandas.core import nanops from pandas.core.arrays import DatetimeArray -import pandas.core.nanops as nanops use_bn = nanops._USE_BOTTLENECK diff --git a/pandas/tests/tseries/frequencies/test_inference.py b/pandas/tests/tseries/frequencies/test_inference.py index eebed6a4c27d3..60ede451ddd81 100644 --- a/pandas/tests/tseries/frequencies/test_inference.py +++ b/pandas/tests/tseries/frequencies/test_inference.py @@ -29,8 +29,10 @@ ) from pandas.core.tools.datetimes import to_datetime -import pandas.tseries.frequencies as frequencies -import pandas.tseries.offsets as offsets +from pandas.tseries import ( + frequencies, + offsets, +) @pytest.fixture( diff --git a/pandas/tests/tseries/offsets/conftest.py b/pandas/tests/tseries/offsets/conftest.py index b07771af4e1c1..c9c4d6c456c53 100644 --- a/pandas/tests/tseries/offsets/conftest.py +++ b/pandas/tests/tseries/offsets/conftest.py @@ -5,7 +5,7 @@ from pandas._libs.tslibs import Timestamp from pandas._libs.tslibs.offsets import MonthOffset -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets @pytest.fixture( diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index f1e511713d720..29b82f27234a5 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -40,7 +40,7 @@ import pandas._testing as tm from pandas.tests.tseries.offsets.common import WeekDay -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets from pandas.tseries.offsets import ( FY5253, BaseOffset, diff --git a/pandas/tests/util/test_util.py b/pandas/tests/util/test_util.py index b7ed9415ecb90..c68501e3ea260 100644 --- a/pandas/tests/util/test_util.py +++ b/pandas/tests/util/test_util.py @@ -2,8 +2,7 @@ import pytest -import pandas.compat as compat - +from pandas import compat import pandas._testing as tm diff --git a/pandas/tests/window/test_apply.py b/pandas/tests/window/test_apply.py index 12f9cb27e8cbe..b442c5a887503 100644 --- a/pandas/tests/window/test_apply.py +++ b/pandas/tests/window/test_apply.py @@ -16,7 +16,7 @@ ) import pandas._testing as tm -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets def f(x): diff --git a/pandas/tests/window/test_rolling_functions.py b/pandas/tests/window/test_rolling_functions.py index fc64c8efc8fcf..bb6faf4f4eb22 100644 --- a/pandas/tests/window/test_rolling_functions.py +++ b/pandas/tests/window/test_rolling_functions.py @@ -15,7 +15,7 @@ ) import pandas._testing as tm -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets @pytest.mark.parametrize( diff --git a/pandas/tests/window/test_rolling_quantile.py b/pandas/tests/window/test_rolling_quantile.py index 815ee419590f7..e78e997f220b5 100644 --- a/pandas/tests/window/test_rolling_quantile.py +++ b/pandas/tests/window/test_rolling_quantile.py @@ -12,7 +12,7 @@ ) import pandas._testing as tm -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets def scoreatpercentile(a, per): diff --git a/pandas/tests/window/test_rolling_skew_kurt.py b/pandas/tests/window/test_rolling_skew_kurt.py index 4489fada9c11e..8f162f376c863 100644 --- a/pandas/tests/window/test_rolling_skew_kurt.py +++ b/pandas/tests/window/test_rolling_skew_kurt.py @@ -14,7 +14,7 @@ ) import pandas._testing as tm -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets @td.skip_if_no_scipy diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py index eaa4181ac5df6..d04cdb3e46bc0 100644 --- a/pandas/tests/window/test_timeseries_window.py +++ b/pandas/tests/window/test_timeseries_window.py @@ -12,7 +12,7 @@ ) import pandas._testing as tm -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets @pytest.fixture diff --git a/pandas/tseries/api.py b/pandas/tseries/api.py index e274838d45b27..9fdf95d09fe52 100644 --- a/pandas/tseries/api.py +++ b/pandas/tseries/api.py @@ -2,7 +2,7 @@ Timeseries API """ +from pandas.tseries import offsets from pandas.tseries.frequencies import infer_freq -import pandas.tseries.offsets as offsets __all__ = ["infer_freq", "offsets"] diff --git a/pandas/util/_doctools.py b/pandas/util/_doctools.py index 80ec9724931bc..dc8a22b1fe0ef 100644 --- a/pandas/util/_doctools.py +++ b/pandas/util/_doctools.py @@ -55,7 +55,7 @@ def plot(self, left, right, labels: Iterable[str] = (), vertical: bool = True): vertical : bool, default True If True, use vertical layout. If False, use horizontal layout. """ - import matplotlib.gridspec as gridspec + from matplotlib import gridspec import matplotlib.pyplot as plt if not isinstance(left, list): @@ -141,7 +141,7 @@ def _make_table(self, ax, df, title: str, height: float | None = None) -> None: ax.set_visible(False) return - import pandas.plotting as plotting + from pandas import plotting idx_nlevels = df.index.nlevels col_nlevels = df.columns.nlevels diff --git a/pyproject.toml b/pyproject.toml index 63c2719b3b0fd..d035c4a70d1f7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -108,7 +108,6 @@ disable = [ "comparison-of-constants", "comparison-with-itself", "consider-merging-isinstance", - "consider-using-from-import", "consider-using-min-builtin", "consider-using-sys-exit", "consider-using-ternary",
Refers to one of the issues in https://github.com/pandas-dev/pandas/issues/48855 - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Fixed imports triggering pylints "consider using from" message
https://api.github.com/repos/pandas-dev/pandas/pulls/49335
2022-10-26T15:35:15Z
2022-10-28T18:52:43Z
2022-10-28T18:52:43Z
2022-10-28T18:52:52Z
STYLE: fix pylint consider-using-get warnings
diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index 5572116ca29fe..85f1e7fda8daa 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -139,8 +139,7 @@ def _convert_to_style_kwargs(cls, style_dict: dict) -> dict[str, Serialisable]: style_kwargs: dict[str, Serialisable] = {} for k, v in style_dict.items(): - if k in _style_key_map: - k = _style_key_map[k] + k = _style_key_map.get(k, k) _conv_to_x = getattr(cls, f"_convert_to_{k}", lambda x: None) new_v = _conv_to_x(v) if new_v: @@ -218,8 +217,7 @@ def _convert_to_font(cls, font_dict): font_kwargs = {} for k, v in font_dict.items(): - if k in _font_key_map: - k = _font_key_map[k] + k = _font_key_map.get(k, k) if k == "color": v = cls._convert_to_color(v) font_kwargs[k] = v @@ -288,11 +286,8 @@ def _convert_to_fill(cls, fill_dict: dict[str, Any]): pfill_kwargs = {} gfill_kwargs = {} for k, v in fill_dict.items(): - pk = gk = None - if k in _pattern_fill_key_map: - pk = _pattern_fill_key_map[k] - if k in _gradient_fill_key_map: - gk = _gradient_fill_key_map[k] + pk = _pattern_fill_key_map.get(k) + gk = _gradient_fill_key_map.get(k) if pk in ["start_color", "end_color"]: v = cls._convert_to_color(v) if gk == "stop": @@ -336,8 +331,7 @@ def _convert_to_side(cls, side_spec): side_kwargs = {} for k, v in side_spec.items(): - if k in _side_key_map: - k = _side_key_map[k] + k = _side_key_map.get(k, k) if k == "color": v = cls._convert_to_color(v) side_kwargs[k] = v @@ -375,8 +369,7 @@ def _convert_to_border(cls, border_dict): border_kwargs = {} for k, v in border_dict.items(): - if k in _border_key_map: - k = _border_key_map[k] + k = _border_key_map.get(k, k) if k == "color": v = cls._convert_to_color(v) if k in ["left", "right", "top", "bottom", "diagonal"]: diff --git a/pyproject.toml b/pyproject.toml index b38a3f3de21c6..63c2719b3b0fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -109,7 +109,6 @@ disable = [ "comparison-with-itself", "consider-merging-isinstance", "consider-using-from-import", - "consider-using-get", "consider-using-min-builtin", "consider-using-sys-exit", "consider-using-ternary",
- Related to https://github.com/pandas-dev/pandas/issues/48855 - [x] Resolves pylint: consider-using-get - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/49334
2022-10-26T14:42:32Z
2022-10-27T09:27:59Z
2022-10-27T09:27:59Z
2022-10-27T09:27:59Z
BUG: pandas.to_datetime() does not respect exact format string with ISO8601
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index d114d72633012..4577d20a509ce 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -644,6 +644,7 @@ Conversion - Bug in :meth:`Series.convert_dtypes` not converting dtype to nullable dtype when :class:`Series` contains ``NA`` and has dtype ``object`` (:issue:`48791`) - Bug where any :class:`ExtensionDtype` subclass with ``kind="M"`` would be interpreted as a timezone type (:issue:`34986`) - Bug in :class:`.arrays.ArrowExtensionArray` that would raise ``NotImplementedError`` when passed a sequence of strings or binary (:issue:`49172`) +- Bug in :func:`to_datetime` was not respecting ``exact`` argument when ``format`` was an ISO8601 format (:issue:`12649`) Strings ^^^^^^^ diff --git a/pandas/_libs/tslib.pyi b/pandas/_libs/tslib.pyi index f3a24a707c530..cc08b17e0ff5d 100644 --- a/pandas/_libs/tslib.pyi +++ b/pandas/_libs/tslib.pyi @@ -24,6 +24,8 @@ def array_to_datetime( yearfirst: bool = ..., utc: bool = ..., require_iso8601: bool = ..., + format: str | None = ..., + exact: bool = ..., ) -> tuple[np.ndarray, tzinfo | None]: ... # returned ndarray may be object dtype or datetime64[ns] diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 3104ecbc8bdb8..e01de6b70470e 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -446,6 +446,8 @@ cpdef array_to_datetime( bint yearfirst=False, bint utc=False, bint require_iso8601=False, + format: str | None=None, + bint exact=True, ): """ Converts a 1D array of date-like values to a numpy array of either: @@ -563,6 +565,16 @@ cpdef array_to_datetime( iresult[i] = get_datetime64_nanos(val, NPY_FR_ns) elif is_integer_object(val) or is_float_object(val): + if require_iso8601: + if is_coerce: + iresult[i] = NPY_NAT + continue + elif is_raise: + raise ValueError( + f"time data \"{val}\" at position {i} doesn't " + f"match format \"{format}\"" + ) + return values, tz_out # these must be ns unit by-definition seen_integer = True @@ -593,7 +605,7 @@ cpdef array_to_datetime( string_to_dts_failed = string_to_dts( val, &dts, &out_bestunit, &out_local, - &out_tzoffset, False + &out_tzoffset, False, format, exact ) if string_to_dts_failed: # An error at this point is a _parsing_ error @@ -609,7 +621,7 @@ cpdef array_to_datetime( elif is_raise: raise ValueError( f"time data \"{val}\" at position {i} doesn't " - "match format specified" + f"match format \"{format}\"" ) return values, tz_out diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd index e51bbd4e074e1..de81c611c9ee9 100644 --- a/pandas/_libs/tslibs/np_datetime.pxd +++ b/pandas/_libs/tslibs/np_datetime.pxd @@ -95,6 +95,8 @@ cdef int string_to_dts( int* out_local, int* out_tzoffset, bint want_exc, + format: str | None = *, + bint exact = * ) except? -1 cdef NPY_DATETIMEUNIT get_unit_from_dtype(cnp.dtype dtype) diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index b1ff456c84a70..d49c41e54764f 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -52,7 +52,8 @@ cdef extern from "src/datetime/np_datetime_strings.h": int parse_iso_8601_datetime(const char *str, int len, int want_exc, npy_datetimestruct *out, NPY_DATETIMEUNIT *out_bestunit, - int *out_local, int *out_tzoffset) + int *out_local, int *out_tzoffset, + const char *format, int format_len, int exact) # ---------------------------------------------------------------------- @@ -277,14 +278,25 @@ cdef inline int string_to_dts( int* out_local, int* out_tzoffset, bint want_exc, + format: str | None=None, + bint exact=True, ) except? -1: cdef: Py_ssize_t length const char* buf + Py_ssize_t format_length + const char* format_buf buf = get_c_string_buf_and_size(val, &length) + if format is None: + format_buf = b'' + format_length = 0 + exact = False + else: + format_buf = get_c_string_buf_and_size(format, &format_length) return parse_iso_8601_datetime(buf, length, want_exc, - dts, out_bestunit, out_local, out_tzoffset) + dts, out_bestunit, out_local, out_tzoffset, + format_buf, format_length, exact) cpdef ndarray astype_overflowsafe( diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime_strings.c b/pandas/_libs/tslibs/src/datetime/np_datetime_strings.c index cfbaed01b57c9..597a2aae7a2a3 100644 --- a/pandas/_libs/tslibs/src/datetime/np_datetime_strings.c +++ b/pandas/_libs/tslibs/src/datetime/np_datetime_strings.c @@ -66,10 +66,45 @@ This file implements string parsing and creation for NumPy datetime. * * Returns 0 on success, -1 on failure. */ + +// This function will advance the pointer on format +// and decrement characters_remaining by n on success +// On failure will return -1 without incrementing +static int compare_format(const char **format, int *characters_remaining, + const char *compare_to, int n, const int exact) { + if (*characters_remaining < n) { + if (exact) { + // TODO(pandas-dev): in the future we should set a PyErr here + // to be very clear about what went wrong + return -1; + } else if (*characters_remaining) { + // TODO(pandas-dev): same return value in this function as + // above branch, but stub out a future where + // we have a better error message + return -1; + } else { + return 0; + } + } else { + if (strncmp(*format, compare_to, n)) { + // TODO(pandas-dev): PyErr to differentiate what went wrong + return -1; + } else { + *format += n; + *characters_remaining -= n; + return 0; + } + } + return 0; +} + int parse_iso_8601_datetime(const char *str, int len, int want_exc, npy_datetimestruct *out, NPY_DATETIMEUNIT *out_bestunit, - int *out_local, int *out_tzoffset) { + int *out_local, int *out_tzoffset, + const char* format, int format_len, int exact) { + if (len < 0 || format_len < 0) + goto parse_error; int year_leap = 0; int i, numdigits; const char *substr; @@ -104,6 +139,9 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, while (sublen > 0 && isspace(*substr)) { ++substr; --sublen; + if (compare_format(&format, &format_len, " ", 1, exact)) { + goto parse_error; + } } /* Leading '-' sign for negative year */ @@ -117,6 +155,10 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, } /* PARSE THE YEAR (4 digits) */ + if (compare_format(&format, &format_len, "%Y", 2, exact)) { + goto parse_error; + } + out->year = 0; if (sublen >= 4 && isdigit(substr[0]) && isdigit(substr[1]) && isdigit(substr[2]) && isdigit(substr[3])) { @@ -139,6 +181,9 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, if (out_local != NULL) { *out_local = 0; } + if (format_len) { + goto parse_error; + } bestunit = NPY_FR_Y; goto finish; } @@ -156,6 +201,10 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, ymd_sep = valid_ymd_sep[i]; ++substr; --sublen; + + if (compare_format(&format, &format_len, &ymd_sep, 1, exact)) { + goto parse_error; + } /* Cannot have trailing separator */ if (sublen == 0 || !isdigit(*substr)) { goto parse_error; @@ -163,6 +212,9 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, } /* PARSE THE MONTH */ + if (compare_format(&format, &format_len, "%m", 2, exact)) { + goto parse_error; + } /* First digit required */ out->month = (*substr - '0'); ++substr; @@ -190,6 +242,9 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, if (!has_ymd_sep) { goto parse_error; } + if (format_len) { + goto parse_error; + } if (out_local != NULL) { *out_local = 0; } @@ -203,9 +258,15 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, } ++substr; --sublen; + if (compare_format(&format, &format_len, &ymd_sep, 1, exact)) { + goto parse_error; + } } /* PARSE THE DAY */ + if (compare_format(&format, &format_len, "%d", 2, exact)) { + goto parse_error; + } /* First digit required */ if (!isdigit(*substr)) { goto parse_error; @@ -235,6 +296,9 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, if (out_local != NULL) { *out_local = 0; } + if (format_len) { + goto parse_error; + } bestunit = NPY_FR_D; goto finish; } @@ -242,10 +306,16 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, if ((*substr != 'T' && *substr != ' ') || sublen == 1) { goto parse_error; } + if (compare_format(&format, &format_len, substr, 1, exact)) { + goto parse_error; + } ++substr; --sublen; /* PARSE THE HOURS */ + if (compare_format(&format, &format_len, "%H", 2, exact)) { + goto parse_error; + } /* First digit required */ if (!isdigit(*substr)) { goto parse_error; @@ -274,6 +344,9 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, if (!hour_was_2_digits) { goto parse_error; } + if (format_len) { + goto parse_error; + } bestunit = NPY_FR_h; goto finish; } @@ -286,6 +359,9 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, if (sublen == 0 || !isdigit(*substr)) { goto parse_error; } + if (compare_format(&format, &format_len, ":", 1, exact)) { + goto parse_error; + } } else if (!isdigit(*substr)) { if (!hour_was_2_digits) { goto parse_error; @@ -294,6 +370,9 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, } /* PARSE THE MINUTES */ + if (compare_format(&format, &format_len, "%M", 2, exact)) { + goto parse_error; + } /* First digit required */ out->min = (*substr - '0'); ++substr; @@ -317,12 +396,18 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, if (sublen == 0) { bestunit = NPY_FR_m; + if (format_len) { + goto parse_error; + } goto finish; } /* If we make it through this condition block, then the next * character is a digit. */ if (has_hms_sep && *substr == ':') { + if (compare_format(&format, &format_len, ":", 1, exact)) { + goto parse_error; + } ++substr; --sublen; /* Cannot have a trailing ':' */ @@ -335,6 +420,9 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, } /* PARSE THE SECONDS */ + if (compare_format(&format, &format_len, "%S", 2, exact)) { + goto parse_error; + } /* First digit required */ out->sec = (*substr - '0'); ++substr; @@ -360,12 +448,18 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, if (sublen > 0 && *substr == '.') { ++substr; --sublen; + if (compare_format(&format, &format_len, ".", 1, exact)) { + goto parse_error; + } } else { bestunit = NPY_FR_s; goto parse_timezone; } /* PARSE THE MICROSECONDS (0 to 6 digits) */ + if (compare_format(&format, &format_len, "%f", 2, exact)) { + goto parse_error; + } numdigits = 0; for (i = 0; i < 6; ++i) { out->us *= 10; @@ -430,15 +524,24 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, while (sublen > 0 && isspace(*substr)) { ++substr; --sublen; + if (compare_format(&format, &format_len, " ", 1, exact)) { + goto parse_error; + } } if (sublen == 0) { // Unlike NumPy, treating no time zone as naive + if (format_len > 0) { + goto parse_error; + } goto finish; } /* UTC specifier */ if (*substr == 'Z') { + if (compare_format(&format, &format_len, "%Z", 2, exact)) { + goto parse_error; + } /* "Z" should be equivalent to tz offset "+00:00" */ if (out_local != NULL) { *out_local = 1; @@ -449,12 +552,18 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, } if (sublen == 1) { + if (format_len > 0) { + goto parse_error; + } goto finish; } else { ++substr; --sublen; } } else if (*substr == '-' || *substr == '+') { + if (compare_format(&format, &format_len, "%z", 2, exact)) { + goto parse_error; + } /* Time zone offset */ int offset_neg = 0, offset_hour = 0, offset_minute = 0; @@ -538,9 +647,12 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, while (sublen > 0 && isspace(*substr)) { ++substr; --sublen; + if (compare_format(&format, &format_len, " ", 1, exact)) { + goto parse_error; + } } - if (sublen != 0) { + if ((sublen != 0) || (format_len != 0)) { goto parse_error; } diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime_strings.h b/pandas/_libs/tslibs/src/datetime/np_datetime_strings.h index 511d9a401fed2..734f7daceba05 100644 --- a/pandas/_libs/tslibs/src/datetime/np_datetime_strings.h +++ b/pandas/_libs/tslibs/src/datetime/np_datetime_strings.h @@ -58,7 +58,10 @@ parse_iso_8601_datetime(const char *str, int len, int want_exc, npy_datetimestruct *out, NPY_DATETIMEUNIT *out_bestunit, int *out_local, - int *out_tzoffset); + int *out_tzoffset, + const char* format, + int format_len, + int exact); /* * Provides a string length to use for converting datetime diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 64deba8a9d3ce..ed0a7df41c28d 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -2102,6 +2102,8 @@ def objects_to_datetime64ns( errors: DateTimeErrorChoices = "raise", require_iso8601: bool = False, allow_object: bool = False, + format: str | None = None, + exact: bool = True, ): """ Convert data to array of timestamps. @@ -2146,6 +2148,8 @@ def objects_to_datetime64ns( dayfirst=dayfirst, yearfirst=yearfirst, require_iso8601=require_iso8601, + format=format, + exact=exact, ) result = result.reshape(data.shape, order=order) except OverflowError as err: diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 4cd89d25995bb..9b59c9ea43e45 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -424,16 +424,14 @@ def _convert_listlike_datetimes( format_is_iso8601 = format_is_iso(format) if format_is_iso8601: require_iso8601 = not infer_datetime_format - format = None - if format is not None: + if format is not None and not require_iso8601: res = _to_datetime_with_format( arg, orig_arg, name, tz, format, exact, errors, infer_datetime_format ) if res is not None: return res - assert format is None or infer_datetime_format utc = tz == "utc" result, tz_parsed = objects_to_datetime64ns( arg, @@ -443,6 +441,8 @@ def _convert_listlike_datetimes( errors=errors, require_iso8601=require_iso8601, allow_object=True, + format=format, + exact=exact, ) if tz_parsed is not None: diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 27fe4e2d5e0b6..22dbec337c8b1 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1746,6 +1746,130 @@ def test_to_datetime_iso8601(self, cache, arg, exp_str): exp = Timestamp(exp_str) assert result[0] == exp + @pytest.mark.parametrize( + "input, format", + [ + ("2012", "%Y-%m"), + ("2012-01", "%Y-%m-%d"), + ("2012-01-01", "%Y-%m-%d %H"), + ("2012-01-01 10", "%Y-%m-%d %H:%M"), + ("2012-01-01 10:00", "%Y-%m-%d %H:%M:%S"), + ("2012-01-01 10:00:00", "%Y-%m-%d %H:%M:%S.%f"), + ("2012-01-01 10:00:00.123", "%Y-%m-%d %H:%M:%S.%f%Z"), + ("2012-01-01 10:00:00.123", "%Y-%m-%d %H:%M:%S.%f%z"), + (0, "%Y-%m-%d"), + ], + ) + @pytest.mark.parametrize("exact", [True, False]) + def test_to_datetime_iso8601_fails(self, input, format, exact): + # https://github.com/pandas-dev/pandas/issues/12649 + # `format` is longer than the string, so this fails regardless of `exact` + with pytest.raises( + ValueError, + match=( + rf"time data \"{input}\" at position 0 doesn't match format " + rf"\"{format}\"" + ), + ): + to_datetime(input, format=format, exact=exact) + + @pytest.mark.parametrize( + "input, format", + [ + ("2012-01-01", "%Y-%m"), + ("2012-01-01 10", "%Y-%m-%d"), + ("2012-01-01 10:00", "%Y-%m-%d %H"), + ("2012-01-01 10:00:00", "%Y-%m-%d %H:%M"), + (0, "%Y-%m-%d"), + ], + ) + def test_to_datetime_iso8601_exact_fails(self, input, format): + # https://github.com/pandas-dev/pandas/issues/12649 + # `format` is shorter than the date string, so only fails with `exact=True` + with pytest.raises( + ValueError, + match=( + rf"time data \"{input}\" at position 0 doesn't match format " + rf"\"{format}\"" + ), + ): + to_datetime(input, format=format) + + @pytest.mark.parametrize( + "input, format", + [ + ("2012-01-01", "%Y-%m"), + ("2012-01-01 00", "%Y-%m-%d"), + ("2012-01-01 00:00", "%Y-%m-%d %H"), + ("2012-01-01 00:00:00", "%Y-%m-%d %H:%M"), + ], + ) + def test_to_datetime_iso8601_non_exact(self, input, format): + # https://github.com/pandas-dev/pandas/issues/12649 + expected = Timestamp(2012, 1, 1) + result = to_datetime(input, format=format, exact=False) + assert result == expected + + @pytest.mark.parametrize( + "input, format", + [ + ("2020-01", "%Y/%m"), + ("2020-01-01", "%Y/%m/%d"), + ("2020-01-01 00", "%Y/%m/%dT%H"), + ("2020-01-01T00", "%Y/%m/%d %H"), + ("2020-01-01 00:00", "%Y/%m/%dT%H:%M"), + ("2020-01-01T00:00", "%Y/%m/%d %H:%M"), + ("2020-01-01 00:00:00", "%Y/%m/%dT%H:%M:%S"), + ("2020-01-01T00:00:00", "%Y/%m/%d %H:%M:%S"), + ], + ) + def test_to_datetime_iso8601_separator(self, input, format): + # https://github.com/pandas-dev/pandas/issues/12649 + with pytest.raises( + ValueError, + match=( + rf"time data \"{input}\" at position 0 doesn\'t match format " + rf"\"{format}\"" + ), + ): + to_datetime(input, format=format) + + @pytest.mark.parametrize( + "input, format", + [ + ("2020-01", "%Y-%m"), + ("2020-01-01", "%Y-%m-%d"), + ("2020-01-01 00", "%Y-%m-%d %H"), + ("2020-01-01T00", "%Y-%m-%dT%H"), + ("2020-01-01 00:00", "%Y-%m-%d %H:%M"), + ("2020-01-01T00:00", "%Y-%m-%dT%H:%M"), + ("2020-01-01 00:00:00", "%Y-%m-%d %H:%M:%S"), + ("2020-01-01T00:00:00", "%Y-%m-%dT%H:%M:%S"), + ("2020-01-01T00:00:00.000", "%Y-%m-%dT%H:%M:%S.%f"), + ("2020-01-01T00:00:00.000000", "%Y-%m-%dT%H:%M:%S.%f"), + ("2020-01-01T00:00:00.000000000", "%Y-%m-%dT%H:%M:%S.%f"), + ], + ) + def test_to_datetime_iso8601_valid(self, input, format): + # https://github.com/pandas-dev/pandas/issues/12649 + expected = Timestamp(2020, 1, 1) + result = to_datetime(input, format=format) + assert result == expected + + @pytest.mark.parametrize( + "input, format", + [ + ("2020-01-01T00:00:00.000000000+00:00", "%Y-%m-%dT%H:%M:%S.%f%z"), + ("2020-01-01T00:00:00+00:00", "%Y-%m-%dT%H:%M:%S%z"), + ("2020-01-01T00:00:00Z", "%Y-%m-%dT%H:%M:%S%Z"), + ], + ) + def test_to_datetime_iso8601_with_timezone_valid(self, input, format): + # https://github.com/pandas-dev/pandas/issues/12649 + expected = Timestamp(2020, 1, 1, tzinfo=pytz.UTC) + result = to_datetime(input, format=format) + assert result == expected + def test_to_datetime_default(self, cache): rs = to_datetime("2001", cache=cache) xp = datetime(2001, 1, 1) @@ -2259,7 +2383,7 @@ def test_day_not_in_month_raise(self, cache): @pytest.mark.parametrize("arg", ["2015-02-29", "2015-02-32", "2015-04-31"]) def test_day_not_in_month_raise_value(self, cache, arg): - msg = f'time data "{arg}" at position 0 doesn\'t match format specified' + msg = f'time data "{arg}" at position 0 doesn\'t match format "%Y-%m-%d"' with pytest.raises(ValueError, match=msg): to_datetime(arg, errors="raise", format="%Y-%m-%d", cache=cache)
- [ ] closes #12649 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. --- EDIT (by MarcoGorelli): this is something @nikitaved, @FDRocha, and I started working on together at a company retreat
https://api.github.com/repos/pandas-dev/pandas/pulls/49333
2022-10-26T13:59:57Z
2022-11-17T13:17:33Z
2022-11-17T13:17:33Z
2022-11-17T15:40:44Z
update from_dict docstring
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d741ca21d8ca7..133a96be5457b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1644,7 +1644,7 @@ def from_dict( 'tight' as an allowed value for the ``orient`` argument dtype : dtype, default None - Data type to force, otherwise infer. + Data type to force after DataFrame construction, otherwise infer. columns : list, default None Column labels to use when ``orient='index'``. Raises a ValueError if used with ``orient='columns'`` or ``orient='tight'``.
- [x] closes #49251
https://api.github.com/repos/pandas-dev/pandas/pulls/49332
2022-10-26T11:03:22Z
2022-10-26T15:56:21Z
2022-10-26T15:56:21Z
2022-10-26T15:56:28Z
Backport PR #49322 on branch 1.5.x (DOC: Fix typo in DataFrame.rolling)
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index c92c448304de2..1a71b41b0e317 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -994,7 +994,7 @@ class Window(BaseWindow): step : int, default None - ..versionadded:: 1.5.0 + .. versionadded:: 1.5.0 Evaluate the window at every ``step`` result, equivalent to slicing as ``[::step]``. ``window`` must be an integer. Using a step argument other
Backport PR #49322: DOC: Fix typo in DataFrame.rolling
https://api.github.com/repos/pandas-dev/pandas/pulls/49326
2022-10-26T07:25:40Z
2022-10-26T11:42:10Z
2022-10-26T11:42:10Z
2022-10-26T11:42:10Z
DEPR: SparseArray.astype
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index eab8df5ccff73..73a63f77f3d83 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -271,6 +271,7 @@ Removal of prior version deprecations/changes - Removed the deprecated method ``mad`` from pandas classes (:issue:`11787`) - Removed the deprecated method ``tshift`` from pandas classes (:issue:`11631`) - Changed the behavior of :func:`to_datetime` with argument "now" with ``utc=False`` to match ``Timestamp("now")`` (:issue:`18705`) +- Changed behavior of :meth:`SparseArray.astype` when given a dtype that is not explicitly ``SparseDtype``, cast to the exact requested dtype rather than silently using a ``SparseDtype`` instead (:issue:`34457`) - Changed behavior of :class:`DataFrame` constructor given floating-point ``data`` and an integer ``dtype``, when the data cannot be cast losslessly, the floating point dtype is retained, matching :class:`Series` behavior (:issue:`41170`) - Changed behavior of :class:`DataFrame` constructor when passed a ``dtype`` (other than int) that the data cannot be cast to; it now raises instead of silently ignoring the dtype (:issue:`41733`) - Changed the behavior of :class:`Series` constructor, it will no longer infer a datetime64 or timedelta64 dtype from string entries (:issue:`41731`) diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 88e94b3c93e5c..d167037fa3015 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -120,6 +120,8 @@ class ellipsis(Enum): SparseIndexKind = Literal["integer", "block"] + from pandas.core.dtypes.dtypes import ExtensionDtype + from pandas import Series else: @@ -1328,14 +1330,13 @@ def astype(self, dtype: AstypeArg | None = None, copy: bool = True): future_dtype = pandas_dtype(dtype) if not isinstance(future_dtype, SparseDtype): # GH#34457 - warnings.warn( - "The behavior of .astype from SparseDtype to a non-sparse dtype " - "is deprecated. In a future version, this will return a non-sparse " - "array with the requested dtype. To retain the old behavior, use " - "`obj.astype(SparseDtype(dtype))`", - FutureWarning, - stacklevel=find_stack_level(), - ) + if isinstance(future_dtype, np.dtype): + values = np.array(self) + return astype_nansafe(values, dtype=future_dtype) + else: + dtype = cast(ExtensionDtype, dtype) + cls = dtype.construct_array_type() + return cls._from_sequence(self, dtype=dtype, copy=copy) dtype = self.dtype.update_dtype(dtype) subtype = pandas_dtype(dtype._subtype_with_str) diff --git a/pandas/tests/arrays/sparse/test_astype.py b/pandas/tests/arrays/sparse/test_astype.py index 6761040d444a5..8751b9bb294ae 100644 --- a/pandas/tests/arrays/sparse/test_astype.py +++ b/pandas/tests/arrays/sparse/test_astype.py @@ -39,12 +39,9 @@ def test_astype(self): def test_astype_bool(self): a = SparseArray([1, 0, 0, 1], dtype=SparseDtype(int, 0)) - with tm.assert_produces_warning(FutureWarning, match="astype from Sparse"): - result = a.astype(bool) - expected = SparseArray( - [True, False, False, True], dtype=SparseDtype(bool, False) - ) - tm.assert_sp_array_equal(result, expected) + result = a.astype(bool) + expected = np.array([1, 0, 0, 1], dtype=bool) + tm.assert_numpy_array_equal(result, expected) # update fill value result = a.astype(SparseDtype(bool, False)) @@ -57,12 +54,8 @@ def test_astype_all(self, any_real_numpy_dtype): vals = np.array([1, 2, 3]) arr = SparseArray(vals, fill_value=1) typ = np.dtype(any_real_numpy_dtype) - with tm.assert_produces_warning(FutureWarning, match="astype from Sparse"): - res = arr.astype(typ) - assert res.dtype == SparseDtype(typ, 1) - assert res.sp_values.dtype == typ - - tm.assert_numpy_array_equal(np.asarray(res.to_dense()), vals.astype(typ)) + res = arr.astype(typ) + tm.assert_numpy_array_equal(res, vals.astype(any_real_numpy_dtype)) @pytest.mark.parametrize( "arr, dtype, expected", @@ -100,22 +93,13 @@ def test_astype_all(self, any_real_numpy_dtype): ], ) def test_astype_more(self, arr, dtype, expected): - - if isinstance(dtype, SparseDtype): - warn = None - else: - warn = FutureWarning - - with tm.assert_produces_warning(warn, match="astype from SparseDtype"): - result = arr.astype(dtype) + result = arr.astype(arr.dtype.update_dtype(dtype)) tm.assert_sp_array_equal(result, expected) def test_astype_nan_raises(self): arr = SparseArray([1.0, np.nan]) with pytest.raises(ValueError, match="Cannot convert non-finite"): - msg = "astype from SparseDtype" - with tm.assert_produces_warning(FutureWarning, match=msg): - arr.astype(int) + arr.astype(int) def test_astype_copy_false(self): # GH#34456 bug caused by using .view instead of .astype in astype_nansafe diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py index babb2868a4421..cc970c690529d 100644 --- a/pandas/tests/extension/base/reshaping.py +++ b/pandas/tests/extension/base/reshaping.py @@ -4,7 +4,6 @@ import pytest import pandas as pd -import pandas._testing as tm from pandas.api.extensions import ExtensionArray from pandas.core.internals.blocks import EABackedBlock from pandas.tests.extension.base.base import BaseExtensionTests @@ -319,23 +318,13 @@ def test_unstack(self, data, index, obj): alt = df.unstack(level=level).droplevel(0, axis=1) self.assert_frame_equal(result, alt) - if obj == "series": - is_sparse = isinstance(ser.dtype, pd.SparseDtype) - else: - is_sparse = isinstance(ser.dtypes.iat[0], pd.SparseDtype) - warn = None if not is_sparse else FutureWarning - with tm.assert_produces_warning(warn, match="astype from Sparse"): - obj_ser = ser.astype(object) + obj_ser = ser.astype(object) expected = obj_ser.unstack(level=level, fill_value=data.dtype.na_value) - if obj == "series" and not is_sparse: - # GH#34457 SparseArray.astype(object) gives Sparse[object] - # instead of np.dtype(object) + if obj == "series": assert (expected.dtypes == object).all() - with tm.assert_produces_warning(warn, match="astype from Sparse"): - result = result.astype(object) - + result = result.astype(object) self.assert_frame_equal(result, expected) def test_ravel(self, data): diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index b1111951d67fa..c051119f0fec4 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -19,8 +19,6 @@ from pandas.errors import PerformanceWarning -from pandas.core.dtypes.common import is_object_dtype - import pandas as pd from pandas import SparseDtype import pandas._testing as tm @@ -159,10 +157,7 @@ def test_concat_mixed_dtypes(self, data): ], ) def test_stack(self, data, columns): - with tm.assert_produces_warning( - FutureWarning, check_stacklevel=False, match="astype from Sparse" - ): - super().test_stack(data, columns) + super().test_stack(data, columns) def test_concat_columns(self, data, na_value): self._check_unsupported(data) @@ -385,33 +380,11 @@ def test_equals(self, data, na_value, as_series, box): class TestCasting(BaseSparseTests, base.BaseCastingTests): - def test_astype_object_series(self, all_data): - # Unlike the base class, we do not expect the resulting Block - # to be ObjectBlock / resulting array to be np.dtype("object") - ser = pd.Series(all_data, name="A") - with tm.assert_produces_warning(FutureWarning, match="astype from Sparse"): - result = ser.astype(object) - assert is_object_dtype(result.dtype) - assert is_object_dtype(result._mgr.array.dtype) - - def test_astype_object_frame(self, all_data): - # Unlike the base class, we do not expect the resulting Block - # to be ObjectBlock / resulting array to be np.dtype("object") - df = pd.DataFrame({"A": all_data}) - - with tm.assert_produces_warning(FutureWarning, match="astype from Sparse"): - result = df.astype(object) - assert is_object_dtype(result._mgr.arrays[0].dtype) - - # check that we can compare the dtypes - comp = result.dtypes == df.dtypes - assert not comp.any() - def test_astype_str(self, data): - with tm.assert_produces_warning(FutureWarning, match="astype from Sparse"): - result = pd.Series(data[:5]).astype(str) - expected_dtype = SparseDtype(str, str(data.fill_value)) - expected = pd.Series([str(x) for x in data[:5]], dtype=expected_dtype) + # pre-2.0 this would give a SparseDtype even if the user asked + # for a non-sparse dtype. + result = pd.Series(data[:5]).astype(str) + expected = pd.Series([str(x) for x in data[:5]], dtype=object) self.assert_series_equal(result, expected) @pytest.mark.xfail(raises=TypeError, reason="no sparse StringDtype") diff --git a/pandas/tests/frame/methods/test_append.py b/pandas/tests/frame/methods/test_append.py index f07ffee20a55f..54d7d95ed4570 100644 --- a/pandas/tests/frame/methods/test_append.py +++ b/pandas/tests/frame/methods/test_append.py @@ -241,12 +241,7 @@ def test_append_timestamps_aware_or_naive(self, tz_naive_fixture, timestamp): def test_other_dtypes(self, data, dtype, using_array_manager): df = DataFrame(data, dtype=dtype) - warn = None - if using_array_manager and isinstance(dtype, pd.SparseDtype): - warn = FutureWarning - - with tm.assert_produces_warning(warn, match="astype from SparseDtype"): - result = df._append(df.iloc[0]).iloc[-1] + result = df._append(df.iloc[0]).iloc[-1] expected = Series(data, name=0, dtype=dtype) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 88ae431fb1baf..1f6a56dc3fdc6 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1300,10 +1300,6 @@ def test_loc_getitem_time_object(self, frame_or_series): @pytest.mark.parametrize("spmatrix_t", ["coo_matrix", "csc_matrix", "csr_matrix"]) @pytest.mark.parametrize("dtype", [np.int64, np.float64, complex]) @td.skip_if_no_scipy - @pytest.mark.filterwarnings( - # TODO(2.0): remove filtering; note only needed for using_array_manager - "ignore:The behavior of .astype from SparseDtype.*FutureWarning" - ) def test_loc_getitem_range_from_spmatrix(self, spmatrix_t, dtype): import scipy.sparse diff --git a/pandas/tests/series/test_ufunc.py b/pandas/tests/series/test_ufunc.py index 4e53000059cdc..6483ad37a2886 100644 --- a/pandas/tests/series/test_ufunc.py +++ b/pandas/tests/series/test_ufunc.py @@ -85,9 +85,7 @@ def test_binary_ufunc_with_index(flip, sparse, ufunc, arrays_for_binary_ufunc): name = "name" # op(pd.Series, array) preserves the name. series = pd.Series(a1, name=name) - warn = None if not sparse else FutureWarning - with tm.assert_produces_warning(warn): - other = pd.Index(a2, name=name).astype("int64") + other = pd.Index(a2, name=name).astype("int64") array_args = (a1, a2) series_args = (series, other) # ufunc(series, array)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49324
2022-10-26T03:03:25Z
2022-11-01T18:45:10Z
2022-11-01T18:45:10Z
2022-11-01T19:00:52Z
STYLE: fix pylint simplifiable-if-statement warnings
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index cd1753bc8fec1..85b1a2a61012a 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -986,10 +986,7 @@ def is_dtype(cls, dtype: object) -> bool: # but doesn't regard freq str like "U" as dtype. if dtype.startswith("period[") or dtype.startswith("Period["): try: - if cls._parse_dtype_strict(dtype) is not None: - return True - else: - return False + return cls._parse_dtype_strict(dtype) is not None except ValueError: return False else: @@ -1254,10 +1251,7 @@ def is_dtype(cls, dtype: object) -> bool: if isinstance(dtype, str): if dtype.lower().startswith("interval"): try: - if cls.construct_from_string(dtype) is not None: - return True - else: - return False + return cls.construct_from_string(dtype) is not None except (ValueError, TypeError): return False else: diff --git a/pandas/io/formats/info.py b/pandas/io/formats/info.py index e0f6e01a65052..96b96f31792cc 100644 --- a/pandas/io/formats/info.py +++ b/pandas/io/formats/info.py @@ -500,10 +500,7 @@ def non_null_counts(self) -> Sequence[int]: @property def memory_usage_bytes(self) -> int: - if self.memory_usage == "deep": - deep = True - else: - deep = False + deep = self.memory_usage == "deep" return self.data.memory_usage(index=True, deep=deep).sum() def render( @@ -579,10 +576,7 @@ def memory_usage_bytes(self) -> int: memory_usage_bytes : int Object's total memory usage in bytes. """ - if self.memory_usage == "deep": - deep = True - else: - deep = False + deep = self.memory_usage == "deep" return self.data.memory_usage(index=True, deep=deep) diff --git a/pandas/tests/tseries/offsets/test_week.py b/pandas/tests/tseries/offsets/test_week.py index 51eb662967db6..f42ff091af277 100644 --- a/pandas/tests/tseries/offsets/test_week.py +++ b/pandas/tests/tseries/offsets/test_week.py @@ -114,11 +114,7 @@ def test_is_on_offset(self, weekday): for day in range(1, 8): date = datetime(2008, 1, day) - - if day % 7 == weekday: - expected = True - else: - expected = False + expected = day % 7 == weekday assert_is_on_offset(offset, date, expected) @pytest.mark.parametrize( diff --git a/pyproject.toml b/pyproject.toml index f2ebed97bed50..b6c657dfd8b15 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -125,7 +125,6 @@ disable = [ "no-self-use", "redefined-argument-from-local", "simplifiable-if-expression", - "simplifiable-if-statement", "too-few-public-methods", "too-many-ancestors", "too-many-arguments",
Related to https://github.com/pandas-dev/pandas/issues/48855 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49323
2022-10-26T02:08:02Z
2022-10-26T13:00:37Z
2022-10-26T13:00:37Z
2022-10-26T14:35:23Z
DOC: Fix typo in DataFrame.rolling
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index cde39daaacab9..4ac09a7149857 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -964,7 +964,7 @@ class Window(BaseWindow): step : int, default None - ..versionadded:: 1.5.0 + .. versionadded:: 1.5.0 Evaluate the window at every ``step`` result, equivalent to slicing as ``[::step]``. ``window`` must be an integer. Using a step argument other
null
https://api.github.com/repos/pandas-dev/pandas/pulls/49322
2022-10-26T01:51:33Z
2022-10-26T07:25:14Z
2022-10-26T07:25:14Z
2022-10-26T07:25:26Z
DEPR: remove inplace arg in Categorical methods
diff --git a/doc/source/user_guide/categorical.rst b/doc/source/user_guide/categorical.rst index b5cb1d83a9f52..f3d68f4c471c1 100644 --- a/doc/source/user_guide/categorical.rst +++ b/doc/source/user_guide/categorical.rst @@ -353,11 +353,6 @@ Renaming categories is done by using the In contrast to R's ``factor``, categorical data can have categories of other types than string. -.. note:: - - Be aware that assigning new categories is an inplace operation, while most other operations - under ``Series.cat`` per default return a new ``Series`` of dtype ``category``. - Categories must be unique or a ``ValueError`` is raised: .. ipython:: python @@ -952,7 +947,6 @@ categorical (categories and ordering). So if you read back the CSV file you have relevant columns back to ``category`` and assign the right categories and categories ordering. .. ipython:: python - :okwarning: import io @@ -969,8 +963,8 @@ relevant columns back to ``category`` and assign the right categories and catego df2["cats"] # Redo the category df2["cats"] = df2["cats"].astype("category") - df2["cats"].cat.set_categories( - ["very bad", "bad", "medium", "good", "very good"], inplace=True + df2["cats"] = df2["cats"].cat.set_categories( + ["very bad", "bad", "medium", "good", "very good"] ) df2.dtypes df2["cats"] @@ -1162,16 +1156,12 @@ Constructing a ``Series`` from a ``Categorical`` will not copy the input change the original ``Categorical``: .. ipython:: python - :okwarning: cat = pd.Categorical([1, 2, 3, 10], categories=[1, 2, 3, 4, 10]) s = pd.Series(cat, name="cat") cat s.iloc[0:2] = 10 cat - df = pd.DataFrame(s) - df["cat"].cat.categories = [1, 2, 3, 4, 5] - cat Use ``copy=True`` to prevent such a behaviour or simply don't reuse ``Categoricals``: diff --git a/doc/source/whatsnew/v0.15.0.rst b/doc/source/whatsnew/v0.15.0.rst index 04506f1655c7d..f52253687ecfd 100644 --- a/doc/source/whatsnew/v0.15.0.rst +++ b/doc/source/whatsnew/v0.15.0.rst @@ -70,7 +70,6 @@ For full docs, see the :ref:`categorical introduction <categorical>` and the :ref:`API documentation <api.arrays.categorical>`. .. ipython:: python - :okwarning: df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6], "raw_grade": ['a', 'b', 'b', 'a', 'a', 'e']}) @@ -79,7 +78,7 @@ For full docs, see the :ref:`categorical introduction <categorical>` and the df["grade"] # Rename the categories - df["grade"].cat.categories = ["very good", "good", "very bad"] + df["grade"] = df["grade"].cat.rename_categories(["very good", "good", "very bad"]) # Reorder the categories and simultaneously add the missing categories df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", diff --git a/doc/source/whatsnew/v0.19.0.rst b/doc/source/whatsnew/v0.19.0.rst index 0c992cf3cc462..feeb7b5ee30ce 100644 --- a/doc/source/whatsnew/v0.19.0.rst +++ b/doc/source/whatsnew/v0.19.0.rst @@ -271,12 +271,12 @@ Individual columns can be parsed as a ``Categorical`` using a dict specification such as :func:`to_datetime`. .. ipython:: python - :okwarning: df = pd.read_csv(StringIO(data), dtype="category") df.dtypes df["col3"] - df["col3"].cat.categories = pd.to_numeric(df["col3"].cat.categories) + new_categories = pd.to_numeric(df["col3"].cat.categories) + df["col3"] = df["col3"].cat.rename_categories(new_categories) df["col3"] .. _whatsnew_0190.enhancements.union_categoricals: diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 91bdc106ad0b8..becca2b668290 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -15,11 +15,7 @@ cast, overload, ) -from warnings import ( - catch_warnings, - simplefilter, - warn, -) +from warnings import warn import numpy as np @@ -31,10 +27,6 @@ lib, ) from pandas._libs.arrays import NDArrayBacked -from pandas._libs.lib import ( - NoDefault, - no_default, -) from pandas._typing import ( ArrayLike, AstypeArg, @@ -48,7 +40,6 @@ type_t, ) from pandas.compat.numpy import function as nv -from pandas.util._decorators import deprecate_nonkeyword_arguments from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_bool_kwarg @@ -729,8 +720,6 @@ def categories(self) -> Index: unique and the number of items in the new categories must be the same as the number of items in the old categories. - Assigning to `categories` is a inplace operation! - Raises ------ ValueError @@ -748,17 +737,6 @@ def categories(self) -> Index: """ return self.dtype.categories - @categories.setter - def categories(self, categories) -> None: - warn( - "Setting categories in-place is deprecated and will raise in a " - "future version. Use rename_categories instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - - self._set_categories(categories) - @property def ordered(self) -> Ordered: """ @@ -839,24 +817,7 @@ def _set_dtype(self, dtype: CategoricalDtype) -> Categorical: codes = recode_for_categories(self.codes, self.categories, dtype.categories) return type(self)(codes, dtype=dtype, fastpath=True) - @overload - def set_ordered( - self, value, *, inplace: NoDefault | Literal[False] = ... - ) -> Categorical: - ... - - @overload - def set_ordered(self, value, *, inplace: Literal[True]) -> None: - ... - - @overload - def set_ordered(self, value, *, inplace: bool) -> Categorical | None: - ... - - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "value"]) - def set_ordered( - self, value, inplace: bool | NoDefault = no_default - ) -> Categorical | None: + def set_ordered(self, value: bool) -> Categorical: """ Set the ordered attribute to the boolean value. @@ -864,98 +825,35 @@ def set_ordered( ---------- value : bool Set whether this categorical is ordered (True) or not (False). - inplace : bool, default False - Whether or not to set the ordered attribute in-place or return - a copy of this categorical with ordered set to the value. - - .. deprecated:: 1.5.0 - """ - if inplace is not no_default: - warn( - "The `inplace` parameter in pandas.Categorical." - "set_ordered is deprecated and will be removed in " - "a future version. setting ordered-ness on categories will always " - "return a new Categorical object.", - FutureWarning, - stacklevel=find_stack_level(), - ) - else: - inplace = False - - inplace = validate_bool_kwarg(inplace, "inplace") new_dtype = CategoricalDtype(self.categories, ordered=value) - cat = self if inplace else self.copy() + cat = self.copy() NDArrayBacked.__init__(cat, cat._ndarray, new_dtype) - if not inplace: - return cat - return None - - @overload - def as_ordered(self, *, inplace: NoDefault | Literal[False] = ...) -> Categorical: - ... - - @overload - def as_ordered(self, *, inplace: Literal[True]) -> None: - ... + return cat - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) - def as_ordered(self, inplace: bool | NoDefault = no_default) -> Categorical | None: + def as_ordered(self) -> Categorical: """ Set the Categorical to be ordered. - Parameters - ---------- - inplace : bool, default False - Whether or not to set the ordered attribute in-place or return - a copy of this categorical with ordered set to True. - - .. deprecated:: 1.5.0 - Returns ------- - Categorical or None - Ordered Categorical or None if ``inplace=True``. + Categorical + Ordered Categorical. """ - if inplace is not no_default: - inplace = validate_bool_kwarg(inplace, "inplace") - return self.set_ordered(True, inplace=inplace) - - @overload - def as_unordered(self, *, inplace: NoDefault | Literal[False] = ...) -> Categorical: - ... - - @overload - def as_unordered(self, *, inplace: Literal[True]) -> None: - ... + return self.set_ordered(True) - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) - def as_unordered( - self, inplace: bool | NoDefault = no_default - ) -> Categorical | None: + def as_unordered(self) -> Categorical: """ Set the Categorical to be unordered. - Parameters - ---------- - inplace : bool, default False - Whether or not to set the ordered attribute in-place or return - a copy of this categorical with ordered set to False. - - .. deprecated:: 1.5.0 - Returns ------- - Categorical or None - Unordered Categorical or None if ``inplace=True``. + Categorical + Unordered Categorical. """ - if inplace is not no_default: - inplace = validate_bool_kwarg(inplace, "inplace") - return self.set_ordered(False, inplace=inplace) + return self.set_ordered(False) - def set_categories( - self, new_categories, ordered=None, rename: bool = False, inplace=no_default - ): + def set_categories(self, new_categories, ordered=None, rename: bool = False): """ Set the categories to the specified new_categories. @@ -985,15 +883,10 @@ def set_categories( rename : bool, default False Whether or not the new_categories should be considered as a rename of the old categories or as reordered categories. - inplace : bool, default False - Whether or not to reorder the categories in-place or return a copy - of this categorical with reordered categories. - - .. deprecated:: 1.3.0 Returns ------- - Categorical with reordered categories or None if inplace. + Categorical with reordered categories. Raises ------ @@ -1008,24 +901,12 @@ def set_categories( remove_categories : Remove the specified categories. remove_unused_categories : Remove categories which are not used. """ - if inplace is not no_default: - warn( - "The `inplace` parameter in pandas.Categorical." - "set_categories is deprecated and will be removed in " - "a future version. Removing unused categories will always " - "return a new Categorical object.", - FutureWarning, - stacklevel=find_stack_level(), - ) - else: - inplace = False - inplace = validate_bool_kwarg(inplace, "inplace") if ordered is None: ordered = self.dtype.ordered new_dtype = CategoricalDtype(new_categories, ordered=ordered) - cat = self if inplace else self.copy() + cat = self.copy() if rename: if cat.dtype.categories is not None and len(new_dtype.categories) < len( cat.dtype.categories @@ -1038,26 +919,9 @@ def set_categories( cat.codes, cat.categories, new_dtype.categories ) NDArrayBacked.__init__(cat, codes, new_dtype) + return cat - if not inplace: - return cat - - @overload - def rename_categories( - self, new_categories, *, inplace: Literal[False] | NoDefault = ... - ) -> Categorical: - ... - - @overload - def rename_categories(self, new_categories, *, inplace: Literal[True]) -> None: - ... - - @deprecate_nonkeyword_arguments( - version=None, allowed_args=["self", "new_categories"] - ) - def rename_categories( - self, new_categories, inplace: bool | NoDefault = no_default - ) -> Categorical | None: + def rename_categories(self, new_categories) -> Categorical: """ Rename categories. @@ -1078,16 +942,10 @@ def rename_categories( * callable : a callable that is called on all items in the old categories and whose return values comprise the new categories. - inplace : bool, default False - Whether or not to rename the categories inplace or return a copy of - this categorical with renamed categories. - - .. deprecated:: 1.3.0 - Returns ------- - cat : Categorical or None - Categorical with removed categories or None if ``inplace=True``. + cat : Categorical + Categorical with renamed categories. Raises ------ @@ -1123,32 +981,19 @@ def rename_categories( ['A', 'A', 'B'] Categories (2, object): ['A', 'B'] """ - if inplace is not no_default: - warn( - "The `inplace` parameter in pandas.Categorical." - "rename_categories is deprecated and will be removed in " - "a future version. Removing unused categories will always " - "return a new Categorical object.", - FutureWarning, - stacklevel=find_stack_level(), - ) - else: - inplace = False - - inplace = validate_bool_kwarg(inplace, "inplace") - cat = self if inplace else self.copy() if is_dict_like(new_categories): - new_categories = [new_categories.get(item, item) for item in cat.categories] + new_categories = [ + new_categories.get(item, item) for item in self.categories + ] elif callable(new_categories): - new_categories = [new_categories(item) for item in cat.categories] + new_categories = [new_categories(item) for item in self.categories] + cat = self.copy() cat._set_categories(new_categories) - if not inplace: - return cat - return None + return cat - def reorder_categories(self, new_categories, ordered=None, inplace=no_default): + def reorder_categories(self, new_categories, ordered=None): """ Reorder categories as specified in new_categories. @@ -1162,16 +1007,11 @@ def reorder_categories(self, new_categories, ordered=None, inplace=no_default): ordered : bool, optional Whether or not the categorical is treated as a ordered categorical. If not given, do not change the ordered information. - inplace : bool, default False - Whether or not to reorder the categories inplace or return a copy of - this categorical with reordered categories. - - .. deprecated:: 1.3.0 Returns ------- - cat : Categorical or None - Categorical with removed categories or None if ``inplace=True``. + cat : Categorical + Categorical with reordered categories. Raises ------ @@ -1187,44 +1027,13 @@ def reorder_categories(self, new_categories, ordered=None, inplace=no_default): remove_unused_categories : Remove categories which are not used. set_categories : Set the categories to the specified ones. """ - if inplace is not no_default: - warn( - "The `inplace` parameter in pandas.Categorical." - "reorder_categories is deprecated and will be removed in " - "a future version. Reordering categories will always " - "return a new Categorical object.", - FutureWarning, - stacklevel=find_stack_level(), - ) - else: - inplace = False - - inplace = validate_bool_kwarg(inplace, "inplace") if set(self.dtype.categories) != set(new_categories): raise ValueError( "items in new_categories are not the same as in old categories" ) + return self.set_categories(new_categories, ordered=ordered) - with catch_warnings(): - simplefilter("ignore") - return self.set_categories(new_categories, ordered=ordered, inplace=inplace) - - @overload - def add_categories( - self, new_categories, *, inplace: Literal[False] | NoDefault = ... - ) -> Categorical: - ... - - @overload - def add_categories(self, new_categories, *, inplace: Literal[True]) -> None: - ... - - @deprecate_nonkeyword_arguments( - version=None, allowed_args=["self", "new_categories"] - ) - def add_categories( - self, new_categories, inplace: bool | NoDefault = no_default - ) -> Categorical | None: + def add_categories(self, new_categories) -> Categorical: """ Add new categories. @@ -1235,16 +1044,11 @@ def add_categories( ---------- new_categories : category or list-like of category The new categories to be included. - inplace : bool, default False - Whether or not to add the categories inplace or return a copy of - this categorical with added categories. - - .. deprecated:: 1.3.0 Returns ------- - cat : Categorical or None - Categorical with new categories added or None if ``inplace=True``. + cat : Categorical + Categorical with new categories added. Raises ------ @@ -1271,19 +1075,7 @@ def add_categories( ['c', 'b', 'c'] Categories (4, object): ['b', 'c', 'd', 'a'] """ - if inplace is not no_default: - warn( - "The `inplace` parameter in pandas.Categorical." - "add_categories is deprecated and will be removed in " - "a future version. Removing unused categories will always " - "return a new Categorical object.", - FutureWarning, - stacklevel=find_stack_level(), - ) - else: - inplace = False - inplace = validate_bool_kwarg(inplace, "inplace") if not is_list_like(new_categories): new_categories = [new_categories] already_included = set(new_categories) & set(self.dtype.categories) @@ -1305,15 +1097,12 @@ def add_categories( new_categories = list(self.dtype.categories) + list(new_categories) new_dtype = CategoricalDtype(new_categories, self.ordered) - - cat = self if inplace else self.copy() + cat = self.copy() codes = coerce_indexer_dtype(cat._ndarray, new_dtype.categories) NDArrayBacked.__init__(cat, codes, new_dtype) - if not inplace: - return cat - return None + return cat - def remove_categories(self, removals, inplace=no_default): + def remove_categories(self, removals): """ Remove the specified categories. @@ -1324,16 +1113,11 @@ def remove_categories(self, removals, inplace=no_default): ---------- removals : category or list of categories The categories which should be removed. - inplace : bool, default False - Whether or not to remove the categories inplace or return a copy of - this categorical with removed categories. - - .. deprecated:: 1.3.0 Returns ------- - cat : Categorical or None - Categorical with removed categories or None if ``inplace=True``. + cat : Categorical + Categorical with removed categories. Raises ------ @@ -1359,19 +1143,6 @@ def remove_categories(self, removals, inplace=no_default): [NaN, 'c', 'b', 'c', NaN] Categories (2, object): ['b', 'c'] """ - if inplace is not no_default: - warn( - "The `inplace` parameter in pandas.Categorical." - "remove_categories is deprecated and will be removed in " - "a future version. Removing unused categories will always " - "return a new Categorical object.", - FutureWarning, - stacklevel=find_stack_level(), - ) - else: - inplace = False - - inplace = validate_bool_kwarg(inplace, "inplace") if not is_list_like(removals): removals = [removals] @@ -1387,11 +1158,7 @@ def remove_categories(self, removals, inplace=no_default): if len(not_included) != 0: raise ValueError(f"removals must all be in old categories: {not_included}") - with catch_warnings(): - simplefilter("ignore") - return self.set_categories( - new_categories, ordered=self.ordered, rename=False, inplace=inplace - ) + return self.set_categories(new_categories, ordered=self.ordered, rename=False) def remove_unused_categories(self) -> Categorical: """ @@ -2522,40 +2289,40 @@ def _replace(self, *, to_replace, value, inplace: bool = False): inplace = validate_bool_kwarg(inplace, "inplace") cat = self if inplace else self.copy() - # build a dict of (to replace -> value) pairs - if is_list_like(to_replace): - # if to_replace is list-like and value is scalar - replace_dict = {replace_value: value for replace_value in to_replace} - else: - # if both to_replace and value are scalar - replace_dict = {to_replace: value} - # other cases, like if both to_replace and value are list-like or if # to_replace is a dict, are handled separately in NDFrame - for replace_value, new_value in replace_dict.items(): - if new_value == replace_value: + if not is_list_like(to_replace): + to_replace = [to_replace] + + categories = cat.categories.tolist() + removals = set() + for replace_value in to_replace: + if value == replace_value: + continue + if replace_value not in cat.categories: continue - if replace_value in cat.categories: - if isna(new_value): - with catch_warnings(): - simplefilter("ignore") - cat.remove_categories(replace_value, inplace=True) - continue - - categories = cat.categories.tolist() - index = categories.index(replace_value) - - if new_value in cat.categories: - value_index = categories.index(new_value) - cat._codes[cat._codes == index] = value_index - with catch_warnings(): - simplefilter("ignore") - cat.remove_categories(replace_value, inplace=True) - else: - categories[index] = new_value - with catch_warnings(): - simplefilter("ignore") - cat.rename_categories(categories, inplace=True) + if isna(value): + removals.add(replace_value) + continue + + index = categories.index(replace_value) + + if value in cat.categories: + value_index = categories.index(value) + cat._codes[cat._codes == index] = value_index + removals.add(replace_value) + else: + categories[index] = value + cat._set_categories(categories) + + if len(removals): + new_categories = [c for c in categories if c not in removals] + new_dtype = CategoricalDtype(new_categories, ordered=self.dtype.ordered) + codes = recode_for_categories( + cat.codes, cat.categories, new_dtype.categories + ) + NDArrayBacked.__init__(cat, codes, new_dtype) + if not inplace: return cat @@ -2605,10 +2372,6 @@ class CategoricalAccessor(PandasDelegate, PandasObject, NoNewAttributesMixin): """ Accessor object for categorical properties of the Series values. - Be aware that assigning to `categories` is a inplace operation, while all - methods return new categorical data per default (but can be called with - `inplace=True`). - Parameters ---------- data : Series or CategoricalIndex diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py index 2723b838c41a2..55d39cf84eb30 100644 --- a/pandas/tests/arrays/categorical/test_analytics.py +++ b/pandas/tests/arrays/categorical/test_analytics.py @@ -320,48 +320,6 @@ def test_validate_inplace_raises(self, value): 'For argument "inplace" expected type bool, ' f"received type {type(value).__name__}" ) - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning( - FutureWarning, match="Use rename_categories" - ): - cat.set_ordered(value=True, inplace=value) - - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning( - FutureWarning, match="Use rename_categories" - ): - cat.as_ordered(inplace=value) - - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning( - FutureWarning, match="Use rename_categories" - ): - cat.as_unordered(inplace=value) - - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - cat.set_categories(["X", "Y", "Z"], rename=True, inplace=value) - - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - cat.rename_categories(["X", "Y", "Z"], inplace=value) - - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - cat.reorder_categories(["X", "Y", "Z"], ordered=True, inplace=value) - - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - cat.add_categories(new_categories=["D", "E", "F"], inplace=value) - - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - cat.remove_categories(removals=["D", "E", "F"], inplace=value) with pytest.raises(ValueError, match=msg): cat.sort_values(inplace=value) diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py index 2f13d4ee0dd40..450581f89d735 100644 --- a/pandas/tests/arrays/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -37,31 +37,14 @@ def test_ordered_api(self): assert cat4.ordered def test_set_ordered(self): - msg = ( - "The `inplace` parameter in pandas.Categorical.set_ordered is " - "deprecated and will be removed in a future version. setting " - "ordered-ness on categories will always return a new Categorical object" - ) cat = Categorical(["a", "b", "c", "a"], ordered=True) cat2 = cat.as_unordered() assert not cat2.ordered cat2 = cat.as_ordered() assert cat2.ordered - with tm.assert_produces_warning(FutureWarning, match=msg): - cat2.as_unordered(inplace=True) - assert not cat2.ordered - with tm.assert_produces_warning(FutureWarning, match=msg): - cat2.as_ordered(inplace=True) - assert cat2.ordered assert cat2.set_ordered(True).ordered assert not cat2.set_ordered(False).ordered - with tm.assert_produces_warning(FutureWarning, match=msg): - cat2.set_ordered(True, inplace=True) - assert cat2.ordered - with tm.assert_produces_warning(FutureWarning, match=msg): - cat2.set_ordered(False, inplace=True) - assert not cat2.ordered # removed in 0.19.0 msg = ( @@ -95,17 +78,6 @@ def test_rename_categories(self): expected = Categorical(["A", "B", "C", "A"]) tm.assert_categorical_equal(result, expected) - # and now inplace - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - res = cat.rename_categories([1, 2, 3], inplace=True) - - assert res is None - tm.assert_numpy_array_equal( - cat.__array__(), np.array([1, 2, 3, 1], dtype=np.int64) - ) - tm.assert_index_equal(cat.categories, Index([1, 2, 3])) - @pytest.mark.parametrize("new_categories", [[1, 2, 3, 4], [1, 2]]) def test_rename_categories_wrong_length_raises(self, new_categories): cat = Categorical(["a", "b", "c", "a"]) @@ -130,14 +102,6 @@ def test_rename_categories_dict(self): expected = Index([4, 3, 2, 1]) tm.assert_index_equal(res.categories, expected) - # Test for inplace - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - res = cat.rename_categories({"a": 4, "b": 3, "c": 2, "d": 1}, inplace=True) - - assert res is None - tm.assert_index_equal(cat.categories, expected) - # Test for dicts of smaller length cat = Categorical(["a", "b", "c", "d"]) res = cat.rename_categories({"a": 1, "c": 3}) @@ -165,21 +129,12 @@ def test_reorder_categories(self): ["a", "b", "c", "a"], categories=["c", "b", "a"], ordered=True ) - # first inplace == False res = cat.reorder_categories(["c", "b", "a"]) # cat must be the same as before tm.assert_categorical_equal(cat, old) # only res is changed tm.assert_categorical_equal(res, new) - # inplace == True - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - res = cat.reorder_categories(["c", "b", "a"], inplace=True) - - assert res is None - tm.assert_categorical_equal(cat, new) - @pytest.mark.parametrize( "new_categories", [ @@ -201,7 +156,6 @@ def test_add_categories(self): ["a", "b", "c", "a"], categories=["a", "b", "c", "d"], ordered=True ) - # first inplace == False res = cat.add_categories("d") tm.assert_categorical_equal(cat, old) tm.assert_categorical_equal(res, new) @@ -210,14 +164,6 @@ def test_add_categories(self): tm.assert_categorical_equal(cat, old) tm.assert_categorical_equal(res, new) - # inplace == True - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - res = cat.add_categories("d", inplace=True) - - tm.assert_categorical_equal(cat, new) - assert res is None - # GH 9927 cat = Categorical(list("abc"), ordered=True) expected = Categorical(list("abc"), categories=list("abcde"), ordered=True) @@ -262,14 +208,7 @@ def test_set_categories(self): exp_categories = Index(["c", "b", "a"]) exp_values = np.array(["a", "b", "c", "a"], dtype=np.object_) - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - res = cat.set_categories(["c", "b", "a"], inplace=True) - - tm.assert_index_equal(cat.categories, exp_categories) - tm.assert_numpy_array_equal(cat.__array__(), exp_values) - assert res is None - + cat = cat.set_categories(["c", "b", "a"]) res = cat.set_categories(["a", "b", "c"]) # cat must be the same as before tm.assert_index_equal(cat.categories, exp_categories) @@ -386,7 +325,6 @@ def test_remove_categories(self): old = cat.copy() new = Categorical(["a", "b", np.nan, "a"], categories=["a", "b"], ordered=True) - # first inplace == False res = cat.remove_categories("c") tm.assert_categorical_equal(cat, old) tm.assert_categorical_equal(res, new) @@ -395,14 +333,6 @@ def test_remove_categories(self): tm.assert_categorical_equal(cat, old) tm.assert_categorical_equal(res, new) - # inplace == True - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - res = cat.remove_categories("c", inplace=True) - - tm.assert_categorical_equal(cat, new) - assert res is None - @pytest.mark.parametrize("removals", [["c"], ["c", np.nan], "c", ["c", "c"]]) def test_remove_categories_raises(self, removals): cat = Categorical(["a", "b", "a"]) @@ -462,11 +392,7 @@ def test_describe(self, factor): # check unused categories cat = factor.copy() - - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - cat.set_categories(["a", "b", "c", "d"], inplace=True) - + cat = cat.set_categories(["a", "b", "c", "d"]) desc = cat.describe() exp_index = CategoricalIndex( @@ -500,15 +426,6 @@ def test_describe(self, factor): ) tm.assert_frame_equal(desc, expected) - def test_set_categories_inplace(self, factor): - cat = factor.copy() - - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - cat.set_categories(["a", "b", "c", "d"], inplace=True) - - tm.assert_index_equal(cat.categories, Index(["a", "b", "c", "d"])) - class TestPrivateCategoricalAPI: def test_codes_immutable(self): diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index 94e966642b925..d42b73b7c0020 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -191,14 +191,6 @@ def test_periodindex(self): tm.assert_numpy_array_equal(cat3._codes, exp_arr) tm.assert_index_equal(cat3.categories, exp_idx) - def test_categories_assignments(self): - cat = Categorical(["a", "b", "c", "a"]) - exp = np.array([1, 2, 3, 1], dtype=np.int64) - with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): - cat.categories = [1, 2, 3] - tm.assert_numpy_array_equal(cat.__array__(), exp) - tm.assert_index_equal(cat.categories, Index([1, 2, 3])) - @pytest.mark.parametrize( "null_val", [None, np.nan, NaT, NA, math.nan, "NaT", "nat", "NAT", "nan", "NaN", "NAN"], @@ -217,9 +209,8 @@ def test_categories_assignments_wrong_length_raises(self, new_categories): "new categories need to have the same number of items " "as the old categories!" ) - with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): - with pytest.raises(ValueError, match=msg): - cat.categories = new_categories + with pytest.raises(ValueError, match=msg): + cat.rename_categories(new_categories) # Combinations of sorted/unique: @pytest.mark.parametrize( diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 6e7ba57dddf8f..1c08a37c58e4e 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -1076,12 +1076,7 @@ def test_setitem_mask_categorical(self): df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf) exp_fancy = exp_multi_row.copy() - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - # issue #37643 inplace kwarg deprecated - return_value = exp_fancy["cats"].cat.set_categories( - ["a", "b", "c"], inplace=True - ) - assert return_value is None + exp_fancy["cats"] = exp_fancy["cats"].cat.set_categories(["a", "b", "c"]) mask = df["cats"] == "c" df[mask] = ["b", 2] diff --git a/pandas/tests/series/accessors/test_cat_accessor.py b/pandas/tests/series/accessors/test_cat_accessor.py index 48a01f0018775..54a3ddd24a203 100644 --- a/pandas/tests/series/accessors/test_cat_accessor.py +++ b/pandas/tests/series/accessors/test_cat_accessor.py @@ -46,13 +46,6 @@ def test_cat_accessor(self): exp = Categorical(["a", "b", np.nan, "a"], categories=["b", "a"]) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - # issue #37643 inplace kwarg deprecated - return_value = ser.cat.set_categories(["b", "a"], inplace=True) - - assert return_value is None - tm.assert_categorical_equal(ser.values, exp) - res = ser.cat.set_categories(["b", "a"]) tm.assert_categorical_equal(res.values, exp) @@ -99,8 +92,7 @@ def test_categorical_delegations(self): ser = Series(Categorical(["a", "b", "c", "a"], ordered=True)) exp_categories = Index(["a", "b", "c"]) tm.assert_index_equal(ser.cat.categories, exp_categories) - with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): - ser.cat.categories = [1, 2, 3] + ser = ser.cat.rename_categories([1, 2, 3]) exp_categories = Index([1, 2, 3]) tm.assert_index_equal(ser.cat.categories, exp_categories) @@ -110,9 +102,8 @@ def test_categorical_delegations(self): assert ser.cat.ordered ser = ser.cat.as_unordered() assert not ser.cat.ordered - with tm.assert_produces_warning(FutureWarning, match="The `inplace`"): - return_value = ser.cat.as_ordered(inplace=True) - assert return_value is None + + ser = ser.cat.as_ordered() assert ser.cat.ordered # reorder @@ -234,34 +225,13 @@ def test_dt_accessor_api_for_categorical_invalid(self): invalid.dt assert not hasattr(invalid, "str") - def test_reorder_categories_updates_dtype(self): - # GH#43232 - ser = Series(["a", "b", "c"], dtype="category") - orig_dtype = ser.dtype - - # Need to construct this before calling reorder_categories inplace - expected = ser.cat.reorder_categories(["c", "b", "a"]) - - with tm.assert_produces_warning(FutureWarning, match="`inplace` parameter"): - ser.cat.reorder_categories(["c", "b", "a"], inplace=True) - - assert not orig_dtype.categories.equals(ser.dtype.categories) - assert not orig_dtype.categories.equals(expected.dtype.categories) - assert ser.dtype == expected.dtype - assert ser.dtype.categories.equals(expected.dtype.categories) - - tm.assert_series_equal(ser, expected) - def test_set_categories_setitem(self): # GH#43334 df = DataFrame({"Survived": [1, 0, 1], "Sex": [0, 1, 1]}, dtype="category") - # change the dtype in-place - with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): - df["Survived"].cat.categories = ["No", "Yes"] - with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): - df["Sex"].cat.categories = ["female", "male"] + df["Survived"] = df["Survived"].cat.rename_categories(["No", "Yes"]) + df["Sex"] = df["Sex"].cat.rename_categories(["female", "male"]) # values should not be coerced to NaN assert list(df["Sex"]) == ["female", "male", "male"] diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 4a4b5bd3edc6c..11f8544b78e94 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -478,8 +478,7 @@ def test_categorical_sideeffects_free(self): cat = Categorical(["a", "b", "c", "a"]) s = Series(cat, copy=True) assert s.cat is not cat - with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): - s.cat.categories = [1, 2, 3] + s = s.cat.rename_categories([1, 2, 3]) exp_s = np.array([1, 2, 3, 1], dtype=np.int64) exp_cat = np.array(["a", "b", "c", "a"], dtype=np.object_) tm.assert_numpy_array_equal(s.__array__(), exp_s) @@ -496,16 +495,14 @@ def test_categorical_sideeffects_free(self): cat = Categorical(["a", "b", "c", "a"]) s = Series(cat) assert s.values is cat - with tm.assert_produces_warning(FutureWarning, match="Use rename_categories"): - s.cat.categories = [1, 2, 3] + s = s.cat.rename_categories([1, 2, 3]) + assert s.values is not cat exp_s = np.array([1, 2, 3, 1], dtype=np.int64) tm.assert_numpy_array_equal(s.__array__(), exp_s) - tm.assert_numpy_array_equal(cat.__array__(), exp_s) s[0] = 2 exp_s2 = np.array([2, 2, 3, 1], dtype=np.int64) tm.assert_numpy_array_equal(s.__array__(), exp_s2) - tm.assert_numpy_array_equal(cat.__array__(), exp_s2) def test_unordered_compare_equal(self): left = Series(["a", "b", "c"], dtype=CategoricalDtype(["a", "b"]))
- [x] closes #37643 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.0.0.rst` file if fixing a bug or adding a new feature. I combined these into a single PR given they're all roughly the same deprecation of removing the `inplace` arg from Categorical methods. This can be split into smaller PRs if preferred. Deprecations introduced in: #37981, #41118, #41133, #47834
https://api.github.com/repos/pandas-dev/pandas/pulls/49321
2022-10-26T00:21:07Z
2022-10-29T01:42:21Z
2022-10-29T01:42:21Z
2022-11-03T01:38:37Z
(📚) update docs to mention 3.11 support
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 218d95229e93a..f41d6eebef302 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -52,7 +52,7 @@ jobs: - [windows-2019, win_amd64] - [windows-2019, win32] # TODO: support PyPy? - python: [["cp38", "3.8"], ["cp39", "3.9"], ["cp310", "3.10"], ["cp311", "3.11-dev"]]# "pp38", "pp39"] + python: [["cp38", "3.8"], ["cp39", "3.9"], ["cp310", "3.10"], ["cp311", "3.11"]]# "pp38", "pp39"] env: IS_PUSH: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }} IS_SCHEDULE_DISPATCH: ${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }} @@ -73,7 +73,7 @@ jobs: CIBW_BUILD: ${{ matrix.python[0] }}-${{ matrix.buildplat[1] }} # Used to test the built wheels - - uses: actions/setup-python@v3 + - uses: actions/setup-python@v4 with: python-version: ${{ matrix.python[1] }} diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index ca45540b637ba..aea65eb15e929 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -20,7 +20,7 @@ Instructions for installing from source, Python version support ---------------------- -Officially Python 3.8, 3.9 and 3.10. +Officially Python 3.8, 3.9, 3.10 and 3.11. Installing pandas ----------------- diff --git a/pyproject.toml b/pyproject.toml index 0ce8cf87ab17e..da56b8d23f597 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ requires = [ "setuptools>=51.0.0", "wheel", "Cython>=0.29.32,<3", # Note: sync with setup.py, environment.yml and asv.conf.json - "oldest-supported-numpy>=0.10" + "oldest-supported-numpy>=2022.8.16" ] # uncomment to enable pep517 after versioneer problem is fixed. # https://github.com/python-versioneer/python-versioneer/issues/193 diff --git a/setup.cfg b/setup.cfg index d80d09725d18b..5680db30ec50d 100644 --- a/setup.cfg +++ b/setup.cfg @@ -22,6 +22,7 @@ classifiers = Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 + Programming Language :: Python :: 3.11 Topic :: Scientific/Engineering project_urls = Bug Tracker = https://github.com/pandas-dev/pandas/issues @@ -33,6 +34,7 @@ packages = find: install_requires = numpy>=1.20.3; python_version<'3.10' numpy>=1.21.0; python_version>='3.10' + numpy>=1.23.2; python_version>='3.11' python-dateutil>=2.8.2 pytz>=2020.1 python_requires = >=3.8
- [x] closes #49301 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49320
2022-10-25T23:34:59Z
2022-10-31T18:50:49Z
2022-10-31T18:50:49Z
2023-01-12T11:54:06Z
DEPR: stop inferring dt64/td64 from strings in Series construtor
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 4c85b3d5dc745..b8a7775e6066e 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -232,6 +232,7 @@ Removal of prior version deprecations/changes - Removed the ``display.column_space`` option in favor of ``df.to_string(col_space=...)`` (:issue:`47280`) - Removed the deprecated method ``mad`` from pandas classes (:issue:`11787`) - Removed the deprecated method ``tshift`` from pandas classes (:issue:`11631`) +- Changed the behavior of :class:`Series` constructor, it will no longer infer a datetime64 or timedelta64 dtype from string entries (:issue:`41731`) - Changed behavior of :class:`Index` constructor when passed a ``SparseArray`` or ``SparseDtype`` to retain that dtype instead of casting to ``numpy.ndarray`` (:issue:`43930`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi index 244d1dbe4730e..6d7f895f7f730 100644 --- a/pandas/_libs/lib.pyi +++ b/pandas/_libs/lib.pyi @@ -158,7 +158,7 @@ def ensure_string_array( ) -> npt.NDArray[np.object_]: ... def infer_datetimelike_array( arr: npt.NDArray[np.object_], -) -> tuple[str, bool]: ... +) -> str: ... def convert_nans_to_NA( arr: npt.NDArray[np.object_], ) -> npt.NDArray[np.object_]: ... diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 4151ba927adf0..188b531b2b469 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -95,7 +95,6 @@ from pandas._libs.util cimport ( is_nan, ) -from pandas._libs.tslib import array_to_datetime from pandas._libs.tslibs import ( OutOfBoundsDatetime, OutOfBoundsTimedelta, @@ -1583,25 +1582,19 @@ def infer_datetimelike_array(arr: ndarray[object]) -> tuple[str, bool]: Returns ------- str: {datetime, timedelta, date, nat, mixed} - bool """ cdef: Py_ssize_t i, n = len(arr) bint seen_timedelta = False, seen_date = False, seen_datetime = False bint seen_tz_aware = False, seen_tz_naive = False - bint seen_nat = False, seen_str = False + bint seen_nat = False bint seen_period = False, seen_interval = False - list objs = [] object v for i in range(n): v = arr[i] if isinstance(v, str): - objs.append(v) - seen_str = True - - if len(objs) == 3: - break + return "mixed" elif v is None or util.is_nan(v): # nan or None @@ -1619,7 +1612,7 @@ def infer_datetimelike_array(arr: ndarray[object]) -> tuple[str, bool]: seen_tz_aware = True if seen_tz_naive and seen_tz_aware: - return "mixed", seen_str + return "mixed" elif util.is_datetime64_object(v): # np.datetime64 seen_datetime = True @@ -1635,43 +1628,30 @@ def infer_datetimelike_array(arr: ndarray[object]) -> tuple[str, bool]: seen_interval = True break else: - return "mixed", seen_str + return "mixed" if seen_period: if is_period_array(arr): - return "period", seen_str - return "mixed", seen_str + return "period" + return "mixed" if seen_interval: if is_interval_array(arr): - return "interval", seen_str - return "mixed", seen_str + return "interval" + return "mixed" if seen_date and not (seen_datetime or seen_timedelta): - return "date", seen_str + return "date" elif seen_datetime and not seen_timedelta: - return "datetime", seen_str + return "datetime" elif seen_timedelta and not seen_datetime: - return "timedelta", seen_str + return "timedelta" + elif seen_datetime and seen_timedelta: + return "mixed" elif seen_nat: - return "nat", seen_str + return "nat" - # short-circuit by trying to - # actually convert these strings - # this is for performance as we don't need to try - # convert *every* string array - if len(objs): - try: - # require_iso8601 as in maybe_infer_to_datetimelike - array_to_datetime(objs, errors="raise", require_iso8601=True) - return "datetime", seen_str - except (ValueError, TypeError): - pass - - # we are *not* going to infer from strings - # for timedelta as too much ambiguity - - return "mixed", seen_str + return "mixed" cdef inline bint is_timedelta(object o): diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index ec313f91d2721..cabd85aed1bbe 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1264,7 +1264,9 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: else: return td_values.reshape(shape) - inferred_type, seen_str = lib.infer_datetimelike_array(ensure_object(v)) + # TODO: can we just do lib.maybe_convert_objects for this entire function? + inferred_type = lib.infer_datetimelike_array(ensure_object(v)) + if inferred_type in ["period", "interval"]: # Incompatible return value type (got "Union[ExtensionArray, ndarray]", # expected "Union[ndarray, DatetimeArray, TimedeltaArray, PeriodArray, @@ -1280,6 +1282,7 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: elif inferred_type == "timedelta": value = try_timedelta(v) elif inferred_type == "nat": + # only reached if we have at least 1 NaT and the rest (NaT or None or np.nan) # if all NaT, return as datetime if isna(v).all(): @@ -1287,7 +1290,6 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: # "ExtensionArray", variable has type "Union[ndarray, List[Any]]") value = try_datetime(v) # type: ignore[assignment] else: - # We have at least a NaT and a string # try timedelta first to avoid spurious datetime conversions # e.g. '00:00:01' is a timedelta but technically is also a datetime @@ -1300,15 +1302,6 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: # "ExtensionArray", variable has type "Union[ndarray, List[Any]]") value = try_datetime(v) # type: ignore[assignment] - if value.dtype.kind in ["m", "M"] and seen_str: - # TODO(2.0): enforcing this deprecation should close GH#40111 - warnings.warn( - f"Inferring {value.dtype} from data containing strings is deprecated " - "and will be removed in a future version. To retain the old behavior " - f"explicitly pass Series(data, dtype={value.dtype})", - FutureWarning, - stacklevel=find_stack_level(), - ) return value diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index 44773f13276c0..5b54ac56d48c8 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -775,7 +775,7 @@ def _infer_types( result = BooleanArray(result, bool_mask) elif result.dtype == np.object_ and use_nullable_dtypes: # read_excel sends array of datetime objects - inferred_type, _ = lib.infer_datetimelike_array(result) + inferred_type = lib.infer_datetimelike_array(result) if inferred_type != "datetime": result = StringDtype().construct_array_type()._from_sequence(values) diff --git a/pandas/tests/apply/test_series_apply.py b/pandas/tests/apply/test_series_apply.py index 5221c41ce35d5..b67af8c521090 100644 --- a/pandas/tests/apply/test_series_apply.py +++ b/pandas/tests/apply/test_series_apply.py @@ -859,8 +859,7 @@ def test_apply_to_timedelta(): list_of_strings = ["00:00:01", np.nan, pd.NaT, pd.NaT] a = pd.to_timedelta(list_of_strings) - with tm.assert_produces_warning(FutureWarning, match="Inferring timedelta64"): - ser = Series(list_of_strings) + ser = Series(list_of_strings) b = ser.apply(pd.to_timedelta) tm.assert_series_equal(Series(a), b) diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 56c97ac7a4dc5..e1d16fed73a88 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -1346,7 +1346,7 @@ def test_infer_dtype_period_with_na(self, na_value): ], ) def test_infer_datetimelike_array_datetime(self, data): - assert lib.infer_datetimelike_array(data) == ("datetime", False) + assert lib.infer_datetimelike_array(data) == "datetime" @pytest.mark.parametrize( "data", @@ -1358,11 +1358,11 @@ def test_infer_datetimelike_array_datetime(self, data): ], ) def test_infer_datetimelike_array_timedelta(self, data): - assert lib.infer_datetimelike_array(data) == ("timedelta", False) + assert lib.infer_datetimelike_array(data) == "timedelta" def test_infer_datetimelike_array_date(self): arr = [date(2017, 6, 12), date(2017, 3, 11)] - assert lib.infer_datetimelike_array(arr) == ("date", False) + assert lib.infer_datetimelike_array(arr) == "date" @pytest.mark.parametrize( "data", @@ -1377,7 +1377,7 @@ def test_infer_datetimelike_array_date(self): ], ) def test_infer_datetimelike_array_mixed(self, data): - assert lib.infer_datetimelike_array(data)[0] == "mixed" + assert lib.infer_datetimelike_array(data) == "mixed" @pytest.mark.parametrize( "first, expected", @@ -1395,7 +1395,7 @@ def test_infer_datetimelike_array_mixed(self, data): @pytest.mark.parametrize("second", [None, np.nan]) def test_infer_datetimelike_array_nan_nat_like(self, first, second, expected): first.append(second) - assert lib.infer_datetimelike_array(first) == (expected, False) + assert lib.infer_datetimelike_array(first) == expected def test_infer_dtype_all_nan_nat_like(self): arr = np.array([np.nan, np.nan]) diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py index 4498f11d77313..7ec3c81de235c 100644 --- a/pandas/tests/resample/test_time_grouper.py +++ b/pandas/tests/resample/test_time_grouper.py @@ -321,29 +321,27 @@ def test_groupby_resample_interpolate(): .interpolate(method="linear") ) - msg = "containing strings is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected_ind = pd.MultiIndex.from_tuples( - [ - (50, "2018-01-07"), - (50, Timestamp("2018-01-08")), - (50, Timestamp("2018-01-09")), - (50, Timestamp("2018-01-10")), - (50, Timestamp("2018-01-11")), - (50, Timestamp("2018-01-12")), - (50, Timestamp("2018-01-13")), - (50, Timestamp("2018-01-14")), - (50, Timestamp("2018-01-15")), - (50, Timestamp("2018-01-16")), - (50, Timestamp("2018-01-17")), - (50, Timestamp("2018-01-18")), - (50, Timestamp("2018-01-19")), - (50, Timestamp("2018-01-20")), - (50, Timestamp("2018-01-21")), - (60, Timestamp("2018-01-14")), - ], - names=["volume", "week_starting"], - ) + expected_ind = pd.MultiIndex.from_tuples( + [ + (50, Timestamp("2018-01-07")), + (50, Timestamp("2018-01-08")), + (50, Timestamp("2018-01-09")), + (50, Timestamp("2018-01-10")), + (50, Timestamp("2018-01-11")), + (50, Timestamp("2018-01-12")), + (50, Timestamp("2018-01-13")), + (50, Timestamp("2018-01-14")), + (50, Timestamp("2018-01-15")), + (50, Timestamp("2018-01-16")), + (50, Timestamp("2018-01-17")), + (50, Timestamp("2018-01-18")), + (50, Timestamp("2018-01-19")), + (50, Timestamp("2018-01-20")), + (50, Timestamp("2018-01-21")), + (60, Timestamp("2018-01-14")), + ], + names=["volume", "week_starting"], + ) expected = DataFrame( data={ diff --git a/pandas/tests/series/methods/test_combine_first.py b/pandas/tests/series/methods/test_combine_first.py index b838797b5f9b9..1d104b12ce7d2 100644 --- a/pandas/tests/series/methods/test_combine_first.py +++ b/pandas/tests/series/methods/test_combine_first.py @@ -79,9 +79,7 @@ def test_combine_first_dt64(self): s1 = Series([np.NaN, "2011"]) rs = s0.combine_first(s1) - msg = "containing strings is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - xp = Series([datetime(2010, 1, 1), "2011"]) + xp = Series([datetime(2010, 1, 1), "2011"], dtype="datetime64[ns]") tm.assert_series_equal(rs, xp) diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index 26416c7a2b483..409a3b231fa95 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -365,10 +365,7 @@ def test_datetime64_fillna(self): def test_datetime64_fillna_backfill(self): # GH#6587 # make sure that we are treating as integer when filling - msg = "containing strings is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - # this also tests inference of a datetime-like with NaT's - ser = Series([NaT, NaT, "2013-08-05 15:30:00.000001"]) + ser = Series([NaT, NaT, "2013-08-05 15:30:00.000001"], dtype="M8[ns]") expected = Series( [ diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 35ebd152f447c..eccf6c9c92ea1 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1018,24 +1018,20 @@ def test_constructor_dtype_datetime64_7(self): assert series1.dtype == object def test_constructor_dtype_datetime64_6(self): - # these will correctly infer a datetime - msg = "containing strings is deprecated" + # as of 2.0, these no longer infer datetime64 based on the strings, + # matching the Index behavior - with tm.assert_produces_warning(FutureWarning, match=msg): - ser = Series([None, NaT, "2013-08-05 15:30:00.000001"]) - assert ser.dtype == "datetime64[ns]" + ser = Series([None, NaT, "2013-08-05 15:30:00.000001"]) + assert ser.dtype == object - with tm.assert_produces_warning(FutureWarning, match=msg): - ser = Series([np.nan, NaT, "2013-08-05 15:30:00.000001"]) - assert ser.dtype == "datetime64[ns]" + ser = Series([np.nan, NaT, "2013-08-05 15:30:00.000001"]) + assert ser.dtype == object - with tm.assert_produces_warning(FutureWarning, match=msg): - ser = Series([NaT, None, "2013-08-05 15:30:00.000001"]) - assert ser.dtype == "datetime64[ns]" + ser = Series([NaT, None, "2013-08-05 15:30:00.000001"]) + assert ser.dtype == object - with tm.assert_produces_warning(FutureWarning, match=msg): - ser = Series([NaT, np.nan, "2013-08-05 15:30:00.000001"]) - assert ser.dtype == "datetime64[ns]" + ser = Series([NaT, np.nan, "2013-08-05 15:30:00.000001"]) + assert ser.dtype == object def test_constructor_dtype_datetime64_5(self): # tz-aware (UTC and other tz's) @@ -1517,23 +1513,19 @@ def test_constructor_dtype_timedelta64(self): td = Series([timedelta(days=i) for i in range(3)] + ["foo"]) assert td.dtype == "object" - # these will correctly infer a timedelta - msg = "containing strings is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - ser = Series([None, NaT, "1 Day"]) - assert ser.dtype == "timedelta64[ns]" + # as of 2.0, these no longer infer timedelta64 based on the strings, + # matching Index behavior + ser = Series([None, NaT, "1 Day"]) + assert ser.dtype == object - with tm.assert_produces_warning(FutureWarning, match=msg): - ser = Series([np.nan, NaT, "1 Day"]) - assert ser.dtype == "timedelta64[ns]" + ser = Series([np.nan, NaT, "1 Day"]) + assert ser.dtype == object - with tm.assert_produces_warning(FutureWarning, match=msg): - ser = Series([NaT, None, "1 Day"]) - assert ser.dtype == "timedelta64[ns]" + ser = Series([NaT, None, "1 Day"]) + assert ser.dtype == object - with tm.assert_produces_warning(FutureWarning, match=msg): - ser = Series([NaT, np.nan, "1 Day"]) - assert ser.dtype == "timedelta64[ns]" + ser = Series([NaT, np.nan, "1 Day"]) + assert ser.dtype == object # GH 16406 def test_constructor_mixed_tz(self): diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py index fd808328ef386..60d54a48965df 100644 --- a/pandas/tests/tools/test_to_timedelta.py +++ b/pandas/tests/tools/test_to_timedelta.py @@ -207,9 +207,7 @@ def test_to_timedelta_on_missing_values(self): ) tm.assert_series_equal(actual, expected) - with tm.assert_produces_warning(FutureWarning, match="Inferring timedelta64"): - ser = Series(["00:00:01", pd.NaT]) - assert ser.dtype == "m8[ns]" + ser = Series(["00:00:01", pd.NaT], dtype="m8[ns]") actual = to_timedelta(ser) tm.assert_series_equal(actual, expected)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49319
2022-10-25T21:54:52Z
2022-10-26T17:00:02Z
2022-10-26T17:00:02Z
2022-10-26T17:01:04Z
DEPR: Disallow groupby __getitem__ with tuple
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 8a628dbce3ca7..a10e99c13e548 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -227,6 +227,7 @@ Removal of prior version deprecations/changes - Removed ``pandas.SparseArray`` in favor of :class:`arrays.SparseArray` (:issue:`30642`) - Removed ``pandas.SparseSeries`` and ``pandas.SparseDataFrame`` (:issue:`30642`) - Enforced disallowing a string column label into ``times`` in :meth:`DataFrame.ewm` (:issue:`43265`) +- Enforced disallowing a tuple of column labels into :meth:`.DataFrameGroupBy.__getitem__` (:issue:`30546`) - Removed setting Categorical._codes directly (:issue:`41429`) - Enforced :meth:`Rolling.count` with ``min_periods=None`` to default to the size of the window (:issue:`31302`) - Enforced the ``display.max_colwidth`` option to not accept negative integers (:issue:`31569`) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 109227633cfdd..4c06ee60d3f6a 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1595,12 +1595,10 @@ def __getitem__(self, key) -> DataFrameGroupBy | SeriesGroupBy: # per GH 23566 if isinstance(key, tuple) and len(key) > 1: # if len == 1, then it becomes a SeriesGroupBy and this is actually - # valid syntax, so don't raise warning - warnings.warn( - "Indexing with multiple keys (implicitly converted to a tuple " - "of keys) will be deprecated, use a list instead.", - FutureWarning, - stacklevel=find_stack_level(), + # valid syntax, so don't raise + raise ValueError( + "Cannot subset columns with a tuple with more than one element. " + "Use a list instead." ) return super().__getitem__(key) diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 728575a80f32f..1c8b8e3d33ecf 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -102,13 +102,13 @@ def test_getitem_numeric_column_names(self): tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected) - # per GH 23566 this should raise a FutureWarning - with tm.assert_produces_warning(FutureWarning): + # per GH 23566 enforced deprecation raises a ValueError + with pytest.raises(ValueError, match="Cannot subset columns with a tuple"): df.groupby(0)[2, 4].mean() - def test_getitem_single_list_of_columns(self, df): - # per GH 23566 this should raise a FutureWarning - with tm.assert_produces_warning(FutureWarning): + def test_getitem_single_tuple_of_columns_raises(self, df): + # per GH 23566 enforced deprecation raises a ValueError + with pytest.raises(ValueError, match="Cannot subset columns with a tuple"): df.groupby("A")["C", "D"].mean() def test_getitem_single_column(self):
Introduced in https://github.com/pandas-dev/pandas/pull/30546
https://api.github.com/repos/pandas-dev/pandas/pulls/49317
2022-10-25T21:48:23Z
2022-10-26T09:34:00Z
2022-10-26T09:34:00Z
2022-10-26T15:38:00Z
DEPR: Remove SparseDataFrame/Series pickle compat
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 8a628dbce3ca7..5d830afc9f74a 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -225,7 +225,7 @@ Removal of prior version deprecations/changes - Removed ``pandas.util.testing`` in favor of ``pandas.testing`` (:issue:`30745`) - Removed :meth:`Series.str.__iter__` (:issue:`28277`) - Removed ``pandas.SparseArray`` in favor of :class:`arrays.SparseArray` (:issue:`30642`) -- Removed ``pandas.SparseSeries`` and ``pandas.SparseDataFrame`` (:issue:`30642`) +- Removed ``pandas.SparseSeries`` and ``pandas.SparseDataFrame``, including pickle support. (:issue:`30642`) - Enforced disallowing a string column label into ``times`` in :meth:`DataFrame.ewm` (:issue:`43265`) - Removed setting Categorical._codes directly (:issue:`41429`) - Enforced :meth:`Rolling.count` with ``min_periods=None`` to default to the size of the window (:issue:`31302`) diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py index c233e3d8a4892..051aa5c337782 100644 --- a/pandas/compat/pickle_compat.py +++ b/pandas/compat/pickle_compat.py @@ -7,11 +7,7 @@ import copy import io import pickle as pkl -from typing import ( - TYPE_CHECKING, - Generator, -) -import warnings +from typing import Generator import numpy as np @@ -26,12 +22,6 @@ ) from pandas.core.internals import BlockManager -if TYPE_CHECKING: - from pandas import ( - DataFrame, - Series, - ) - def load_reduce(self): stack = self.stack @@ -68,49 +58,6 @@ def load_reduce(self): raise -_sparse_msg = """\ - -Loading a saved '{cls}' as a {new} with sparse values. -'{cls}' is now removed. You should re-save this dataset in its new format. -""" - - -class _LoadSparseSeries: - # To load a SparseSeries as a Series[Sparse] - - # https://github.com/python/mypy/issues/1020 - # error: Incompatible return type for "__new__" (returns "Series", but must return - # a subtype of "_LoadSparseSeries") - def __new__(cls) -> Series: # type: ignore[misc] - from pandas import Series - - warnings.warn( - _sparse_msg.format(cls="SparseSeries", new="Series"), - FutureWarning, - stacklevel=6, - ) - - return Series(dtype=object) - - -class _LoadSparseFrame: - # To load a SparseDataFrame as a DataFrame[Sparse] - - # https://github.com/python/mypy/issues/1020 - # error: Incompatible return type for "__new__" (returns "DataFrame", but must - # return a subtype of "_LoadSparseFrame") - def __new__(cls) -> DataFrame: # type: ignore[misc] - from pandas import DataFrame - - warnings.warn( - _sparse_msg.format(cls="SparseDataFrame", new="DataFrame"), - FutureWarning, - stacklevel=6, - ) - - return DataFrame() - - # If classes are moved, provide compat here. _class_locations_map = { ("pandas.core.sparse.array", "SparseArray"): ("pandas.core.arrays", "SparseArray"), @@ -144,14 +91,6 @@ def __new__(cls) -> DataFrame: # type: ignore[misc] "pandas.core.arrays.sparse", "SparseArray", ), - ("pandas.sparse.series", "SparseSeries"): ( - "pandas.compat.pickle_compat", - "_LoadSparseSeries", - ), - ("pandas.sparse.frame", "SparseDataFrame"): ( - "pandas.core.sparse.frame", - "_LoadSparseFrame", - ), ("pandas.indexes.base", "_new_Index"): ("pandas.core.indexes.base", "_new_Index"), ("pandas.indexes.base", "Index"): ("pandas.core.indexes.base", "Index"), ("pandas.indexes.numeric", "Int64Index"): ( @@ -183,14 +122,6 @@ def __new__(cls) -> DataFrame: # type: ignore[misc] "pandas.core.indexes.numeric", "Float64Index", ), - ("pandas.core.sparse.series", "SparseSeries"): ( - "pandas.compat.pickle_compat", - "_LoadSparseSeries", - ), - ("pandas.core.sparse.frame", "SparseDataFrame"): ( - "pandas.compat.pickle_compat", - "_LoadSparseFrame", - ), } diff --git a/pandas/tests/io/data/legacy_pickle/0.20.3/0.20.3_x86_64_darwin_3.5.2.pickle b/pandas/tests/io/data/legacy_pickle/0.20.3/0.20.3_x86_64_darwin_3.5.2.pickle deleted file mode 100644 index 9777319465de6..0000000000000 Binary files a/pandas/tests/io/data/legacy_pickle/0.20.3/0.20.3_x86_64_darwin_3.5.2.pickle and /dev/null differ diff --git a/pandas/tests/io/data/legacy_pickle/0.20.3/0.20.3_x86_64_darwin_3.5.6.pickle b/pandas/tests/io/data/legacy_pickle/0.20.3/0.20.3_x86_64_darwin_3.5.6.pickle deleted file mode 100644 index 88bb6989f5b08..0000000000000 Binary files a/pandas/tests/io/data/legacy_pickle/0.20.3/0.20.3_x86_64_darwin_3.5.6.pickle and /dev/null differ diff --git a/pandas/tests/io/data/pickle/sparseframe-0.20.3.pickle.gz b/pandas/tests/io/data/pickle/sparseframe-0.20.3.pickle.gz deleted file mode 100644 index f4ff0dbaa1ff9..0000000000000 Binary files a/pandas/tests/io/data/pickle/sparseframe-0.20.3.pickle.gz and /dev/null differ diff --git a/pandas/tests/io/data/pickle/sparseseries-0.20.3.pickle.gz b/pandas/tests/io/data/pickle/sparseseries-0.20.3.pickle.gz deleted file mode 100644 index b299e7d85808e..0000000000000 Binary files a/pandas/tests/io/data/pickle/sparseseries-0.20.3.pickle.gz and /dev/null differ diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index d78cb9e46cd1a..5115a33694207 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -254,28 +254,6 @@ def test_pickle_path_localpath(): tm.assert_frame_equal(df, result) -@pytest.mark.parametrize("typ", ["sparseseries", "sparseframe"]) -def test_legacy_sparse_warning(datapath, typ): - """ - - Generated with - - >>> df = pd.DataFrame({"A": [1, 2, 3, 4], "B": [0, 0, 1, 1]}).to_sparse() - >>> df.to_pickle("pandas/tests/io/data/pickle/sparseframe-0.20.3.pickle.gz", - ... compression="gzip") - - >>> s = df['B'] - >>> s.to_pickle("pandas/tests/io/data/pickle/sparseseries-0.20.3.pickle.gz", - ... compression="gzip") - """ - with tm.assert_produces_warning(FutureWarning): - simplefilter("ignore", DeprecationWarning) # from boto - pd.read_pickle( - datapath("io", "data", "pickle", f"{typ}-0.20.3.pickle.gz"), - compression="gzip", - ) - - # --------------------- # test pickle compression # ---------------------
Follow up to https://github.com/pandas-dev/pandas/pull/49218 Also some pickles generated with 0.20.3 contained these objects, so thought to remove since the pandas version is very old
https://api.github.com/repos/pandas-dev/pandas/pulls/49316
2022-10-25T21:32:48Z
2022-10-26T17:29:29Z
2022-10-26T17:29:28Z
2023-10-28T18:56:31Z
DEPR: Remove sort_columns in plotting
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 8a628dbce3ca7..6725a3f466b62 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -189,6 +189,7 @@ Removal of prior version deprecations/changes - Removed argument ``how`` from :meth:`PeriodIndex.astype`, use :meth:`PeriodIndex.to_timestamp` instead (:issue:`37982`) - Removed argument ``try_cast`` from :meth:`DataFrame.mask`, :meth:`DataFrame.where`, :meth:`Series.mask` and :meth:`Series.where` (:issue:`38836`) - Removed argument ``tz`` from :meth:`Period.to_timestamp`, use ``obj.to_timestamp(...).tz_localize(tz)`` instead (:issue:`34522`) +- Removed argument ``sort_columns`` in :meth:`DataFrame.plot` and :meth:`Series.plot` (:issue:`47563`) - Removed argument ``is_copy`` from :meth:`DataFrame.take` and :meth:`Series.take` (:issue:`30615`) - Removed argument ``kind`` from :meth:`Index.get_slice_bound`, :meth:`Index.slice_indexer` and :meth:`Index.slice_locs` (:issue:`41378`) - Removed argument ``inplace`` from :meth:`Categorical.remove_unused_categories` (:issue:`37918`) diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index e340ea31deef4..036d2c84f006e 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -1,13 +1,11 @@ from __future__ import annotations import importlib -import itertools import types from typing import ( TYPE_CHECKING, Sequence, ) -import warnings from pandas._config import get_option @@ -16,7 +14,6 @@ Appender, Substitution, ) -from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_integer, @@ -760,13 +757,6 @@ class PlotAccessor(PandasObject): Equivalent to yerr. stacked : bool, default False in line and bar plots, and True in area plot If True, create stacked plot. - sort_columns : bool, default False - Sort column names to determine plot ordering. - - .. deprecated:: 1.5.0 - The `sort_columns` arguments is deprecated and will be removed in a - future version. - secondary_y : bool or sequence, default False Whether to plot on the secondary y-axis if a list/tuple, which columns to plot on secondary y-axis. @@ -877,7 +867,6 @@ def _get_call_args(backend_name, data, args, kwargs): ("yerr", None), ("xerr", None), ("secondary_y", False), - ("sort_columns", False), ("xlabel", None), ("ylabel", None), ] @@ -887,14 +876,6 @@ def _get_call_args(backend_name, data, args, kwargs): "expected Series or DataFrame" ) - if "sort_columns" in itertools.chain(args, kwargs.keys()): - warnings.warn( - "`sort_columns` is deprecated and will be removed in a future " - "version.", - FutureWarning, - stacklevel=find_stack_level(), - ) - if args and isinstance(data, ABCSeries): positional_args = str(args)[1:-1] keyword_args = ", ".join( diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 5c3a79927ec2f..9bcb51a7b032a 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -138,7 +138,6 @@ def __init__( yticks=None, xlabel: Hashable | None = None, ylabel: Hashable | None = None, - sort_columns: bool = False, fontsize=None, secondary_y: bool | tuple | list | np.ndarray = False, colormap=None, @@ -184,7 +183,6 @@ def __init__( self.kind = kind - self.sort_columns = sort_columns self.subplots = self._validate_subplots_kwarg(subplots) if sharex is None: diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index 44f57b02d0f0a..455bc177d43e2 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -76,8 +76,6 @@ def test_plot(self): ax = _check_plot_works(df.plot, use_index=True) self._check_ticks_props(ax, xrot=0) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - _check_plot_works(df.plot, sort_columns=False) _check_plot_works(df.plot, yticks=[1, 5, 10]) _check_plot_works(df.plot, xticks=[1, 5, 10]) _check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100)) @@ -2232,19 +2230,6 @@ def test_secondary_y(self, secondary_y): assert ax.get_ylim() == (0, 100) assert ax.get_yticks()[0] == 99 - def test_sort_columns_deprecated(self): - # GH 47563 - df = DataFrame({"a": [1, 2], "b": [3, 4]}) - - with tm.assert_produces_warning(FutureWarning): - df.plot.box("a", sort_columns=True) - - with tm.assert_produces_warning(FutureWarning): - df.plot.box(sort_columns=False) - - with tm.assert_produces_warning(False): - df.plot.box("a") - def _generate_4_axes_via_gridspec(): import matplotlib as mpl
Introduced in https://github.com/pandas-dev/pandas/pull/48073
https://api.github.com/repos/pandas-dev/pandas/pulls/49315
2022-10-25T21:20:31Z
2022-10-26T09:33:09Z
2022-10-26T09:33:09Z
2022-10-26T15:37:32Z
DEPR: Remove get_offset, infer_freq warn param
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 4c85b3d5dc745..0bf61e7fa9b78 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -217,6 +217,8 @@ Removal of prior version deprecations/changes - Remove :meth:`DataFrameGroupBy.pad` and :meth:`DataFrameGroupBy.backfill` (:issue:`45076`) - Remove ``numpy`` argument from :func:`read_json` (:issue:`30636`) - Disallow passing abbreviations for ``orient`` in :meth:`DataFrame.to_dict` (:issue:`32516`) +- Removed ``get_offset`` in favor of :func:`to_offset` (:issue:`30340`) +- Removed the ``warn`` keyword in :func:`infer_freq` (:issue:`45947`) - Removed the ``center`` keyword in :meth:`DataFrame.expanding` (:issue:`20647`) - Removed the ``truediv`` keyword from :func:`eval` (:issue:`29812`) - Removed the ``pandas.datetime`` submodule (:issue:`30489`) diff --git a/pandas/tests/tseries/frequencies/test_inference.py b/pandas/tests/tseries/frequencies/test_inference.py index ea9a09ff2d65c..eebed6a4c27d3 100644 --- a/pandas/tests/tseries/frequencies/test_inference.py +++ b/pandas/tests/tseries/frequencies/test_inference.py @@ -10,6 +10,7 @@ DAYS, MONTHS, ) +from pandas._libs.tslibs.offsets import _get_offset from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG from pandas.compat import is_platform_windows @@ -447,7 +448,7 @@ def test_series_datetime_index(freq): @pytest.mark.parametrize( "offset_func", [ - frequencies._get_offset, + _get_offset, lambda freq: date_range("2011-01-01", periods=5, freq=freq), ], ) @@ -507,18 +508,13 @@ def test_legacy_offset_warnings(offset_func, freq): def test_ms_vs_capital_ms(): - left = frequencies._get_offset("ms") - right = frequencies._get_offset("MS") + left = _get_offset("ms") + right = _get_offset("MS") assert left == offsets.Milli() assert right == offsets.MonthBegin() -def test_infer_freq_warn_deprecated(): - with tm.assert_produces_warning(FutureWarning): - frequencies.infer_freq(date_range(2022, periods=3), warn=False) - - def test_infer_freq_non_nano(): arr = np.arange(10).astype(np.int64).view("M8[s]") dta = DatetimeArray._simple_new(arr, dtype=arr.dtype) diff --git a/pandas/tests/tseries/offsets/test_fiscal.py b/pandas/tests/tseries/offsets/test_fiscal.py index d0801b2cede29..26937c348d9c8 100644 --- a/pandas/tests/tseries/offsets/test_fiscal.py +++ b/pandas/tests/tseries/offsets/test_fiscal.py @@ -6,17 +6,13 @@ from dateutil.relativedelta import relativedelta import pytest -from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG - from pandas import Timestamp -import pandas._testing as tm from pandas.tests.tseries.offsets.common import ( WeekDay, assert_is_on_offset, assert_offset_equal, ) -from pandas.tseries.frequencies import get_offset from pandas.tseries.offsets import ( FY5253, FY5253Quarter, @@ -54,46 +50,6 @@ def test_get_offset_name(): ) -def test_get_offset(): - with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): - with tm.assert_produces_warning(FutureWarning): - get_offset("gibberish") - with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): - with tm.assert_produces_warning(FutureWarning): - get_offset("QS-JAN-B") - - pairs = [ - ("RE-N-DEC-MON", makeFY5253NearestEndMonth(weekday=0, startingMonth=12)), - ("RE-L-DEC-TUE", makeFY5253LastOfMonth(weekday=1, startingMonth=12)), - ( - "REQ-L-MAR-TUE-4", - makeFY5253LastOfMonthQuarter( - weekday=1, startingMonth=3, qtr_with_extra_week=4 - ), - ), - ( - "REQ-L-DEC-MON-3", - makeFY5253LastOfMonthQuarter( - weekday=0, startingMonth=12, qtr_with_extra_week=3 - ), - ), - ( - "REQ-N-DEC-MON-3", - makeFY5253NearestEndMonthQuarter( - weekday=0, startingMonth=12, qtr_with_extra_week=3 - ), - ), - ] - - for name, expected in pairs: - with tm.assert_produces_warning(FutureWarning): - offset = get_offset(name) - assert offset == expected, ( - f"Expected {repr(name)} to yield {repr(expected)} " - f"(actual: {repr(offset)})" - ) - - class TestFY5253LastOfMonth: offset_lom_sat_aug = makeFY5253LastOfMonth(1, startingMonth=8, weekday=WeekDay.SAT) offset_lom_sat_sep = makeFY5253LastOfMonth(1, startingMonth=9, weekday=WeekDay.SAT) diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index a7fe2da703908..1cf9fb9a85b37 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -1,7 +1,5 @@ from __future__ import annotations -import warnings - import numpy as np from pandas._libs.algos import unique_deltas @@ -23,16 +21,13 @@ month_position_check, ) from pandas._libs.tslibs.offsets import ( - BaseOffset, DateOffset, Day, - _get_offset, to_offset, ) from pandas._libs.tslibs.parsing import get_rule_month from pandas._typing import npt from pandas.util._decorators import cache_readonly -from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_datetime64_dtype, @@ -102,30 +97,11 @@ def get_period_alias(offset_str: str) -> str | None: return _offset_to_period_map.get(offset_str, None) -def get_offset(name: str) -> BaseOffset: - """ - Return DateOffset object associated with rule name. - - .. deprecated:: 1.0.0 - - Examples - -------- - get_offset('EOM') --> BMonthEnd(1) - """ - warnings.warn( - "get_offset is deprecated and will be removed in a future version, " - "use to_offset instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - return _get_offset(name) - - # --------------------------------------------------------------------- # Period codes -def infer_freq(index, warn: bool = True) -> str | None: +def infer_freq(index) -> str | None: """ Infer the most likely frequency given the input index. @@ -133,8 +109,6 @@ def infer_freq(index, warn: bool = True) -> str | None: ---------- index : DatetimeIndex or TimedeltaIndex If passed a Series will use the values of the series (NOT THE INDEX). - warn : bool, default True - .. deprecated:: 1.5.0 Returns ------- @@ -186,7 +160,7 @@ def infer_freq(index, warn: bool = True) -> str | None: ) elif is_timedelta64_dtype(index.dtype): # Allow TimedeltaIndex and TimedeltaArray - inferer = _TimedeltaFrequencyInferer(index, warn=warn) + inferer = _TimedeltaFrequencyInferer(index) return inferer.get_freq() if isinstance(index, Index) and not isinstance(index, DatetimeIndex): @@ -199,7 +173,7 @@ def infer_freq(index, warn: bool = True) -> str | None: if not isinstance(index, DatetimeIndex): index = DatetimeIndex(index) - inferer = _FrequencyInferer(index, warn=warn) + inferer = _FrequencyInferer(index) return inferer.get_freq() @@ -208,7 +182,7 @@ class _FrequencyInferer: Not sure if I can avoid the state machine here """ - def __init__(self, index, warn: bool = True) -> None: + def __init__(self, index) -> None: self.index = index self.i8values = index.asi8 @@ -230,15 +204,6 @@ def __init__(self, index, warn: bool = True) -> None: if index.tz is not None: self.i8values = tz_convert_from_utc(self.i8values, index.tz) - if warn is not True: - warnings.warn( - "warn is deprecated (and never implemented) and " - "will be removed in a future version.", - FutureWarning, - stacklevel=find_stack_level(), - ) - self.warn = warn - if len(index) < 3: raise ValueError("Need at least 3 dates to infer frequency") @@ -652,7 +617,6 @@ def _is_weekly(rule: str) -> bool: __all__ = [ "Day", - "get_offset", "get_period_alias", "infer_freq", "is_subperiod",
Introduced in https://github.com/pandas-dev/pandas/pull/30340, https://github.com/pandas-dev/pandas/pull/45947
https://api.github.com/repos/pandas-dev/pandas/pulls/49314
2022-10-25T21:03:25Z
2022-10-26T09:35:07Z
2022-10-26T09:35:07Z
2022-10-26T15:38:31Z
DEPR: DataFrame dtype keyword match Series behavior
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index cad0eb1012bb4..78ea78ec97a3a 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -252,6 +252,8 @@ Removal of prior version deprecations/changes - Removed the ``display.column_space`` option in favor of ``df.to_string(col_space=...)`` (:issue:`47280`) - Removed the deprecated method ``mad`` from pandas classes (:issue:`11787`) - Removed the deprecated method ``tshift`` from pandas classes (:issue:`11631`) +- Changed behavior of :class:`DataFrame` constructor given floating-point ``data`` and an integer ``dtype``, when the data cannot be cast losslessly, the floating point dtype is retained, matching :class:`Series` behavior (:issue:`41170`) +- Changed behavior of :class:`DataFrame` constructor when passed a ``dtype`` (other than int) that the data cannot be cast to; it now raises instead of silently ignoring the dtype (:issue:`41733`) - Changed the behavior of :class:`Series` constructor, it will no longer infer a datetime64 or timedelta64 dtype from string entries (:issue:`41731`) - Changed behavior of :class:`Index` constructor when passed a ``SparseArray`` or ``SparseDtype`` to retain that dtype instead of casting to ``numpy.ndarray`` (:issue:`43930`) diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 447006572f22d..c7db58fe8c6a3 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -500,7 +500,6 @@ def sanitize_array( index: Index | None, dtype: DtypeObj | None = None, copy: bool = False, - raise_cast_failure: bool = True, *, allow_2d: bool = False, ) -> ArrayLike: @@ -514,19 +513,12 @@ def sanitize_array( index : Index or None, default None dtype : np.dtype, ExtensionDtype, or None, default None copy : bool, default False - raise_cast_failure : bool, default True allow_2d : bool, default False If False, raise if we have a 2D Arraylike. Returns ------- np.ndarray or ExtensionArray - - Notes - ----- - raise_cast_failure=False is only intended to be True when called from the - DataFrame constructor, as the dtype keyword there may be interpreted as only - applying to a subset of columns, see GH#24435. """ if isinstance(data, ma.MaskedArray): data = sanitize_masked_array(data) @@ -564,7 +556,7 @@ def sanitize_array( # GH 47391 numpy > 1.24 will raise a RuntimeError for nan -> int # casting aligning with IntCastingNaNError below with np.errstate(invalid="ignore"): - subarr = _try_cast(data, dtype, copy, True) + subarr = _try_cast(data, dtype, copy) except IntCastingNaNError: warnings.warn( "In a future version, passing float-dtype values containing NaN " @@ -577,21 +569,10 @@ def sanitize_array( ) subarr = np.array(data, copy=copy) except ValueError: - if not raise_cast_failure: - # i.e. called via DataFrame constructor - warnings.warn( - "In a future version, passing float-dtype values and an " - "integer dtype to DataFrame will retain floating dtype " - "if they cannot be cast losslessly (matching Series behavior). " - "To retain the old behavior, use DataFrame(data).astype(dtype)", - FutureWarning, - stacklevel=find_stack_level(), - ) - # GH#40110 until the deprecation is enforced, we _dont_ - # ignore the dtype for DataFrame, and _do_ cast even though - # it is lossy. - dtype = cast(np.dtype, dtype) - return np.array(data, dtype=dtype, copy=copy) + # Pre-2.0, we would have different behavior for Series vs DataFrame. + # DataFrame would call np.array(data, dtype=dtype, copy=copy), + # which would cast to the integer dtype even if the cast is lossy. + # See GH#40110. # We ignore the dtype arg and return floating values, # e.g. test_constructor_floating_data_int_dtype @@ -599,7 +580,7 @@ def sanitize_array( subarr = np.array(data, copy=copy) else: # we will try to copy by-definition here - subarr = _try_cast(data, dtype, copy, raise_cast_failure) + subarr = _try_cast(data, dtype, copy) elif isinstance(data, ABCExtensionArray): # it is already ensured above this is not a PandasArray @@ -624,7 +605,7 @@ def sanitize_array( if dtype is not None or len(data) == 0: try: - subarr = _try_cast(data, dtype, copy, raise_cast_failure) + subarr = _try_cast(data, dtype, copy) except ValueError: if is_integer_dtype(dtype): casted = np.array(data, copy=False) @@ -636,7 +617,6 @@ def sanitize_array( index, dtype, copy=False, - raise_cast_failure=raise_cast_failure, allow_2d=allow_2d, ) else: @@ -750,7 +730,6 @@ def _try_cast( arr: list | np.ndarray, dtype: DtypeObj | None, copy: bool, - raise_cast_failure: bool, ) -> ArrayLike: """ Convert input to numpy ndarray and optionally cast to a given dtype. @@ -762,9 +741,6 @@ def _try_cast( dtype : np.dtype, ExtensionDtype or None copy : bool If False, don't copy the data if not needed. - raise_cast_failure : bool - If True, and if a dtype is specified, raise errors during casting. - Otherwise an object array is returned. Returns ------- @@ -823,35 +799,15 @@ def _try_cast( elif dtype.kind in ["m", "M"]: return maybe_cast_to_datetime(arr, dtype) - try: - # GH#15832: Check if we are requesting a numeric dtype and - # that we can convert the data to the requested dtype. - if is_integer_dtype(dtype): - # this will raise if we have e.g. floats + # GH#15832: Check if we are requesting a numeric dtype and + # that we can convert the data to the requested dtype. + elif is_integer_dtype(dtype): + # this will raise if we have e.g. floats + + subarr = maybe_cast_to_integer_array(arr, dtype) + else: + subarr = np.array(arr, dtype=dtype, copy=copy) - subarr = maybe_cast_to_integer_array(arr, dtype) - else: - # 4 tests fail if we move this to a try/except/else; see - # test_constructor_compound_dtypes, test_constructor_cast_failure - # test_constructor_dict_cast2, test_loc_setitem_dtype - subarr = np.array(arr, dtype=dtype, copy=copy) - - except (ValueError, TypeError): - if raise_cast_failure: - raise - else: - # we only get here with raise_cast_failure False, which means - # called via the DataFrame constructor - # GH#24435 - warnings.warn( - f"Could not cast to {dtype}, falling back to object. This " - "behavior is deprecated. In a future version, when a dtype is " - "passed to 'DataFrame', either all columns will be cast to that " - "dtype, or a TypeError will be raised.", - FutureWarning, - stacklevel=find_stack_level(), - ) - subarr = np.array(arr, dtype=object, copy=copy) return subarr diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 054663fcd0626..8f3c93259f0c6 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -331,14 +331,11 @@ def ndarray_to_mgr( if dtype is not None and not is_dtype_equal(values.dtype, dtype): # GH#40110 see similar check inside sanitize_array - rcf = not (is_integer_dtype(dtype) and values.dtype.kind == "f") - values = sanitize_array( values, None, dtype=dtype, copy=copy_on_sanitize, - raise_cast_failure=rcf, allow_2d=True, ) @@ -615,9 +612,7 @@ def _homogenize(data, index: Index, dtype: DtypeObj | None) -> list[ArrayLike]: val = dict(val) val = lib.fast_multiget(val, oindex._values, default=np.nan) - val = sanitize_array( - val, index, dtype=dtype, copy=False, raise_cast_failure=False - ) + val = sanitize_array(val, index, dtype=dtype, copy=False) com.require_length_match(val, index) homogenized.append(val) diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index 7d33e8b6b0fd1..ed9d7bced9253 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -259,11 +259,10 @@ def f(dtype): with pytest.raises(NotImplementedError, match=msg): f([("A", "datetime64[h]"), ("B", "str"), ("C", "int32")]) - # these work (though results may be unexpected) - depr_msg = "either all columns will be cast to that dtype, or a TypeError will" - with tm.assert_produces_warning(FutureWarning, match=depr_msg): + # pre-2.0 these used to work (though results may be unexpected) + with pytest.raises(TypeError, match="argument must be"): f("int64") - with tm.assert_produces_warning(FutureWarning, match=depr_msg): + with pytest.raises(TypeError, match="argument must be"): f("float64") # 10822 diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index f9cfb0b81a7bd..10b1f8406025a 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -245,10 +245,11 @@ def test_constructor_mixed(self, float_string_frame): assert float_string_frame["foo"].dtype == np.object_ def test_constructor_cast_failure(self): - msg = "either all columns will be cast to that dtype, or a TypeError will" - with tm.assert_produces_warning(FutureWarning, match=msg): - foo = DataFrame({"a": ["a", "b", "c"]}, dtype=np.float64) - assert foo["a"].dtype == object + # as of 2.0, we raise if we can't respect "dtype", previously we + # silently ignored + msg = "could not convert string to float" + with pytest.raises(ValueError, match=msg): + DataFrame({"a": ["a", "b", "c"]}, dtype=np.float64) # GH 3010, constructing with odd arrays df = DataFrame(np.ones((4, 2))) @@ -753,13 +754,8 @@ def test_constructor_dict_cast2(self): "A": dict(zip(range(20), tm.makeStringIndex(20))), "B": dict(zip(range(15), np.random.randn(15))), } - msg = "either all columns will be cast to that dtype, or a TypeError will" - with tm.assert_produces_warning(FutureWarning, match=msg): - frame = DataFrame(test_data, dtype=float) - - assert len(frame) == 20 - assert frame["A"].dtype == np.object_ - assert frame["B"].dtype == np.float64 + with pytest.raises(ValueError, match="could not convert string"): + DataFrame(test_data, dtype=float) def test_constructor_dict_dont_upcast(self): d = {"Col1": {"Row1": "A String", "Row2": np.nan}} @@ -2788,13 +2784,14 @@ def test_floating_values_integer_dtype(self): arr = np.random.randn(10, 5) - msg = "if they cannot be cast losslessly" - with tm.assert_produces_warning(FutureWarning, match=msg): - DataFrame(arr, dtype="i8") + # as of 2.0, we match Series behavior by retaining float dtype instead + # of doing a lossy conversion here. Below we _do_ do the conversion + # since it is lossless. + df = DataFrame(arr, dtype="i8") + assert (df.dtypes == "f8").all() - with tm.assert_produces_warning(None): - # if they can be cast losslessly, no warning - DataFrame(arr.round(), dtype="i8") + df = DataFrame(arr.round(), dtype="i8") + assert (df.dtypes == "i8").all() # with NaNs, we go through a different path with a different warning arr[0, 0] = np.nan diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index eccf6c9c92ea1..9817c758759d5 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -782,25 +782,16 @@ def test_constructor_floating_data_int_dtype(self, frame_or_series): # GH#40110 arr = np.random.randn(2) - if frame_or_series is Series: - # Long-standing behavior has been to ignore the dtype on these; - # not clear if this is what we want long-term - expected = frame_or_series(arr) - - res = frame_or_series(arr, dtype="i8") - tm.assert_equal(res, expected) + # Long-standing behavior (for Series, new in 2.0 for DataFrame) + # has been to ignore the dtype on these; + # not clear if this is what we want long-term + expected = frame_or_series(arr) - res = frame_or_series(list(arr), dtype="i8") - tm.assert_equal(res, expected) + res = frame_or_series(arr, dtype="i8") + tm.assert_equal(res, expected) - else: - msg = "passing float-dtype values and an integer dtype" - with tm.assert_produces_warning(FutureWarning, match=msg): - # DataFrame will behave like Series - frame_or_series(arr, dtype="i8") - with tm.assert_produces_warning(FutureWarning, match=msg): - # DataFrame will behave like Series - frame_or_series(list(arr), dtype="i8") + res = frame_or_series(list(arr), dtype="i8") + tm.assert_equal(res, expected) # When we have NaNs, we silently ignore the integer dtype arr[0] = np.nan
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49313
2022-10-25T19:51:27Z
2022-10-26T20:34:00Z
2022-10-26T20:34:00Z
2022-10-26T20:35:18Z
DEPR: disallow subclass-specific keywords in Index.__new__
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 4c85b3d5dc745..be31a78776970 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -191,6 +191,7 @@ Removal of prior version deprecations/changes - Removed argument ``tz`` from :meth:`Period.to_timestamp`, use ``obj.to_timestamp(...).tz_localize(tz)`` instead (:issue:`34522`) - Removed argument ``is_copy`` from :meth:`DataFrame.take` and :meth:`Series.take` (:issue:`30615`) - Removed argument ``kind`` from :meth:`Index.get_slice_bound`, :meth:`Index.slice_indexer` and :meth:`Index.slice_locs` (:issue:`41378`) +- Disallow subclass-specific keywords (e.g. "freq", "tz", "names", "closed") in the :class:`Index` constructor (:issue:`38597`) - Removed argument ``inplace`` from :meth:`Categorical.remove_unused_categories` (:issue:`37918`) - Disallow passing non-round floats to :class:`Timestamp` with ``unit="M"`` or ``unit="Y"`` (:issue:`47266`) - Remove keywords ``convert_float`` and ``mangle_dupe_cols`` from :func:`read_excel` (:issue:`41176`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 2fe61623abfd5..36a66533018bd 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -152,10 +152,6 @@ Categorical, ExtensionArray, ) -from pandas.core.arrays.datetimes import ( - tz_to_dtype, - validate_tz_from_dtype, -) from pandas.core.arrays.string_ import StringArray from pandas.core.base import ( IndexOpsMixin, @@ -241,11 +237,6 @@ def join( return cast(F, join) -def disallow_kwargs(kwargs: dict[str, Any]) -> None: - if kwargs: - raise TypeError(f"Unexpected keyword arguments {repr(set(kwargs))}") - - def _new_Index(cls, d): """ This is called upon unpickling, rather than the default which doesn't @@ -437,18 +428,8 @@ def __new__( copy: bool = False, name=None, tupleize_cols: bool = True, - **kwargs, ) -> Index: - if kwargs: - warnings.warn( - "Passing keywords other than 'data', 'dtype', 'copy', 'name', " - "'tupleize_cols' is deprecated and will raise TypeError in a " - "future version. Use the specific Index subclass directly instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - from pandas.core.arrays import PandasArray from pandas.core.indexes.range import RangeIndex @@ -456,10 +437,6 @@ def __new__( if dtype is not None: dtype = pandas_dtype(dtype) - if "tz" in kwargs: - tz = kwargs.pop("tz") - validate_tz_from_dtype(dtype, tz) - dtype = tz_to_dtype(tz) if type(data) is PandasArray: # ensure users don't accidentally put a PandasArray in an index, @@ -481,18 +458,17 @@ def __new__( # non-EA dtype indexes have special casting logic, so we punt here klass = cls._dtype_to_subclass(dtype) if klass is not Index: - return klass(data, dtype=dtype, copy=copy, name=name, **kwargs) + return klass(data, dtype=dtype, copy=copy, name=name) ea_cls = dtype.construct_array_type() data = ea_cls._from_sequence(data, dtype=dtype, copy=copy) - disallow_kwargs(kwargs) return Index._simple_new(data, name=name) elif is_ea_or_datetimelike_dtype(data_dtype): data_dtype = cast(DtypeObj, data_dtype) klass = cls._dtype_to_subclass(data_dtype) if klass is not Index: - result = klass(data, copy=copy, name=name, **kwargs) + result = klass(data, copy=copy, name=name) if dtype is not None: return result.astype(dtype, copy=False) return result @@ -500,7 +476,6 @@ def __new__( # GH#45206 data = data.astype(dtype, copy=False) - disallow_kwargs(kwargs) data = extract_array(data, extract_numpy=True) return Index._simple_new(data, name=name) @@ -542,18 +517,14 @@ def __new__( ) dtype = arr.dtype - if kwargs: - return cls(arr, dtype, copy=copy, name=name, **kwargs) - klass = cls._dtype_to_subclass(arr.dtype) arr = klass._ensure_array(arr, dtype, copy) - disallow_kwargs(kwargs) return klass._simple_new(arr, name) elif is_scalar(data): raise cls._raise_scalar_data_error(data) elif hasattr(data, "__array__"): - return Index(np.asarray(data), dtype=dtype, copy=copy, name=name, **kwargs) + return Index(np.asarray(data), dtype=dtype, copy=copy, name=name) else: if tupleize_cols and is_list_like(data): @@ -566,9 +537,7 @@ def __new__( # 10697 from pandas.core.indexes.multi import MultiIndex - return MultiIndex.from_tuples( - data, names=name or kwargs.get("names") - ) + return MultiIndex.from_tuples(data, names=name) # other iterable of some kind subarr = com.asarray_tuplesafe(data, dtype=_dtype_obj) @@ -578,7 +547,7 @@ def __new__( subarr, cast_numeric_deprecated=False ) dtype = subarr.dtype - return Index(subarr, dtype=dtype, copy=copy, name=name, **kwargs) + return Index(subarr, dtype=dtype, copy=copy, name=name) @classmethod def _ensure_array(cls, data, dtype, copy: bool): @@ -7081,19 +7050,6 @@ def shape(self) -> Shape: # See GH#27775, GH#27384 for history/reasoning in how this is defined. return (len(self),) - @final - def _deprecated_arg(self, value, name: str_t, methodname: str_t) -> None: - """ - Issue a FutureWarning if the arg/kwarg is not no_default. - """ - if value is not no_default: - warnings.warn( - f"'{name}' argument in {methodname} is deprecated " - "and will be removed in a future version. Do not pass it.", - FutureWarning, - stacklevel=find_stack_level(), - ) - def ensure_index_from_sequences(sequences, names=None) -> Index: """ @@ -7246,14 +7202,6 @@ def maybe_extract_name(name, obj, cls) -> Hashable: return name -_cast_depr_msg = ( - "In a future version, passing an object-dtype arraylike to pd.Index will " - "not infer numeric values to numeric dtype (matching the Series behavior). " - "To retain the old behavior, explicitly pass the desired dtype or use the " - "desired Index subclass" -) - - def _maybe_cast_data_without_dtype( subarr: np.ndarray, cast_numeric_deprecated: bool = True ) -> ArrayLike: diff --git a/pandas/tests/indexes/base_class/test_constructors.py b/pandas/tests/indexes/base_class/test_constructors.py index df04502a01f99..cf8b7214f3b91 100644 --- a/pandas/tests/indexes/base_class/test_constructors.py +++ b/pandas/tests/indexes/base_class/test_constructors.py @@ -30,12 +30,6 @@ def test_construction_list_mixed_tuples(self, index_vals): assert isinstance(index, Index) assert not isinstance(index, MultiIndex) - def test_constructor_wrong_kwargs(self): - # GH #19348 - with pytest.raises(TypeError, match="Unexpected keyword arguments {'foo'}"): - with tm.assert_produces_warning(FutureWarning): - Index([], foo="bar") - def test_constructor_cast(self): msg = "could not convert string to float" with pytest.raises(ValueError, match=msg): diff --git a/pandas/tests/indexes/categorical/test_constructors.py b/pandas/tests/indexes/categorical/test_constructors.py index 98da8038401e7..def865e03ed7c 100644 --- a/pandas/tests/indexes/categorical/test_constructors.py +++ b/pandas/tests/indexes/categorical/test_constructors.py @@ -145,15 +145,5 @@ def test_construction_with_categorical_dtype(self): with pytest.raises(ValueError, match=msg): CategoricalIndex(data, categories=cats, dtype=dtype) - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning): - # passing subclass-specific kwargs to pd.Index - Index(data, categories=cats, dtype=dtype) - with pytest.raises(ValueError, match=msg): CategoricalIndex(data, ordered=ordered, dtype=dtype) - - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning): - # passing subclass-specific kwargs to pd.Index - Index(data, ordered=ordered, dtype=dtype) diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 67f323c5afd81..0061cfd2b903f 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -409,17 +409,6 @@ def test_construction_index_with_mixed_timezones_with_NaT(self): assert isinstance(result, DatetimeIndex) assert result.tz is None - # all NaT with tz - with tm.assert_produces_warning(FutureWarning): - # subclass-specific kwargs to pd.Index - result = Index([pd.NaT, pd.NaT], tz="Asia/Tokyo", name="idx") - exp = DatetimeIndex([pd.NaT, pd.NaT], tz="Asia/Tokyo", name="idx") - - tm.assert_index_equal(result, exp, exact=True) - assert isinstance(result, DatetimeIndex) - assert result.tz is not None - assert result.tz == exp.tz - def test_construction_dti_with_mixed_timezones(self): # GH 11488 (not changed, added explicit tests) @@ -497,22 +486,6 @@ def test_construction_dti_with_mixed_timezones(self): name="idx", ) - with pytest.raises(ValueError, match=msg): - # passing tz should results in DatetimeIndex, then mismatch raises - # TypeError - with tm.assert_produces_warning(FutureWarning): - # subclass-specific kwargs to pd.Index - Index( - [ - pd.NaT, - Timestamp("2011-01-01 10:00"), - pd.NaT, - Timestamp("2011-01-02 10:00", tz="US/Eastern"), - ], - tz="Asia/Tokyo", - name="idx", - ) - def test_construction_base_constructor(self): arr = [Timestamp("2011-01-01"), pd.NaT, Timestamp("2011-01-03")] tm.assert_index_equal(Index(arr), DatetimeIndex(arr)) diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py index a71a8f9e34ea9..315578a5dbf50 100644 --- a/pandas/tests/indexes/interval/test_constructors.py +++ b/pandas/tests/indexes/interval/test_constructors.py @@ -38,7 +38,6 @@ class ConstructorTests: get_kwargs_from_breaks to the expected format. """ - @pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning") @pytest.mark.parametrize( "breaks", [ @@ -96,22 +95,16 @@ def test_constructor_dtype(self, constructor, breaks, subtype): ) def test_constructor_pass_closed(self, constructor, breaks): # not passing closed to IntervalDtype, but to IntervalArray constructor - warn = None - if isinstance(constructor, partial) and constructor.func is Index: - # passing kwargs to Index is deprecated - warn = FutureWarning - iv_dtype = IntervalDtype(breaks.dtype) result_kwargs = self.get_kwargs_from_breaks(breaks) for dtype in (iv_dtype, str(iv_dtype)): - with tm.assert_produces_warning(warn): + with tm.assert_produces_warning(None): result = constructor(dtype=dtype, closed="left", **result_kwargs) assert result.dtype.closed == "left" - @pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning") @pytest.mark.parametrize("breaks", [[np.nan] * 2, [np.nan] * 4, [np.nan] * 50]) def test_constructor_nan(self, constructor, breaks, closed): # GH 18421 @@ -125,7 +118,6 @@ def test_constructor_nan(self, constructor, breaks, closed): assert result.dtype.subtype == expected_subtype tm.assert_numpy_array_equal(np.array(result), expected_values) - @pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning") @pytest.mark.parametrize( "breaks", [ @@ -353,9 +345,14 @@ class TestClassConstructors(ConstructorTests): params=[IntervalIndex, partial(Index, dtype="interval")], ids=["IntervalIndex", "Index"], ) - def constructor(self, request): + def klass(self, request): + # We use a separate fixture here to include Index.__new__ with dtype kwarg return request.param + @pytest.fixture + def constructor(self): + return IntervalIndex + def get_kwargs_from_breaks(self, breaks, closed="right"): """ converts intervals in breaks format to a dictionary of kwargs to @@ -388,12 +385,12 @@ def test_constructor_string(self): # the interval of strings is already forbidden. pass - def test_constructor_errors(self, constructor): + def test_constructor_errors(self, klass): # mismatched closed within intervals with no constructor override ivs = [Interval(0, 1, closed="right"), Interval(2, 3, closed="left")] msg = "intervals must all be closed on the same side" with pytest.raises(ValueError, match=msg): - constructor(ivs) + klass(ivs) # scalar msg = ( @@ -401,14 +398,13 @@ def test_constructor_errors(self, constructor): "some kind, 5 was passed" ) with pytest.raises(TypeError, match=msg): - constructor(5) + klass(5) # not an interval; dtype depends on 32bit/windows builds msg = "type <class 'numpy.int(32|64)'> with value 0 is not an interval" with pytest.raises(TypeError, match=msg): - constructor([0, 1]) + klass([0, 1]) - @pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning") @pytest.mark.parametrize( "data, closed", [ diff --git a/pandas/tests/indexes/multi/test_equivalence.py b/pandas/tests/indexes/multi/test_equivalence.py index 18ff73dcb2221..c51b9386d7ec6 100644 --- a/pandas/tests/indexes/multi/test_equivalence.py +++ b/pandas/tests/indexes/multi/test_equivalence.py @@ -191,18 +191,7 @@ def test_identical(idx): mi2 = mi2.set_names(["new1", "new2"]) assert mi.identical(mi2) - with tm.assert_produces_warning(FutureWarning): - # subclass-specific keywords to pd.Index - mi3 = Index(mi.tolist(), names=mi.names) - - msg = r"Unexpected keyword arguments {'names'}" - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(FutureWarning): - # subclass-specific keywords to pd.Index - Index(mi.tolist(), names=mi.names, tupleize_cols=False) - mi4 = Index(mi.tolist(), tupleize_cols=False) - assert mi.identical(mi3) assert not mi.identical(mi4) assert mi.equals(mi4) diff --git a/pandas/tests/indexes/multi/test_names.py b/pandas/tests/indexes/multi/test_names.py index cfbc90d1b36bb..5e3a427bc75ba 100644 --- a/pandas/tests/indexes/multi/test_names.py +++ b/pandas/tests/indexes/multi/test_names.py @@ -56,9 +56,7 @@ def test_take_preserve_name(idx): def test_copy_names(): # Check that adding a "names" parameter to the copy is honored # GH14302 - with tm.assert_produces_warning(FutureWarning): - # subclass-specific kwargs to pd.Index - multi_idx = pd.Index([(1, 2), (3, 4)], names=["MyName1", "MyName2"]) + multi_idx = MultiIndex.from_tuples([(1, 2), (3, 4)], names=["MyName1", "MyName2"]) multi_idx1 = multi_idx.copy() assert multi_idx.equals(multi_idx1) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index bfe462cdf6c15..e5cce91b09a2f 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -250,9 +250,13 @@ def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass): if attr == "asi8": result = DatetimeIndex(arg).tz_localize(tz_naive_fixture) + tm.assert_index_equal(result, index) + elif klass is Index: + with pytest.raises(TypeError, match="unexpected keyword"): + klass(arg, tz=tz_naive_fixture) else: result = klass(arg, tz=tz_naive_fixture) - tm.assert_index_equal(result, index) + tm.assert_index_equal(result, index) if attr == "asi8": if err: @@ -267,9 +271,13 @@ def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass): if attr == "asi8": result = DatetimeIndex(list(arg)).tz_localize(tz_naive_fixture) + tm.assert_index_equal(result, index) + elif klass is Index: + with pytest.raises(TypeError, match="unexpected keyword"): + klass(arg, tz=tz_naive_fixture) else: result = klass(list(arg), tz=tz_naive_fixture) - tm.assert_index_equal(result, index) + tm.assert_index_equal(result, index) if attr == "asi8": if err: diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 2d54a9ba370ca..26424904482d1 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -368,12 +368,6 @@ def test_insert_index_period(self, insert, coerced_val, coerced_dtype): expected = obj.astype(object).insert(0, str(insert)) tm.assert_index_equal(result, expected) - msg = r"Unexpected keyword arguments {'freq'}" - with pytest.raises(TypeError, match=msg): - with tm.assert_produces_warning(FutureWarning): - # passing keywords to pd.Index - pd.Index(data, freq="M") - @pytest.mark.xfail(reason="Test not implemented") def test_insert_index_complex128(self): raise NotImplementedError
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49311
2022-10-25T18:05:46Z
2022-10-26T17:42:34Z
2022-10-26T17:42:34Z
2022-10-26T17:53:11Z
Backport PR #48890 on branch 1.5.x (ERR: Improve error message when assigning a complete row using 'at' m…)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b525bf6f57e88..d3116f83d58cb 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -86,6 +86,7 @@ function as nv, np_percentile_argname, ) +from pandas.errors import InvalidIndexError from pandas.util._decorators import ( Appender, Substitution, @@ -4220,6 +4221,13 @@ def _set_value( self.loc[index, col] = value self._item_cache.pop(col, None) + except InvalidIndexError as ii_err: + # GH48729: Seems like you are trying to assign a value to a + # row when only scalar options are permitted + raise InvalidIndexError( + f"You can only assign a scalar value not a {type(value)}" + ) from ii_err + def _ensure_valid_index(self, value) -> None: """ Ensure that if we don't have an index, that we can create one from the diff --git a/pandas/tests/indexing/test_at.py b/pandas/tests/indexing/test_at.py index 1e502ca70189a..adbc0e2f8127a 100644 --- a/pandas/tests/indexing/test_at.py +++ b/pandas/tests/indexing/test_at.py @@ -197,8 +197,12 @@ def test_at_frame_raises_key_error2(self, indexer_al): def test_at_frame_multiple_columns(self): # GH#48296 - at shouldn't modify multiple columns df = DataFrame({"a": [1, 2], "b": [3, 4]}) - with pytest.raises(InvalidIndexError, match=r"slice\(None, None, None\)"): - df.at[5] = [6, 7] + new_row = [6, 7] + with pytest.raises( + InvalidIndexError, + match=f"You can only assign a scalar value not a \\{type(new_row)}", + ): + df.at[5] = new_row def test_at_getitem_mixed_index_no_fallback(self): # GH#19860 @@ -220,3 +224,13 @@ def test_at_categorical_integers(self): for key in [0, 1]: with pytest.raises(KeyError, match=str(key)): df.at[key, key] + + def test_at_applied_for_rows(self): + # GH#48729 .at should raise InvalidIndexError when assigning rows + df = DataFrame(index=["a"], columns=["col1", "col2"]) + new_row = [123, 15] + with pytest.raises( + InvalidIndexError, + match=f"You can only assign a scalar value not a \\{type(new_row)}", + ): + df.at["a"] = new_row
Backport PR #48890: ERR: Improve error message when assigning a complete row using 'at' m…
https://api.github.com/repos/pandas-dev/pandas/pulls/49310
2022-10-25T17:48:53Z
2022-10-26T14:26:25Z
2022-10-26T14:26:25Z
2022-10-26T14:26:25Z
DOC: Added pre-commit link inside the guideline for developers.
diff --git a/doc/source/development/contributing_environment.rst b/doc/source/development/contributing_environment.rst index 4a70057cf18e3..afa0d0306f1af 100644 --- a/doc/source/development/contributing_environment.rst +++ b/doc/source/development/contributing_environment.rst @@ -10,7 +10,7 @@ To test out code changes, you'll need to build pandas from source, which requires a C/C++ compiler and Python environment. If you're making documentation changes, you can skip to :ref:`contributing to the documentation <contributing_documentation>` but if you skip creating the development environment you won't be able to build the documentation -locally before pushing your changes. +locally before pushing your changes. It's recommended to also install the :ref:`pre-commit hooks <contributing.pre-commit>`. .. contents:: Table of contents: :local:
- [x] closes #48941 Updated the contributor guidelines doc to include the redirection url for pre-commit. Help developers to setup the environment.
https://api.github.com/repos/pandas-dev/pandas/pulls/49308
2022-10-25T16:50:47Z
2022-10-28T13:18:20Z
2022-10-28T13:18:19Z
2022-10-28T13:18:20Z
DEPR: store SparseArray directly in Index
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index a3b6d1dc90fee..89472b8defa3c 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -229,6 +229,7 @@ Removal of prior version deprecations/changes - Removed the ``display.column_space`` option in favor of ``df.to_string(col_space=...)`` (:issue:`47280`) - Removed the deprecated method ``mad`` from pandas classes (:issue:`11787`) - Removed the deprecated method ``tshift`` from pandas classes (:issue:`11631`) +- Changed behavior of :class:`Index` constructor when passed a ``SparseArray`` or ``SparseDtype`` to retain that dtype instead of casting to ``numpy.ndarray`` (:issue:`43930`) .. --------------------------------------------------------------------------- .. _whatsnew_200.performance: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 1d3efe8bedd94..2fe61623abfd5 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -156,7 +156,6 @@ tz_to_dtype, validate_tz_from_dtype, ) -from pandas.core.arrays.sparse import SparseDtype from pandas.core.arrays.string_ import StringArray from pandas.core.base import ( IndexOpsMixin, @@ -618,17 +617,6 @@ def _dtype_to_subclass(cls, dtype: DtypeObj): return PeriodIndex - elif isinstance(dtype, SparseDtype): - warnings.warn( - "In a future version, passing a SparseArray to pd.Index " - "will store that array directly instead of converting to a " - "dense numpy ndarray. To retain the old behavior, use " - "pd.Index(arr.to_numpy()) instead", - FutureWarning, - stacklevel=find_stack_level(), - ) - return cls._dtype_to_subclass(dtype.subtype) - return Index if dtype.kind == "M": diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py index 599aaae4d3527..703ac6c89fca8 100644 --- a/pandas/tests/base/test_conversion.py +++ b/pandas/tests/base/test_conversion.py @@ -334,10 +334,7 @@ def test_array_multiindex_raises(): def test_to_numpy(arr, expected, index_or_series_or_array, request): box = index_or_series_or_array - warn = None - if index_or_series_or_array is pd.Index and isinstance(arr, SparseArray): - warn = FutureWarning - with tm.assert_produces_warning(warn): + with tm.assert_produces_warning(None): thing = box(arr) if arr.dtype.name == "int64" and box is pd.array: diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 86a523404ef8b..b1111951d67fa 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -211,17 +211,6 @@ def test_reindex(self, data, na_value): class TestIndex(base.BaseIndexTests): - def test_index_from_array(self, data): - msg = "will store that array directly" - with tm.assert_produces_warning(FutureWarning, match=msg): - idx = pd.Index(data) - - if data.dtype.subtype == "f": - assert idx.dtype == np.float64 - elif data.dtype.subtype == "i": - assert idx.dtype == np.int64 - else: - assert idx.dtype == data.dtype.subtype # TODO(2.0): should pass once SparseArray is stored directly in Index. @pytest.mark.xfail(reason="Index cannot yet store sparse dtype") diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 9914f4357cee4..67f323c5afd81 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -142,11 +142,9 @@ def test_constructor_from_sparse_array(self): Timestamp("2016-05-01T01:00:00.000000"), ] arr = pd.arrays.SparseArray(values) - msg = "will store that array directly" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = Index(arr) - expected = DatetimeIndex(values) - tm.assert_index_equal(result, expected) + result = Index(arr) + assert type(result) is Index + assert result.dtype == arr.dtype def test_construction_caching(self): diff --git a/pandas/tests/series/test_ufunc.py b/pandas/tests/series/test_ufunc.py index 924980b62a51b..4e53000059cdc 100644 --- a/pandas/tests/series/test_ufunc.py +++ b/pandas/tests/series/test_ufunc.py @@ -5,8 +5,6 @@ import numpy as np import pytest -from pandas.core.dtypes.common import is_dtype_equal - import pandas as pd import pandas._testing as tm from pandas.arrays import SparseArray @@ -277,14 +275,10 @@ def test_multiply(self, values_for_np_reduce, box_with_array, request): box = box_with_array values = values_for_np_reduce - warn = None - if is_dtype_equal(values.dtype, "Sparse[int]") and box is pd.Index: - warn = FutureWarning - msg = "passing a SparseArray to pd.Index" - with tm.assert_produces_warning(warn, match=msg): + with tm.assert_produces_warning(None): obj = box(values) - if isinstance(values, pd.core.arrays.SparseArray) and box is not pd.Index: + if isinstance(values, pd.core.arrays.SparseArray): mark = pytest.mark.xfail(reason="SparseArray has no 'prod'") request.node.add_marker(mark) @@ -316,11 +310,7 @@ def test_add(self, values_for_np_reduce, box_with_array): box = box_with_array values = values_for_np_reduce - warn = None - if is_dtype_equal(values.dtype, "Sparse[int]") and box is pd.Index: - warn = FutureWarning - msg = "passing a SparseArray to pd.Index" - with tm.assert_produces_warning(warn, match=msg): + with tm.assert_produces_warning(None): obj = box(values) if values.dtype.kind in "miuf": @@ -355,11 +345,7 @@ def test_max(self, values_for_np_reduce, box_with_array): # ATM Index casts to object, so we get python ints/floats same_type = False - warn = None - if is_dtype_equal(values.dtype, "Sparse[int]") and box is pd.Index: - warn = FutureWarning - msg = "passing a SparseArray to pd.Index" - with tm.assert_produces_warning(warn, match=msg): + with tm.assert_produces_warning(None): obj = box(values) result = np.maximum.reduce(obj) @@ -383,11 +369,7 @@ def test_min(self, values_for_np_reduce, box_with_array): # ATM Index casts to object, so we get python ints/floats same_type = False - warn = None - if is_dtype_equal(values.dtype, "Sparse[int]") and box is pd.Index: - warn = FutureWarning - msg = "passing a SparseArray to pd.Index" - with tm.assert_produces_warning(warn, match=msg): + with tm.assert_produces_warning(None): obj = box(values) result = np.minimum.reduce(obj)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49307
2022-10-25T16:21:01Z
2022-10-25T18:29:05Z
2022-10-25T18:29:05Z
2022-10-25T18:31:30Z
STYLE: fix pylint consider-iterating-dictionary warnings
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 16732f5421df7..109227633cfdd 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -332,7 +332,7 @@ def _aggregate_multiple_funcs(self, arg) -> DataFrame: from pandas import concat res_df = concat( - results.values(), axis=1, keys=[key.label for key in results.keys()] + results.values(), axis=1, keys=[key.label for key in results] ) return res_df diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py index 2867f1b067b2d..85fae6da07827 100644 --- a/pandas/io/clipboard/__init__.py +++ b/pandas/io/clipboard/__init__.py @@ -608,7 +608,7 @@ def set_clipboard(clipboard): } if clipboard not in clipboard_types: - allowed_clipboard_types = [repr(_) for _ in clipboard_types.keys()] + allowed_clipboard_types = [repr(_) for _ in clipboard_types] raise ValueError( f"Argument must be one of {', '.join(allowed_clipboard_types)}" ) diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 6d815b43a9bcd..035c5d88a7f4b 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -2284,7 +2284,7 @@ def color(value, user_arg, command, comm_arg): if isinstance(value, str) and "--latex" in value: # return the style without conversion but drop '--latex' latex_styles.append((attribute, value.replace("--latex", ""))) - if attribute in CONVERTED_ATTRIBUTES.keys(): + if attribute in CONVERTED_ATTRIBUTES: arg = "" for x in ["--wrap", "--nowrap", "--lwrap", "--dwrap", "--rwrap"]: if x in str(value): diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 8c2c1026d5c82..7f8b8727629e7 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -1699,7 +1699,7 @@ def test_pivot_table_with_iterator_values(self, data): ) tm.assert_frame_equal(pivot_values_keys, pivot_values_list) - agg_values_gen = (value for value in aggs.keys()) + agg_values_gen = (value for value in aggs) pivot_values_gen = pivot_table( data, index=["A"], values=agg_values_gen, aggfunc=aggs ) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 5a66597bdb314..5214e280718f0 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -180,7 +180,7 @@ def test_unknown_attribute(self): # GH#9680 tdi = pd.timedelta_range(start=0, periods=10, freq="1s") ser = Series(np.random.normal(size=10), index=tdi) - assert "foo" not in ser.__dict__.keys() + assert "foo" not in ser.__dict__ msg = "'Series' object has no attribute 'foo'" with pytest.raises(AttributeError, match=msg): ser.foo diff --git a/pyproject.toml b/pyproject.toml index b6b53f4bfd578..f2ebed97bed50 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -79,7 +79,6 @@ disable = [ "used-before-assignment", # pylint type "C": convention, for programming standard violation - "consider-iterating-dictionary", "consider-using-f-string", "disallowed-name", "import-outside-toplevel",
Related to https://github.com/pandas-dev/pandas/issues/48855 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. The `consider-iterating-dictionary` is also removed from the ignored warnings in `pyproject.toml`.
https://api.github.com/repos/pandas-dev/pandas/pulls/49305
2022-10-25T15:49:50Z
2022-10-25T20:00:12Z
2022-10-25T20:00:12Z
2022-10-25T21:20:50Z
Backport PR #49286 on branch 1.5.x (TST: update exception messages for lxml tests)
diff --git a/pandas/tests/io/xml/test_to_xml.py b/pandas/tests/io/xml/test_to_xml.py index d3247eb9dd47e..0f42c7e070c4a 100644 --- a/pandas/tests/io/xml/test_to_xml.py +++ b/pandas/tests/io/xml/test_to_xml.py @@ -1037,9 +1037,16 @@ def test_stylesheet_wrong_path(): def test_empty_string_stylesheet(val): from lxml.etree import XMLSyntaxError - with pytest.raises( - XMLSyntaxError, match=("Document is empty|Start tag expected, '<' not found") - ): + msg = "|".join( + [ + "Document is empty", + "Start tag expected, '<' not found", + # Seen on Mac with lxml 4.9.1 + r"None \(line 0\)", + ] + ) + + with pytest.raises(XMLSyntaxError, match=msg): geom_df.to_xml(stylesheet=val) diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py index fd4ba87bd302c..33a98f57310c2 100644 --- a/pandas/tests/io/xml/test_xml.py +++ b/pandas/tests/io/xml/test_xml.py @@ -471,7 +471,14 @@ def test_file_handle_close(datapath, parser): def test_empty_string_lxml(val): from lxml.etree import XMLSyntaxError - with pytest.raises(XMLSyntaxError, match="Document is empty"): + msg = "|".join( + [ + "Document is empty", + # Seen on Mac with lxml 4.91 + r"None \(line 0\)", + ] + ) + with pytest.raises(XMLSyntaxError, match=msg): read_xml(val, parser="lxml")
Backport PR #49286: TST: update exception messages for lxml tests
https://api.github.com/repos/pandas-dev/pandas/pulls/49303
2022-10-25T15:00:09Z
2022-10-26T13:04:16Z
2022-10-26T13:04:16Z
2022-10-26T13:04:16Z
DEPR: non-keyword arguments
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index a3b6d1dc90fee..d3eabe8fd7eb7 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -193,6 +193,19 @@ Removal of prior version deprecations/changes - Disallow passing non-round floats to :class:`Timestamp` with ``unit="M"`` or ``unit="Y"`` (:issue:`47266`) - Remove keywords ``convert_float`` and ``mangle_dupe_cols`` from :func:`read_excel` (:issue:`41176`) - Disallow passing non-keyword arguments to :func:`read_excel` except ``io`` and ``sheet_name`` (:issue:`34418`) +- Disallow passing non-keyword arguments to :meth:`DataFrame.drop_duplicates` except for ``subset`` (:issue:`41485`) +- Disallow passing non-keyword arguments to :meth:`DataFrame.sort_index` and :meth:`Series.sort_index` (:issue:`41506`) +- Disallow passing non-keyword arguments to :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` except for ``method`` (:issue:`41510`) +- Disallow passing non-keyword arguments to :meth:`DataFrame.any` and :meth:`Series.any` (:issue:`44896`) +- Disallow passing non-keyword arguments to :meth:`Index.set_names` except for ``names`` (:issue:`41551`) +- Disallow passing non-keyword arguments to :meth:`Index.join` except for ``other`` (:issue:`46518`) +- Disallow passing non-keyword arguments to :func:`concat` except for ``objs`` (:issue:`41485`) +- Disallow passing non-keyword arguments to :func:`pivot` except for ``data`` (:issue:`48301`) +- Disallow passing non-keyword arguments to :meth:`DataFrame.pivot` (:issue:`48301`) +- Disallow passing non-keyword arguments to :func:`read_json` except for ``path_or_buf`` (:issue:`27573`) +- Disallow passing non-keyword arguments to :func:`read_sas` except for ``filepath_or_buffer`` (:issue:`47154`) +- Disallow passing non-keyword arguments to :func:`read_stata` except for ``filepath_or_buffer`` (:issue:`48128`) +- Disallow passing non-keyword arguments to :func:`read_xml` except for ``path_or_buffer`` (:issue:`45133`) - Disallow passing non-keyword arguments to :meth:`Series.mask` and :meth:`DataFrame.mask` except ``cond`` and ``other`` (:issue:`41580`) - Disallow passing non-keyword arguments to :meth:`DataFrame.to_stata` except for ``path`` (:issue:`48128`) - Disallow passing non-keyword arguments to :meth:`DataFrame.where` and :meth:`Series.where` except for ``cond`` and ``other`` (:issue:`41523`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index cc2bca1bcece6..84b8960965463 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6556,10 +6556,10 @@ def dropna( self._update_inplace(result) return None - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "subset"]) def drop_duplicates( self, subset: Hashable | Sequence[Hashable] | None = None, + *, keep: DropKeep = "first", inplace: bool = False, ignore_index: bool = False, @@ -6964,10 +6964,9 @@ def sort_index( ) -> DataFrame | None: ... - # error: Signature of "sort_index" incompatible with supertype "NDFrame" - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) - def sort_index( # type: ignore[override] + def sort_index( self, + *, axis: Axis = 0, level: IndexLabel = None, ascending: bool | Sequence[bool] = True, @@ -11794,10 +11793,10 @@ def clip( ) -> DataFrame | None: return super().clip(lower, upper, axis=axis, inplace=inplace, **kwargs) - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "method"]) def interpolate( self: DataFrame, method: str = "linear", + *, axis: Axis = 0, limit: int | None = None, inplace: bool = False, @@ -11807,13 +11806,13 @@ def interpolate( **kwargs, ) -> DataFrame | None: return super().interpolate( - method, - axis, - limit, - inplace, - limit_direction, - limit_area, - downcast, + method=method, + axis=axis, + limit=limit, + inplace=inplace, + limit_direction=limit_direction, + limit_area=limit_area, + downcast=downcast, **kwargs, ) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a1f799ec5122a..13a2a00dbc6eb 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5000,6 +5000,7 @@ def sort_index( def sort_index( self: NDFrameT, + *, axis: Axis = 0, level: IndexLabel = None, ascending: bool_t | Sequence[bool_t] = True, @@ -7312,6 +7313,7 @@ def replace( def interpolate( self: NDFrameT, method: str = "linear", + *, axis: Axis = 0, limit: int | None = None, inplace: bool_t = False, @@ -11429,11 +11431,6 @@ def _add_numeric_operations(cls) -> None: """ axis_descr, name1, name2 = _doc_params(cls) - @deprecate_nonkeyword_arguments( - version=None, - allowed_args=["self"], - name="DataFrame.any and Series.any", - ) @doc( _bool_doc, desc=_any_desc, @@ -11446,13 +11443,21 @@ def _add_numeric_operations(cls) -> None: ) def any( self, + *, axis: Axis = 0, bool_only=None, skipna: bool_t = True, level=None, **kwargs, ): - return NDFrame.any(self, axis, bool_only, skipna, level, **kwargs) + return NDFrame.any( + self, + axis=axis, + bool_only=bool_only, + skipna=skipna, + level=level, + **kwargs, + ) setattr(cls, "any", any) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 1d3efe8bedd94..f7306142ef16f 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -223,7 +223,8 @@ def _maybe_return_indexers(meth: F) -> F: @functools.wraps(meth) def join( self, - other, + other: Index, + *, how: str_t = "left", level=None, return_indexers: bool = False, @@ -1803,9 +1804,8 @@ def set_names( ) -> _IndexT | None: ... - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "names"]) def set_names( - self: _IndexT, names, level=None, inplace: bool = False + self: _IndexT, names, *, level=None, inplace: bool = False ) -> _IndexT | None: """ Set Index or MultiIndex name. @@ -4537,11 +4537,11 @@ def join( ... @final - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "other"]) @_maybe_return_indexers def join( self, other: Index, + *, how: str_t = "left", level: Level = None, return_indexers: bool = False, diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index bb7a48946d4ca..27058cb54dddf 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -50,7 +50,6 @@ from pandas.util._decorators import ( Appender, cache_readonly, - deprecate_nonkeyword_arguments, doc, ) from pandas.util._exceptions import find_stack_level @@ -3786,10 +3785,8 @@ def set_names(self, names, *, level=..., inplace: Literal[True]) -> None: def set_names(self, names, *, level=..., inplace: bool = ...) -> MultiIndex | None: ... - # error: Signature of "set_names" incompatible with supertype "Index" - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "names"]) - def set_names( # type: ignore[override] - self, names, level=None, inplace: bool = False + def set_names( + self, names, *, level=None, inplace: bool = False ) -> MultiIndex | None: return super().set_names(names=names, level=level, inplace=inplace) diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index e8fd8ed737fd6..31b6209855561 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -23,10 +23,7 @@ AxisInt, HashableT, ) -from pandas.util._decorators import ( - cache_readonly, - deprecate_nonkeyword_arguments, -) +from pandas.util._decorators import cache_readonly from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.concat import concat_compat @@ -67,6 +64,7 @@ @overload def concat( objs: Iterable[DataFrame] | Mapping[HashableT, DataFrame], + *, axis: Literal[0, "index"] = ..., join: str = ..., ignore_index: bool = ..., @@ -83,6 +81,7 @@ def concat( @overload def concat( objs: Iterable[Series] | Mapping[HashableT, Series], + *, axis: Literal[0, "index"] = ..., join: str = ..., ignore_index: bool = ..., @@ -99,6 +98,7 @@ def concat( @overload def concat( objs: Iterable[NDFrame] | Mapping[HashableT, NDFrame], + *, axis: Literal[0, "index"] = ..., join: str = ..., ignore_index: bool = ..., @@ -115,6 +115,7 @@ def concat( @overload def concat( objs: Iterable[NDFrame] | Mapping[HashableT, NDFrame], + *, axis: Literal[1, "columns"], join: str = ..., ignore_index: bool = ..., @@ -131,6 +132,7 @@ def concat( @overload def concat( objs: Iterable[NDFrame] | Mapping[HashableT, NDFrame], + *, axis: Axis = ..., join: str = ..., ignore_index: bool = ..., @@ -144,9 +146,9 @@ def concat( ... -@deprecate_nonkeyword_arguments(version=None, allowed_args=["objs"]) def concat( objs: Iterable[NDFrame] | Mapping[HashableT, NDFrame], + *, axis: Axis = 0, join: str = "outer", ignore_index: bool = False, diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 51ca0e90f8809..8b49d681379c6 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -20,7 +20,6 @@ from pandas.util._decorators import ( Appender, Substitution, - deprecate_nonkeyword_arguments, ) from pandas.core.dtypes.cast import maybe_downcast_to_dtype @@ -493,9 +492,9 @@ def _convert_by(by): @Substitution("\ndata : DataFrame") @Appender(_shared_docs["pivot"], indents=1) -@deprecate_nonkeyword_arguments(version=None, allowed_args=["data"]) def pivot( data: DataFrame, + *, index: IndexLabel | lib.NoDefault = lib.NoDefault, columns: IndexLabel | lib.NoDefault = lib.NoDefault, values: IndexLabel | lib.NoDefault = lib.NoDefault, diff --git a/pandas/core/series.py b/pandas/core/series.py index 2987858492a25..7d6932457ac29 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3767,10 +3767,9 @@ def sort_index( ) -> Series | None: ... - # error: Signature of "sort_index" incompatible with supertype "NDFrame" - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) - def sort_index( # type: ignore[override] + def sort_index( self, + *, axis: Axis = 0, level: IndexLabel = None, ascending: bool | Sequence[bool] = True, @@ -5993,10 +5992,10 @@ def clip( ) -> Series | None: return super().clip(lower, upper, axis=axis, inplace=inplace, **kwargs) - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "method"]) def interpolate( self: Series, method: str = "linear", + *, axis: Axis = 0, limit: int | None = None, inplace: bool = False, @@ -6006,13 +6005,13 @@ def interpolate( **kwargs, ) -> Series | None: return super().interpolate( - method, - axis, - limit, - inplace, - limit_direction, - limit_area, - downcast, + method=method, + axis=axis, + limit=limit, + inplace=inplace, + limit_direction=limit_direction, + limit_area=limit_area, + downcast=downcast, **kwargs, ) diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index 4bf883a7214bf..15e7da1b8525e 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -34,10 +34,7 @@ WriteBuffer, ) from pandas.errors import AbstractMethodError -from pandas.util._decorators import ( - deprecate_nonkeyword_arguments, - doc, -) +from pandas.util._decorators import doc from pandas.core.dtypes.common import ( ensure_str, @@ -452,6 +449,7 @@ def read_json( @overload def read_json( path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes], + *, orient: str | None = ..., typ: Literal["frame"] = ..., dtype: DtypeArg | None = ..., @@ -475,9 +473,9 @@ def read_json( storage_options=_shared_docs["storage_options"], decompression_options=_shared_docs["decompression_options"] % "path_or_buf", ) -@deprecate_nonkeyword_arguments(version="2.0", allowed_args=["path_or_buf"]) def read_json( path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes], + *, orient: str | None = None, typ: Literal["frame", "series"] = "frame", dtype: DtypeArg | None = None, diff --git a/pandas/io/sas/sasreader.py b/pandas/io/sas/sasreader.py index 2b6472913a4d3..bcd342ddb9023 100644 --- a/pandas/io/sas/sasreader.py +++ b/pandas/io/sas/sasreader.py @@ -19,10 +19,7 @@ FilePath, ReadBuffer, ) -from pandas.util._decorators import ( - deprecate_nonkeyword_arguments, - doc, -) +from pandas.util._decorators import doc from pandas.core.shared_docs import _shared_docs @@ -61,6 +58,7 @@ def __exit__( @overload def read_sas( filepath_or_buffer: FilePath | ReadBuffer[bytes], + *, format: str | None = ..., index: Hashable | None = ..., encoding: str | None = ..., @@ -74,6 +72,7 @@ def read_sas( @overload def read_sas( filepath_or_buffer: FilePath | ReadBuffer[bytes], + *, format: str | None = ..., index: Hashable | None = ..., encoding: str | None = ..., @@ -84,10 +83,10 @@ def read_sas( ... -@deprecate_nonkeyword_arguments(version=None, allowed_args=["filepath_or_buffer"]) @doc(decompression_options=_shared_docs["decompression_options"] % "filepath_or_buffer") def read_sas( filepath_or_buffer: FilePath | ReadBuffer[bytes], + *, format: str | None = None, index: Hashable | None = None, encoding: str | None = None, diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 5e9b70aeb2a82..60c710d1930ed 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -50,7 +50,6 @@ ) from pandas.util._decorators import ( Appender, - deprecate_nonkeyword_arguments, doc, ) from pandas.util._exceptions import find_stack_level @@ -2009,9 +2008,9 @@ def value_labels(self) -> dict[str, dict[float, str]]: @Appender(_read_stata_doc) -@deprecate_nonkeyword_arguments(version=None, allowed_args=["filepath_or_buffer"]) def read_stata( filepath_or_buffer: FilePath | ReadBuffer[bytes], + *, convert_dates: bool = True, convert_categoricals: bool = True, index_col: str | None = None, diff --git a/pandas/io/xml.py b/pandas/io/xml.py index 71d19b7861fc2..f042494d0c9ca 100644 --- a/pandas/io/xml.py +++ b/pandas/io/xml.py @@ -27,10 +27,7 @@ AbstractMethodError, ParserError, ) -from pandas.util._decorators import ( - deprecate_nonkeyword_arguments, - doc, -) +from pandas.util._decorators import doc from pandas.core.dtypes.common import is_list_like @@ -853,13 +850,13 @@ def _parse( ) -@deprecate_nonkeyword_arguments(version=None, allowed_args=["path_or_buffer"]) @doc( storage_options=_shared_docs["storage_options"], decompression_options=_shared_docs["decompression_options"] % "path_or_buffer", ) def read_xml( path_or_buffer: FilePath | ReadBuffer[bytes] | ReadBuffer[str], + *, xpath: str = "./*", namespaces: dict[str, str] | None = None, elems_only: bool = False, diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index a7aefc9b1eaa0..c6294cfc0c670 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -1606,28 +1606,6 @@ def test_unique_agg_type_is_series(test, constant): tm.assert_series_equal(result, expected) -def test_any_non_keyword_deprecation(): - df = DataFrame({"A": [1, 2], "B": [0, 2], "C": [0, 0]}) - msg = ( - "In a future version of pandas all arguments of " - "DataFrame.any and Series.any will be keyword-only." - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.any("index", None) - expected = Series({"A": True, "B": True, "C": False}) - tm.assert_series_equal(result, expected) - - s = Series([False, False, False]) - msg = ( - "In a future version of pandas all arguments of " - "DataFrame.any and Series.any will be keyword-only." - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = s.any("index") - expected = False - tm.assert_equal(result, expected) - - def test_any_apply_keyword_non_zero_axis_regression(): # https://github.com/pandas-dev/pandas/issues/48656 df = DataFrame({"A": [1, 2, 0], "B": [0, 2, 0], "C": [0, 0, 0]}) diff --git a/pandas/tests/frame/methods/test_drop_duplicates.py b/pandas/tests/frame/methods/test_drop_duplicates.py index cd61f59a85d1e..988d8e3b6f13f 100644 --- a/pandas/tests/frame/methods/test_drop_duplicates.py +++ b/pandas/tests/frame/methods/test_drop_duplicates.py @@ -472,17 +472,3 @@ def test_drop_duplicates_non_boolean_ignore_index(arg): msg = '^For argument "ignore_index" expected type bool, received type .*.$' with pytest.raises(ValueError, match=msg): df.drop_duplicates(ignore_index=arg) - - -def test_drop_duplicates_pos_args_deprecation(): - # GH#41485 - df = DataFrame({"a": [1, 1, 2], "b": [1, 1, 3], "c": [1, 1, 3]}) - msg = ( - "In a future version of pandas all arguments of " - "DataFrame.drop_duplicates except for the argument 'subset' " - "will be keyword-only" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.drop_duplicates(["b", "c"], "last") - expected = DataFrame({"a": [1, 2], "b": [1, 3], "c": [1, 3]}, index=[1, 2]) - tm.assert_frame_equal(expected, result) diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py index 6543fd8efdf1b..00fdfe373f1d8 100644 --- a/pandas/tests/frame/methods/test_interpolate.py +++ b/pandas/tests/frame/methods/test_interpolate.py @@ -397,15 +397,3 @@ def test_interp_fillna_methods(self, request, axis, method, using_array_manager) expected = df.fillna(axis=axis, method=method) result = df.interpolate(method=method, axis=axis) tm.assert_frame_equal(result, expected) - - def test_interpolate_pos_args_deprecation(self): - # https://github.com/pandas-dev/pandas/issues/41485 - df = DataFrame({"a": [1, 2, 3]}) - msg = ( - r"In a future version of pandas all arguments of DataFrame.interpolate " - r"except for the argument 'method' will be keyword-only" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.interpolate("pad", 0) - expected = DataFrame({"a": [1, 2, 3]}) - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index 5d1cc3d4ecee5..806abc1e7c012 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -913,15 +913,3 @@ def test_sort_index_multiindex_sparse_column(self): result = expected.sort_index(level=0) tm.assert_frame_equal(result, expected) - - def test_sort_index_pos_args_deprecation(self): - # https://github.com/pandas-dev/pandas/issues/41485 - df = DataFrame({"a": [1, 2, 3]}) - msg = ( - r"In a future version of pandas all arguments of DataFrame.sort_index " - r"will be keyword-only" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.sort_index(1) - expected = DataFrame({"a": [1, 2, 3]}) - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py index 4fff4ca961cf7..70350f0df821b 100644 --- a/pandas/tests/indexes/multi/test_get_set.py +++ b/pandas/tests/indexes/multi/test_get_set.py @@ -299,23 +299,6 @@ def test_set_names_with_nlevel_1(inplace): tm.assert_index_equal(result, expected) -def test_multi_set_names_pos_args_deprecation(): - # GH#41485 - idx = MultiIndex.from_product([["python", "cobra"], [2018, 2019]]) - msg = ( - "In a future version of pandas all arguments of MultiIndex.set_names " - "except for the argument 'names' will be keyword-only" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = idx.set_names(["kind", "year"], None) - expected = MultiIndex( - levels=[["python", "cobra"], [2018, 2019]], - codes=[[0, 0, 1, 1], [0, 1, 0, 1]], - names=["kind", "year"], - ) - tm.assert_index_equal(result, expected) - - @pytest.mark.parametrize("ordered", [True, False]) def test_set_levels_categorical(ordered): # GH13854 diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index bfe462cdf6c15..d761695bca61d 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1582,19 +1582,6 @@ def test_construct_from_memoryview(klass, extra_kwargs): tm.assert_index_equal(result, expected, exact=True) -def test_index_set_names_pos_args_deprecation(): - # GH#41485 - idx = Index([1, 2, 3, 4]) - msg = ( - "In a future version of pandas all arguments of Index.set_names " - "except for the argument 'names' will be keyword-only" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = idx.set_names("quarter", None) - expected = Index([1, 2, 3, 4], name="quarter") - tm.assert_index_equal(result, expected) - - def test_drop_duplicates_pos_args_deprecation(): # GH#41485 idx = Index([1, 2, 3, 1]) diff --git a/pandas/tests/io/json/test_deprecated_kwargs.py b/pandas/tests/io/json/test_deprecated_kwargs.py index 79245bc9d34a8..7e3296db75323 100644 --- a/pandas/tests/io/json/test_deprecated_kwargs.py +++ b/pandas/tests/io/json/test_deprecated_kwargs.py @@ -8,19 +8,6 @@ from pandas.io.json import read_json -def test_deprecated_kwargs(): - df = pd.DataFrame({"A": [2, 4, 6], "B": [3, 6, 9]}, index=[0, 1, 2]) - buf = df.to_json(orient="split") - with tm.assert_produces_warning(FutureWarning): - tm.assert_frame_equal(df, read_json(buf, "split")) - buf = df.to_json(orient="columns") - with tm.assert_produces_warning(FutureWarning): - tm.assert_frame_equal(df, read_json(buf, "columns")) - buf = df.to_json(orient="index") - with tm.assert_produces_warning(FutureWarning): - tm.assert_frame_equal(df, read_json(buf, "index")) - - def test_good_kwargs(): df = pd.DataFrame({"A": [2, 4, 6], "B": [3, 6, 9]}, index=[0, 1, 2]) with tm.assert_produces_warning(None): diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py index baebc562fc5ff..0829ece64c451 100644 --- a/pandas/tests/io/xml/test_xml.py +++ b/pandas/tests/io/xml/test_xml.py @@ -1096,19 +1096,6 @@ def test_stylesheet_file(datapath): tm.assert_frame_equal(df_kml, df_iter) -def test_read_xml_passing_as_positional_deprecated(datapath, parser): - # GH#45133 - kml = datapath("io", "data", "xml", "cta_rail_lines.kml") - - with tm.assert_produces_warning(FutureWarning, match="keyword-only"): - read_xml( - kml, - ".//k:Placemark", - namespaces={"k": "http://www.opengis.net/kml/2.2"}, - parser=parser, - ) - - @td.skip_if_no("lxml") def test_stylesheet_file_like(datapath, mode): kml = datapath("io", "data", "xml", "cta_rail_lines.kml") diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index 277496d776cb2..d15199e84f7ac 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -697,21 +697,6 @@ def test_concat_multiindex_with_empty_rangeindex(): tm.assert_frame_equal(result, expected) -def test_concat_posargs_deprecation(): - # https://github.com/pandas-dev/pandas/issues/41485 - df = DataFrame([[1, 2, 3]], index=["a"]) - df2 = DataFrame([[4, 5, 6]], index=["b"]) - - msg = ( - "In a future version of pandas all arguments of concat " - "except for the argument 'objs' will be keyword-only" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = concat([df, df2], 0) - expected = DataFrame([[1, 2, 3], [4, 5, 6]], index=["a", "b"]) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( "data", [ diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 8c2c1026d5c82..464eca412daed 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -481,11 +481,9 @@ def test_pivot_index_with_nan(self, method): } ) if method: - with tm.assert_produces_warning(FutureWarning): - result = df.pivot("a", columns="b", values="c") + result = df.pivot(index="a", columns="b", values="c") else: - with tm.assert_produces_warning(FutureWarning): - result = pd.pivot(df, "a", columns="b", values="c") + result = pd.pivot(df, index="a", columns="b", values="c") expected = DataFrame( [ [nan, nan, 17, nan], diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py index c46f427fd6f09..fc2f636199493 100644 --- a/pandas/tests/series/methods/test_interpolate.py +++ b/pandas/tests/series/methods/test_interpolate.py @@ -811,15 +811,3 @@ def test_interpolate_unsorted_index(self, ascending, expected_values): result = ts.sort_index(ascending=ascending).interpolate(method="index") expected = Series(data=expected_values, index=expected_values, dtype=float) tm.assert_series_equal(result, expected) - - def test_interpolate_pos_args_deprecation(self): - # https://github.com/pandas-dev/pandas/issues/41485 - ser = Series([1, 2, 3]) - msg = ( - r"In a future version of pandas all arguments of Series.interpolate except " - r"for the argument 'method' will be keyword-only" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = ser.interpolate("pad", 0) - expected = Series([1, 2, 3]) - tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py index d7bd92c673e69..4df6f52e0fff4 100644 --- a/pandas/tests/series/methods/test_sort_index.py +++ b/pandas/tests/series/methods/test_sort_index.py @@ -320,15 +320,3 @@ def test_sort_values_key_type(self): result = s.sort_index(key=lambda x: x.month_name()) expected = s.iloc[[2, 1, 0]] tm.assert_series_equal(result, expected) - - def test_sort_index_pos_args_deprecation(self): - # https://github.com/pandas-dev/pandas/issues/41485 - ser = Series([1, 2, 3]) - msg = ( - r"In a future version of pandas all arguments of Series.sort_index " - r"will be keyword-only" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = ser.sort_index(0) - expected = Series([1, 2, 3]) - tm.assert_series_equal(result, expected)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49302
2022-10-25T14:40:12Z
2022-10-26T17:46:29Z
2022-10-26T17:46:29Z
2022-10-26T17:49:06Z
DEPR: inplace arg in Categorical.remove_unused_categories
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 87c19ab164c82..67b7213801ce8 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -190,6 +190,7 @@ Removal of prior version deprecations/changes - Removed argument ``tz`` from :meth:`Period.to_timestamp`, use ``obj.to_timestamp(...).tz_localize(tz)`` instead (:issue:`34522`) - Removed argument ``is_copy`` from :meth:`DataFrame.take` and :meth:`Series.take` (:issue:`30615`) - Removed argument ``kind`` from :meth:`Index.get_slice_bound`, :meth:`Index.slice_indexer` and :meth:`Index.slice_locs` (:issue:`41378`) +- Removed argument ``inplace`` from :meth:`Categorical.remove_unused_categories` (:issue:`37918`) - Disallow passing non-round floats to :class:`Timestamp` with ``unit="M"`` or ``unit="Y"`` (:issue:`47266`) - Remove keywords ``convert_float`` and ``mangle_dupe_cols`` from :func:`read_excel` (:issue:`41176`) - Disallow passing non-keyword arguments to :func:`read_excel` except ``io`` and ``sheet_name`` (:issue:`34418`) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 9326b84f8e3be..b3650173e41ef 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1393,35 +1393,14 @@ def remove_categories(self, removals, inplace=no_default): new_categories, ordered=self.ordered, rename=False, inplace=inplace ) - @overload - def remove_unused_categories( - self, *, inplace: Literal[False] | NoDefault = ... - ) -> Categorical: - ... - - @overload - def remove_unused_categories(self, *, inplace: Literal[True]) -> None: - ... - - @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) - def remove_unused_categories( - self, inplace: bool | NoDefault = no_default - ) -> Categorical | None: + def remove_unused_categories(self) -> Categorical: """ Remove categories which are not used. - Parameters - ---------- - inplace : bool, default False - Whether or not to drop unused categories inplace or return a copy of - this categorical with unused categories dropped. - - .. deprecated:: 1.2.0 - Returns ------- - cat : Categorical or None - Categorical with unused categories dropped or None if ``inplace=True``. + cat : Categorical + Categorical with unused categories dropped. See Also -------- @@ -1448,33 +1427,20 @@ def remove_unused_categories( ['a', 'c', 'a', 'c', 'c'] Categories (2, object): ['a', 'c'] """ - if inplace is not no_default: - warn( - "The `inplace` parameter in pandas.Categorical." - "remove_unused_categories is deprecated and " - "will be removed in a future version.", - FutureWarning, - stacklevel=find_stack_level(), - ) - else: - inplace = False - - inplace = validate_bool_kwarg(inplace, "inplace") - cat = self if inplace else self.copy() - idx, inv = np.unique(cat._codes, return_inverse=True) + idx, inv = np.unique(self._codes, return_inverse=True) if idx.size != 0 and idx[0] == -1: # na sentinel idx, inv = idx[1:], inv - 1 - new_categories = cat.dtype.categories.take(idx) + new_categories = self.dtype.categories.take(idx) new_dtype = CategoricalDtype._from_fastpath( new_categories, ordered=self.ordered ) new_codes = coerce_indexer_dtype(inv, new_dtype.categories) + + cat = self.copy() NDArrayBacked.__init__(cat, new_codes, new_dtype) - if not inplace: - return cat - return None + return cat # ------------------------------------------------------------------ diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py index e9f4be11ee4b7..2723b838c41a2 100644 --- a/pandas/tests/arrays/categorical/test_analytics.py +++ b/pandas/tests/arrays/categorical/test_analytics.py @@ -363,11 +363,6 @@ def test_validate_inplace_raises(self, value): # issue #37643 inplace kwarg deprecated cat.remove_categories(removals=["D", "E", "F"], inplace=value) - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - cat.remove_unused_categories(inplace=value) - with pytest.raises(ValueError, match=msg): cat.sort_values(inplace=value) diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py index 03bd1c522838d..2f13d4ee0dd40 100644 --- a/pandas/tests/arrays/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -422,13 +422,6 @@ def test_remove_unused_categories(self): tm.assert_index_equal(res.categories, exp_categories_dropped) tm.assert_index_equal(c.categories, exp_categories_all) - with tm.assert_produces_warning(FutureWarning): - # issue #37643 inplace kwarg deprecated - res = c.remove_unused_categories(inplace=True) - - tm.assert_index_equal(c.categories, exp_categories_dropped) - assert res is None - # with NaN values (GH11599) c = Categorical(["a", "b", "c", np.nan], categories=["a", "b", "c", "d", "e"]) res = c.remove_unused_categories() diff --git a/pandas/tests/series/accessors/test_cat_accessor.py b/pandas/tests/series/accessors/test_cat_accessor.py index 750e84b8cde08..48a01f0018775 100644 --- a/pandas/tests/series/accessors/test_cat_accessor.py +++ b/pandas/tests/series/accessors/test_cat_accessor.py @@ -78,17 +78,6 @@ def test_cat_accessor_no_new_attributes(self): with pytest.raises(AttributeError, match="You cannot add any new attribute"): cat.cat.xlabel = "a" - def test_cat_accessor_updates_on_inplace(self): - ser = Series(list("abc")).astype("category") - return_value = ser.drop(0, inplace=True) - assert return_value is None - - with tm.assert_produces_warning(FutureWarning): - return_value = ser.cat.remove_unused_categories(inplace=True) - - assert return_value is None - assert len(ser.cat.categories) == 2 - def test_categorical_delegations(self): # invalid accessor
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.0.0.rst` file if fixing a bug or adding a new feature. deprecation introduced in #37918
https://api.github.com/repos/pandas-dev/pandas/pulls/49300
2022-10-25T11:31:01Z
2022-10-25T18:33:20Z
2022-10-25T18:33:20Z
2022-10-26T10:17:55Z
CLN: Index._hidden_attrs
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 1d3efe8bedd94..4c7274c8e5cb2 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -325,13 +325,6 @@ class Index(IndexOpsMixin, PandasObject): Index(['a', 'b', 'c'], dtype='object') """ - # tolist is not actually deprecated, just suppressed in the __dir__ - _hidden_attrs: frozenset[str] = ( - PandasObject._hidden_attrs - | IndexOpsMixin._hidden_attrs - | frozenset(["contains", "set_value"]) - ) - # To hand over control to subclasses _join_precedence = 1
Small cleanup. Both deprecated methods have now been removed.
https://api.github.com/repos/pandas-dev/pandas/pulls/49299
2022-10-25T11:29:09Z
2022-10-27T16:37:18Z
2022-10-27T16:37:18Z
2022-10-30T08:18:21Z
DEPR: Remove xlwt
diff --git a/asv_bench/asv.conf.json b/asv_bench/asv.conf.json index b1ea2682b7ea7..4a0c882640eb6 100644 --- a/asv_bench/asv.conf.json +++ b/asv_bench/asv.conf.json @@ -54,7 +54,6 @@ "openpyxl": [], "xlsxwriter": [], "xlrd": [], - "xlwt": [], "odfpy": [], "jinja2": [], }, diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py index a88c4374b7030..5bd4d832f3dde 100644 --- a/asv_bench/benchmarks/io/excel.py +++ b/asv_bench/benchmarks/io/excel.py @@ -33,7 +33,7 @@ def _generate_dataframe(): class WriteExcel: - params = ["openpyxl", "xlsxwriter", "xlwt"] + params = ["openpyxl", "xlsxwriter"] param_names = ["engine"] def setup(self, engine): @@ -68,10 +68,9 @@ def time_write_excel_style(self, engine): class ReadExcel: - params = ["xlrd", "openpyxl", "odf"] + params = ["openpyxl", "odf"] param_names = ["engine"] fname_excel = "spreadsheet.xlsx" - fname_excel_xls = "spreadsheet.xls" fname_odf = "spreadsheet.ods" def _create_odf(self): @@ -92,13 +91,10 @@ def setup_cache(self): self.df = _generate_dataframe() self.df.to_excel(self.fname_excel, sheet_name="Sheet1") - self.df.to_excel(self.fname_excel_xls, sheet_name="Sheet1") self._create_odf() def time_read_excel(self, engine): - if engine == "xlrd": - fname = self.fname_excel_xls - elif engine == "odf": + if engine == "odf": fname = self.fname_odf else: fname = self.fname_excel @@ -107,9 +103,7 @@ def time_read_excel(self, engine): class ReadExcelNRows(ReadExcel): def time_read_excel(self, engine): - if engine == "xlrd": - fname = self.fname_excel_xls - elif engine == "odf": + if engine == "odf": fname = self.fname_odf else: fname = self.fname_excel diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 113186c746157..c6067faf92d37 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -47,7 +47,7 @@ import pandas blocklist = {'bs4', 'gcsfs', 'html5lib', 'http', 'ipython', 'jinja2', 'hypothesis', 'lxml', 'matplotlib', 'openpyxl', 'py', 'pytest', 's3fs', 'scipy', - 'tables', 'urllib.request', 'xlrd', 'xlsxwriter', 'xlwt'} + 'tables', 'urllib.request', 'xlrd', 'xlsxwriter'} # GH#28227 for some of these check for top-level modules, while others are # more specific (e.g. urllib.request) diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml index da3578e7191eb..9ebc305a0cb0c 100644 --- a/ci/deps/actions-310.yaml +++ b/ci/deps/actions-310.yaml @@ -51,5 +51,4 @@ dependencies: - xarray - xlrd - xlsxwriter - - xlwt - zstandard diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-38-downstream_compat.yaml index 29ad2669afbd2..7e127b9dfebc1 100644 --- a/ci/deps/actions-38-downstream_compat.yaml +++ b/ci/deps/actions-38-downstream_compat.yaml @@ -51,7 +51,6 @@ dependencies: - xarray - xlrd - xlsxwriter - - xlwt - zstandard # downstream packages diff --git a/ci/deps/actions-38-minimum_versions.yaml b/ci/deps/actions-38-minimum_versions.yaml index f92d9958a6248..5540ba01a8f36 100644 --- a/ci/deps/actions-38-minimum_versions.yaml +++ b/ci/deps/actions-38-minimum_versions.yaml @@ -53,5 +53,4 @@ dependencies: - xarray=0.19.0 - xlrd=2.0.1 - xlsxwriter=1.4.3 - - xlwt=1.3.0 - zstandard=0.15.2 diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml index b478b7c900425..825b8aeebfc2f 100644 --- a/ci/deps/actions-38.yaml +++ b/ci/deps/actions-38.yaml @@ -50,5 +50,4 @@ dependencies: - xarray - xlrd - xlsxwriter - - xlwt - zstandard diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml index a12f36ba84cca..1ee96878dbe34 100644 --- a/ci/deps/actions-39.yaml +++ b/ci/deps/actions-39.yaml @@ -51,5 +51,4 @@ dependencies: - xarray - xlrd - xlsxwriter - - xlwt - zstandard diff --git a/ci/deps/circle-38-arm64.yaml b/ci/deps/circle-38-arm64.yaml index 2b65ece881df7..ae4a82d016131 100644 --- a/ci/deps/circle-38-arm64.yaml +++ b/ci/deps/circle-38-arm64.yaml @@ -51,5 +51,4 @@ dependencies: - xarray - xlrd - xlsxwriter - - xlwt - zstandard diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index 5f258973b3db9..ca45540b637ba 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -336,7 +336,6 @@ Can be managed as optional_extra with ``pandas[excel]``. Dependency Minimum Version optional_extra Notes ========================= ================== =============== ============================================================= xlrd 2.0.1 excel Reading Excel -xlwt 1.3.0 excel Writing Excel xlsxwriter 1.4.3 excel Writing Excel openpyxl 3.0.7 excel Reading / writing for xlsx files pyxlsb 1.0.8 excel Reading for xlsb files diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index cf4221d055a27..92bd239d51ae4 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -3466,8 +3466,6 @@ See the :ref:`cookbook<cookbook.excel>` for some advanced strategies. .. warning:: - The `xlwt <https://xlwt.readthedocs.io/en/latest/>`__ package for writing old-style ``.xls`` - excel files is no longer maintained. The `xlrd <https://xlrd.readthedocs.io/en/latest/>`__ package is now only for reading old-style ``.xls`` files. @@ -3481,12 +3479,6 @@ See the :ref:`cookbook<cookbook.excel>` for some advanced strategies. **Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.** This is no longer supported, switch to using ``openpyxl`` instead. - Attempting to use the ``xlwt`` engine will raise a ``FutureWarning`` - unless the option :attr:`io.excel.xls.writer` is set to ``"xlwt"``. - While this option is now deprecated and will also raise a ``FutureWarning``, - it can be globally set and the warning suppressed. Users are recommended to - write ``.xlsx`` files using the ``openpyxl`` engine instead. - .. _io.excel_reader: Reading Excel files @@ -3788,7 +3780,7 @@ written. For example: df.to_excel("path_to_file.xlsx", sheet_name="Sheet1") -Files with a ``.xls`` extension will be written using ``xlwt`` and those with a +Files with a ``.xlsx`` extension will be written using ``xlsxwriter`` (if available) or ``openpyxl``. @@ -3849,20 +3841,13 @@ pandas supports writing Excel files to buffer-like objects such as ``StringIO`` Excel writer engines '''''''''''''''''''' -.. deprecated:: 1.2.0 - - As the `xlwt <https://pypi.org/project/xlwt/>`__ package is no longer - maintained, the ``xlwt`` engine will be removed from a future version - of pandas. This is the only engine in pandas that supports writing to - ``.xls`` files. - pandas chooses an Excel writer via two methods: 1. the ``engine`` keyword argument 2. the filename extension (via the default specified in config options) By default, pandas uses the `XlsxWriter`_ for ``.xlsx``, `openpyxl`_ -for ``.xlsm``, and `xlwt`_ for ``.xls`` files. If you have multiple +for ``.xlsm``. If you have multiple engines installed, you can set the default engine through :ref:`setting the config options <options>` ``io.excel.xlsx.writer`` and ``io.excel.xls.writer``. pandas will fall back on `openpyxl`_ for ``.xlsx`` @@ -3870,14 +3855,12 @@ files if `Xlsxwriter`_ is not available. .. _XlsxWriter: https://xlsxwriter.readthedocs.io .. _openpyxl: https://openpyxl.readthedocs.io/ -.. _xlwt: http://www.python-excel.org To specify which writer you want to use, you can pass an engine keyword argument to ``to_excel`` and to ``ExcelWriter``. The built-in engines are: * ``openpyxl``: version 2.4 or higher is required * ``xlsxwriter`` -* ``xlwt`` .. code-block:: python diff --git a/environment.yml b/environment.yml index 391d7bc779af9..f6ef6367800bd 100644 --- a/environment.yml +++ b/environment.yml @@ -53,7 +53,6 @@ dependencies: - xarray - xlrd - xlsxwriter - - xlwt - zstandard # downstream packages diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index 34e3234390ba5..856fb5e4cb66b 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -43,7 +43,6 @@ "tabulate": "0.8.9", "xarray": "0.19.0", "xlrd": "2.0.1", - "xlwt": "1.3.0", "xlsxwriter": "1.4.3", "zstandard": "0.15.2", "tzdata": "2022.1", diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index e6bdbbcb5aa12..b101b25a10a80 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -624,27 +624,11 @@ def use_inf_as_na_cb(key) -> None: auto, {others}. """ -_xls_options = ["xlwt"] _xlsm_options = ["openpyxl"] _xlsx_options = ["openpyxl", "xlsxwriter"] _ods_options = ["odf"] -with cf.config_prefix("io.excel.xls"): - cf.register_option( - "writer", - "auto", - writer_engine_doc.format(ext="xls", others=", ".join(_xls_options)), - validator=str, - ) -cf.deprecate_option( - "io.excel.xls.writer", - msg="As the xlwt package is no longer maintained, the xlwt engine will be " - "removed in a future version of pandas. This is the only engine in pandas that " - "supports writing in the xls format. Install openpyxl and write to an " - "xlsx file instead.", -) - with cf.config_prefix("io.excel.xlsm"): cf.register_option( "writer", diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a1f799ec5122a..f7fd3e9b0e01c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2260,15 +2260,9 @@ def to_excel( Upper left cell column to dump data frame. engine : str, optional Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this - via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and + via the options ``io.excel.xlsx.writer`` or ``io.excel.xlsm.writer``. - .. deprecated:: 1.2.0 - - As the `xlwt <https://pypi.org/project/xlwt/>`__ package is no longer - maintained, the ``xlwt`` engine will be removed in a future version - of pandas. - merge_cells : bool, default True Write MultiIndex and Hierarchical Rows as merged cells. encoding : str, optional diff --git a/pandas/io/excel/__init__.py b/pandas/io/excel/__init__.py index 854e2a1ec3a73..275cbf0148f94 100644 --- a/pandas/io/excel/__init__.py +++ b/pandas/io/excel/__init__.py @@ -7,17 +7,12 @@ from pandas.io.excel._openpyxl import OpenpyxlWriter as _OpenpyxlWriter from pandas.io.excel._util import register_writer from pandas.io.excel._xlsxwriter import XlsxWriter as _XlsxWriter -from pandas.io.excel._xlwt import XlwtWriter as _XlwtWriter __all__ = ["read_excel", "ExcelWriter", "ExcelFile"] register_writer(_OpenpyxlWriter) - -register_writer(_XlwtWriter) - - register_writer(_XlsxWriter) diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 19edb9acf0aa4..bc3abfb94f31c 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -893,7 +893,6 @@ class ExcelWriter(metaclass=abc.ABCMeta): Default is to use: - * `xlwt <https://pypi.org/project/xlwt/>`__ for xls files * `xlsxwriter <https://pypi.org/project/XlsxWriter/>`__ for xlsx files if xlsxwriter is installed otherwise `openpyxl <https://pypi.org/project/openpyxl/>`__ * `odswriter <https://pypi.org/project/odswriter/>`__ for ods files @@ -911,13 +910,6 @@ class ExcelWriter(metaclass=abc.ABCMeta): Engine to use for writing. If None, defaults to ``io.excel.<extension>.writer``. NOTE: can only be passed as a keyword argument. - - .. deprecated:: 1.2.0 - - As the `xlwt <https://pypi.org/project/xlwt/>`__ package is no longer - maintained, the ``xlwt`` engine will be removed in a future - version of pandas. - date_format : str, default None Format string for dates written into Excel files (e.g. 'YYYY-MM-DD'). datetime_format : str, default None @@ -1127,25 +1119,6 @@ def __new__( except KeyError as err: raise ValueError(f"No engine for filetype: '{ext}'") from err - if engine == "xlwt": - xls_config_engine = config.get_option( - "io.excel.xls.writer", silent=True - ) - # Don't warn a 2nd time if user has changed the default engine for xls - if xls_config_engine != "xlwt": - warnings.warn( - "As the xlwt package is no longer maintained, the xlwt " - "engine will be removed in a future version of pandas. " - "This is the only engine in pandas that supports writing " - "in the xls format. Install openpyxl and write to an xlsx " - "file instead. You can set the option io.excel.xls.writer " - "to 'xlwt' to silence this warning. While this option is " - "deprecated and will also raise a warning, it can " - "be globally set and the warning suppressed.", - FutureWarning, - stacklevel=find_stack_level(), - ) - # for mypy assert engine is not None cls = get_writer(engine) diff --git a/pandas/io/excel/_util.py b/pandas/io/excel/_util.py index c315657170a97..72c64c5ec8939 100644 --- a/pandas/io/excel/_util.py +++ b/pandas/io/excel/_util.py @@ -73,7 +73,6 @@ def get_default_engine(ext: str, mode: Literal["reader", "writer"] = "reader") - "xlsx": "openpyxl", "xlsm": "openpyxl", "xlsb": "pyxlsb", - "xls": "xlwt", "ods": "odf", } assert mode in ["reader", "writer"] diff --git a/pandas/io/excel/_xlwt.py b/pandas/io/excel/_xlwt.py deleted file mode 100644 index f1455e472bb43..0000000000000 --- a/pandas/io/excel/_xlwt.py +++ /dev/null @@ -1,228 +0,0 @@ -from __future__ import annotations - -from typing import ( - TYPE_CHECKING, - Any, - Tuple, - cast, -) - -import pandas._libs.json as json -from pandas._typing import ( - FilePath, - StorageOptions, - WriteExcelBuffer, -) - -from pandas.io.excel._base import ExcelWriter -from pandas.io.excel._util import ( - combine_kwargs, - validate_freeze_panes, -) - -if TYPE_CHECKING: - from xlwt import ( - Workbook, - XFStyle, - ) - - -class XlwtWriter(ExcelWriter): - _engine = "xlwt" - _supported_extensions = (".xls",) - - def __init__( - self, - path: FilePath | WriteExcelBuffer | ExcelWriter, - engine: str | None = None, - date_format: str | None = None, - datetime_format: str | None = None, - encoding: str | None = None, - mode: str = "w", - storage_options: StorageOptions = None, - if_sheet_exists: str | None = None, - engine_kwargs: dict[str, Any] | None = None, - **kwargs, - ) -> None: - # Use the xlwt module as the Excel writer. - import xlwt - - engine_kwargs = combine_kwargs(engine_kwargs, kwargs) - - if mode == "a": - raise ValueError("Append mode is not supported with xlwt!") - - super().__init__( - path, - mode=mode, - storage_options=storage_options, - if_sheet_exists=if_sheet_exists, - engine_kwargs=engine_kwargs, - ) - - if encoding is None: - encoding = "ascii" - self._book = xlwt.Workbook(encoding=encoding, **engine_kwargs) - self._fm_datetime = xlwt.easyxf(num_format_str=self._datetime_format) - self._fm_date = xlwt.easyxf(num_format_str=self._date_format) - - @property - def book(self) -> Workbook: - """ - Book instance of class xlwt.Workbook. - - This attribute can be used to access engine-specific features. - """ - return self._book - - @book.setter - def book(self, other: Workbook) -> None: - """ - Set book instance. Class type will depend on the engine used. - """ - self._deprecate_set_book() - self._book = other - - @property - def sheets(self) -> dict[str, Any]: - """Mapping of sheet names to sheet objects.""" - result = {sheet.name: sheet for sheet in self.book._Workbook__worksheets} - return result - - @property - def fm_date(self): - """ - XFStyle formatter for dates. - """ - self._deprecate("fm_date") - return self._fm_date - - @property - def fm_datetime(self): - """ - XFStyle formatter for dates. - """ - self._deprecate("fm_datetime") - return self._fm_datetime - - def _save(self) -> None: - """ - Save workbook to disk. - """ - if self.sheets: - # fails when the ExcelWriter is just opened and then closed - self.book.save(self._handles.handle) - - def _write_cells( - self, - cells, - sheet_name: str | None = None, - startrow: int = 0, - startcol: int = 0, - freeze_panes: tuple[int, int] | None = None, - ) -> None: - - sheet_name = self._get_sheet_name(sheet_name) - - if sheet_name in self.sheets: - wks = self.sheets[sheet_name] - else: - wks = self.book.add_sheet(sheet_name) - self.sheets[sheet_name] = wks - - if validate_freeze_panes(freeze_panes): - freeze_panes = cast(Tuple[int, int], freeze_panes) - wks.set_panes_frozen(True) - wks.set_horz_split_pos(freeze_panes[0]) - wks.set_vert_split_pos(freeze_panes[1]) - - style_dict: dict[str, XFStyle] = {} - - for cell in cells: - val, fmt = self._value_with_fmt(cell.val) - - stylekey = json.dumps(cell.style) - if fmt: - stylekey += fmt - - if stylekey in style_dict: - style = style_dict[stylekey] - else: - style = self._convert_to_style(cell.style, fmt) - style_dict[stylekey] = style - - if cell.mergestart is not None and cell.mergeend is not None: - wks.write_merge( - startrow + cell.row, - startrow + cell.mergestart, - startcol + cell.col, - startcol + cell.mergeend, - val, - style, - ) - else: - wks.write(startrow + cell.row, startcol + cell.col, val, style) - - @classmethod - def _style_to_xlwt( - cls, item, firstlevel: bool = True, field_sep: str = ",", line_sep: str = ";" - ) -> str: - """ - helper which recursively generate an xlwt easy style string - for example: - - hstyle = {"font": {"bold": True}, - "border": {"top": "thin", - "right": "thin", - "bottom": "thin", - "left": "thin"}, - "align": {"horiz": "center"}} - will be converted to - font: bold on; \ - border: top thin, right thin, bottom thin, left thin; \ - align: horiz center; - """ - if hasattr(item, "items"): - if firstlevel: - it = [ - f"{key}: {cls._style_to_xlwt(value, False)}" - for key, value in item.items() - ] - out = f"{line_sep.join(it)} " - return out - else: - it = [ - f"{key} {cls._style_to_xlwt(value, False)}" - for key, value in item.items() - ] - out = f"{field_sep.join(it)} " - return out - else: - item = f"{item}" - item = item.replace("True", "on") - item = item.replace("False", "off") - return item - - @classmethod - def _convert_to_style( - cls, style_dict, num_format_str: str | None = None - ) -> XFStyle: - """ - converts a style_dict to an xlwt style object - - Parameters - ---------- - style_dict : style dictionary to convert - num_format_str : optional number format string - """ - import xlwt - - if style_dict: - xlwt_stylestr = cls._style_to_xlwt(style_dict) - style = xlwt.easyxf(xlwt_stylestr, field_sep=",", line_sep=";") - else: - style = xlwt.XFStyle() - if num_format_str is not None: - style.num_format_str = num_format_str - - return style diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 466ffe5ac1b49..5c9b3a76123c4 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -879,14 +879,8 @@ def write( is to be frozen engine : string, default None write engine to use if writer is a path - you can also set this - via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, - and ``io.excel.xlsm.writer``. - - .. deprecated:: 1.2.0 - - As the `xlwt <https://pypi.org/project/xlwt/>`__ package is no longer - maintained, the ``xlwt`` engine will be removed in a future - version of pandas. + via the options ``io.excel.xlsx.writer``, + or ``io.excel.xlsm.writer``. {storage_options} diff --git a/pandas/tests/io/__init__.py b/pandas/tests/io/__init__.py index 3231e38b985af..c99d03afc8320 100644 --- a/pandas/tests/io/__init__.py +++ b/pandas/tests/io/__init__.py @@ -20,8 +20,4 @@ r"Use 'tree.iter\(\)' or 'list\(tree.iter\(\)\)' instead." ":PendingDeprecationWarning" ), - # GH 26552 - pytest.mark.filterwarnings( - "ignore:As the xlwt package is no longer maintained:FutureWarning" - ), ] diff --git a/pandas/tests/io/excel/__init__.py b/pandas/tests/io/excel/__init__.py index e7a182ea63178..9136153101e23 100644 --- a/pandas/tests/io/excel/__init__.py +++ b/pandas/tests/io/excel/__init__.py @@ -9,10 +9,6 @@ pytest.mark.filterwarnings( "ignore:This method will be removed in future versions:DeprecationWarning" ), - # GH 26552 - pytest.mark.filterwarnings( - "ignore:As the xlwt package is no longer maintained:FutureWarning" - ), # GH 38571 pytest.mark.filterwarnings( "ignore:.*In xlrd >= 2.0, only the xls format is supported:FutureWarning" diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 62c93de4d44aa..8ad15ac05e26a 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -538,8 +538,8 @@ def test_reader_dtype_str(self, read_ext, dtype, expected): def test_use_nullable_dtypes(self, read_ext): # GH#36712 - if read_ext == ".xlsb": - pytest.skip("No engine for filetype: 'xlsb'") + if read_ext in (".xlsb", ".xls"): + pytest.skip(f"No engine for filetype: '{read_ext}'") df = DataFrame( { @@ -564,8 +564,8 @@ def test_use_nullable_dtypes(self, read_ext): def test_use_nullabla_dtypes_and_dtype(self, read_ext): # GH#36712 - if read_ext == ".xlsb": - pytest.skip("No engine for filetype: 'xlsb'") + if read_ext in (".xlsb", ".xls"): + pytest.skip(f"No engine for filetype: '{read_ext}'") df = DataFrame({"a": [np.nan, 1.0], "b": [2.5, np.nan]}) with tm.ensure_clean(read_ext) as file_path: @@ -579,8 +579,8 @@ def test_use_nullabla_dtypes_and_dtype(self, read_ext): @pytest.mark.parametrize("storage", ["pyarrow", "python"]) def test_use_nullabla_dtypes_string(self, read_ext, storage): # GH#36712 - if read_ext == ".xlsb": - pytest.skip("No engine for filetype: 'xlsb'") + if read_ext in (".xlsb", ".xls"): + pytest.skip(f"No engine for filetype: '{read_ext}'") import pyarrow as pa diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 897d6969ea6ae..307f8b7a7798f 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -27,7 +27,6 @@ ExcelWriter, _OpenpyxlWriter, _XlsxWriter, - _XlwtWriter, register_writer, ) @@ -61,7 +60,6 @@ def set_engine(engine, ext): [ pytest.param(".xlsx", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]), pytest.param(".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]), - pytest.param(".xls", marks=[td.skip_if_no("xlwt"), td.skip_if_no("xlrd")]), pytest.param( ".xlsx", marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")] ), @@ -319,9 +317,6 @@ def test_multiindex_interval_datetimes(self, ext): ".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")], ), - pytest.param( - "xlwt", ".xls", marks=[td.skip_if_no("xlwt"), td.skip_if_no("xlrd")] - ), pytest.param( "xlsxwriter", ".xlsx", @@ -1283,7 +1278,6 @@ class TestExcelWriterEngineTests: [ pytest.param(_XlsxWriter, ".xlsx", marks=td.skip_if_no("xlsxwriter")), pytest.param(_OpenpyxlWriter, ".xlsx", marks=td.skip_if_no("openpyxl")), - pytest.param(_XlwtWriter, ".xls", marks=td.skip_if_no("xlwt")), ], ) def test_ExcelWriter_dispatch(self, klass, ext): diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py index 86141f08f5f2d..30dddbd7de50b 100644 --- a/pandas/tests/io/excel/test_xlrd.py +++ b/pandas/tests/io/excel/test_xlrd.py @@ -11,12 +11,6 @@ from pandas.io.excel._base import inspect_excel_format xlrd = pytest.importorskip("xlrd") -xlwt = pytest.importorskip("xlwt") - -pytestmark = pytest.mark.filterwarnings( - "ignore:As the xlwt package is no longer maintained:FutureWarning" -) - exts = [".xls"] @@ -31,23 +25,18 @@ def read_ext_xlrd(request): return request.param -def test_read_xlrd_book(read_ext_xlrd, frame): - df = frame - +def test_read_xlrd_book(read_ext_xlrd, datapath): engine = "xlrd" - sheet_name = "SheetA" - - with tm.ensure_clean(read_ext_xlrd) as pth: - df.to_excel(pth, sheet_name) - with xlrd.open_workbook(pth) as book: - with ExcelFile(book, engine=engine) as xl: - result = pd.read_excel(xl, sheet_name=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) + sheet_name = "Sheet1" + pth = datapath("io", "data", "excel", "test1.xls") + with xlrd.open_workbook(pth) as book: + with ExcelFile(book, engine=engine) as xl: + result = pd.read_excel(xl, sheet_name=sheet_name, index_col=0) + + expected = pd.read_excel( + book, sheet_name=sheet_name, engine=engine, index_col=0 + ) + tm.assert_frame_equal(result, expected) def test_excel_file_warning_with_xlsx_file(datapath): diff --git a/pandas/tests/io/excel/test_xlwt.py b/pandas/tests/io/excel/test_xlwt.py deleted file mode 100644 index 3aa405eb1e275..0000000000000 --- a/pandas/tests/io/excel/test_xlwt.py +++ /dev/null @@ -1,146 +0,0 @@ -import re - -import numpy as np -import pytest - -from pandas import ( - DataFrame, - MultiIndex, - options, -) -import pandas._testing as tm - -from pandas.io.excel import ( - ExcelWriter, - _XlwtWriter, -) - -xlwt = pytest.importorskip("xlwt") - -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) - - msg = ( - "Writing to Excel with MultiIndex columns and no index " - "\\('index'=False\\) is not yet implemented." - ) - with pytest.raises(NotImplementedError, match=msg): - with tm.ensure_clean(ext) as path: - df.to_excel(path, index=False) - - -def test_excel_multiindex_columns_and_index_true(ext): - cols = MultiIndex.from_tuples( - [("site", ""), ("2014", "height"), ("2014", "weight")] - ) - df = DataFrame(np.random.randn(10, 3), columns=cols) - with tm.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 tm.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 tm.ensure_clean(ext) as f: - with pytest.raises(ValueError, match=msg): - ExcelWriter(f, engine="xlwt", mode="a") - - -def test_to_excel_xlwt_warning(ext): - # GH 26552 - df = DataFrame(np.random.randn(3, 10)) - with tm.ensure_clean(ext) as path: - with tm.assert_produces_warning( - FutureWarning, - match="As the xlwt package is no longer maintained", - ): - df.to_excel(path) - - -def test_option_xls_writer_deprecated(ext): - # GH 26552 - with tm.assert_produces_warning( - FutureWarning, - match="As the xlwt package is no longer maintained", - check_stacklevel=False, - ): - options.io.excel.xls.writer = "xlwt" - - -@pytest.mark.parametrize("style_compression", [0, 2]) -def test_kwargs(ext, style_compression): - # GH 42286 - kwargs = {"style_compression": style_compression} - with tm.ensure_clean(ext) as f: - msg = re.escape("Use of **kwargs is deprecated") - with tm.assert_produces_warning(FutureWarning, match=msg): - with ExcelWriter(f, engine="xlwt", **kwargs) as writer: - assert ( - writer.book._Workbook__styles.style_compression == style_compression - ) - # xlwt won't allow us to close without writing something - DataFrame().to_excel(writer) - - -@pytest.mark.parametrize("style_compression", [0, 2]) -def test_engine_kwargs(ext, style_compression): - # GH 42286 - engine_kwargs = {"style_compression": style_compression} - with tm.ensure_clean(ext) as f: - with ExcelWriter(f, engine="xlwt", engine_kwargs=engine_kwargs) as writer: - assert writer.book._Workbook__styles.style_compression == style_compression - # xlwt won't allow us to close without writing something - DataFrame().to_excel(writer) - - -def test_book_and_sheets_consistent(ext): - # GH#45687 - Ensure sheets is updated if user modifies book - with tm.ensure_clean(ext) as f: - with ExcelWriter(f) as writer: - assert writer.sheets == {} - sheet = writer.book.add_sheet("test_name") - assert writer.sheets == {"test_name": sheet} - - -@pytest.mark.parametrize("attr", ["fm_date", "fm_datetime"]) -def test_deprecated_attr(ext, attr): - # GH#45572 - with tm.ensure_clean(ext) as path: - with ExcelWriter(path, engine="xlwt") as writer: - msg = f"{attr} is not part of the public API" - with tm.assert_produces_warning(FutureWarning, match=msg): - getattr(writer, attr) diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index 4a6ec7cfd2ae3..ec48357e0395d 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -342,7 +342,7 @@ def test_read_fspath_all(self, reader, module, path, datapath): "writer_name, writer_kwargs, module", [ ("to_csv", {}, "os"), - ("to_excel", {"engine": "xlwt"}, "xlwt"), + ("to_excel", {"engine": "openpyxl"}, "openpyxl"), ("to_feather", {}, "pyarrow"), ("to_html", {}, "os"), ("to_json", {}, "os"), diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py index 82f5bdda2a4c5..bdd4cd95ec1af 100644 --- a/pandas/tests/io/test_fsspec.py +++ b/pandas/tests/io/test_fsspec.py @@ -74,13 +74,9 @@ def test_to_csv(cleared_fs, df1): tm.assert_frame_equal(df1, df2) -@pytest.mark.parametrize("ext", ["xls", "xlsx"]) -def test_to_excel(cleared_fs, ext, df1): - if ext == "xls": - pytest.importorskip("xlwt") - else: - pytest.importorskip("openpyxl") - +def test_to_excel(cleared_fs, df1): + pytest.importorskip("openpyxl") + ext = "xlsx" path = f"memory://test/test.{ext}" df1.to_excel(path, index=True) @@ -132,12 +128,9 @@ def test_read_table_options(fsspectest): assert fsspectest.test[0] == "csv_read" -@pytest.mark.parametrize("extension", ["xlsx", "xls"]) -def test_excel_options(fsspectest, extension): - if extension == "xls": - pytest.importorskip("xlwt") - else: - pytest.importorskip("openpyxl") +def test_excel_options(fsspectest): + pytest.importorskip("openpyxl") + extension = "xlsx" df = DataFrame({"a": [0]}) diff --git a/pandas/tests/io/test_gcs.py b/pandas/tests/io/test_gcs.py index 3e94a31b3b25c..e3333025da547 100644 --- a/pandas/tests/io/test_gcs.py +++ b/pandas/tests/io/test_gcs.py @@ -74,7 +74,7 @@ def test_to_read_gcs(gcs_buffer, format): df1.to_csv(path, index=True) df2 = read_csv(path, parse_dates=["dt"], index_col=0) elif format == "excel": - path = "gs://test/test.xls" + path = "gs://test/test.xlsx" df1.to_excel(path) df2 = read_excel(path, parse_dates=["dt"], index_col=0) elif format == "json": diff --git a/requirements-dev.txt b/requirements-dev.txt index 90e4c6dca5ff1..5e98113625374 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -44,7 +44,6 @@ tzdata>=2022.1 xarray xlrd xlsxwriter -xlwt zstandard aiobotocore<2.0.0 botocore diff --git a/setup.cfg b/setup.cfg index eede4a66d598d..d80d09725d18b 100644 --- a/setup.cfg +++ b/setup.cfg @@ -78,7 +78,6 @@ excel = openpyxl>=3.0.7 pyxlsb>=1.0.8 xlrd>=2.0.1 - xlwt>=1.3.0 xlsxwriter>=1.4.3 parquet = pyarrow>=6.0.0 @@ -158,7 +157,6 @@ all = xarray>=0.19.0 xlrd>=2.0.1 xlsxwriter>=1.4.3 - xlwt>=1.3.0 zstandard>=0.15.2 [build_ext]
Introduced in https://github.com/pandas-dev/pandas/pull/38317
https://api.github.com/repos/pandas-dev/pandas/pulls/49296
2022-10-25T00:41:59Z
2022-10-27T16:10:05Z
2022-10-27T16:10:05Z
2022-10-27T16:10:09Z
DEPR: Configuration options
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 1050eed40fbb4..e54f08dd44361 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -224,6 +224,8 @@ Removal of prior version deprecations/changes - Enforced disallowing a string column label into ``times`` in :meth:`DataFrame.ewm` (:issue:`43265`) - Removed setting Categorical._codes directly (:issue:`41429`) - Enforced :meth:`Rolling.count` with ``min_periods=None`` to default to the size of the window (:issue:`31302`) +- Enforced the ``display.max_colwidth`` option to not accept negative integers (:issue:`31569`) +- Removed the ``display.column_space`` option in favor of ``df.to_string(col_space=...)`` (:issue:`47280`) - Removed the deprecated method ``mad`` from pandas classes (:issue:`11787`) - Removed the deprecated method ``tshift`` from pandas classes (:issue:`11631`) diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 378f9dc80bb6d..e6bdbbcb5aa12 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -13,7 +13,6 @@ import os from typing import Callable -import warnings import pandas._config.config as cf from pandas._config.config import ( @@ -27,8 +26,6 @@ is_text, ) -from pandas.util._exceptions import find_stack_level - # compute use_bottleneck_doc = """ @@ -363,17 +360,6 @@ def is_terminal() -> bool: float_format_doc, validator=is_one_of_factory([None, is_callable]), ) - - def _deprecate_column_space(key) -> None: - warnings.warn( - "column_space is deprecated and will be removed " - "in a future version. Use df.to_string(col_space=...) " - "instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - - cf.register_option("column_space", 12, validator=is_int, cb=_deprecate_column_space) cf.register_option( "max_info_rows", 1690785, @@ -389,24 +375,11 @@ def _deprecate_column_space(key) -> None: ) cf.register_option("max_categories", 8, pc_max_categories_doc, validator=is_int) - def _deprecate_negative_int_max_colwidth(key) -> None: - value = cf.get_option(key) - if value is not None and value < 0: - warnings.warn( - "Passing a negative integer is deprecated in version 1.0 and " - "will not be supported in future version. Instead, use None " - "to not limit the column width.", - FutureWarning, - stacklevel=find_stack_level(), - ) - cf.register_option( - # TODO(2.0): change `validator=is_nonnegative_int` see GH#31569 "max_colwidth", 50, max_colwidth_doc, - validator=is_instance_factory([type(None), int]), - cb=_deprecate_negative_int_max_colwidth, + validator=is_nonnegative_int, ) if is_terminal(): max_cols = 0 # automatically determine optimal number of columns diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 0b3f6395e51d7..b3e2e81e95613 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -252,12 +252,13 @@ def test_repr_truncation(self): with option_context("display.max_colwidth", max_len + 2): assert "..." not in repr(df) - def test_repr_deprecation_negative_int(self): - # TODO(2.0): remove in future version after deprecation cycle - # Non-regression test for: + def test_max_colwidth_negative_int_raises(self): + # Deprecation enforced from: # https://github.com/pandas-dev/pandas/issues/31532 width = get_option("display.max_colwidth") - with tm.assert_produces_warning(FutureWarning): + with pytest.raises( + ValueError, match="Value must be a nonnegative integer or None" + ): set_option("display.max_colwidth", -1) set_option("display.max_colwidth", width) @@ -3483,9 +3484,3 @@ def test_filepath_or_buffer_bad_arg_raises(float_frame, method): msg = "buf is not a file name and it has no write method" with pytest.raises(TypeError, match=msg): getattr(float_frame, method)(buf=object()) - - -def test_col_space_deprecated(): - # GH 7576 - with tm.assert_produces_warning(FutureWarning, match="column_space is"): - set_option("display.column_space", 11)
Introduced in https://github.com/pandas-dev/pandas/pull/31569, https://github.com/pandas-dev/pandas/pull/47280
https://api.github.com/repos/pandas-dev/pandas/pulls/49295
2022-10-24T23:56:25Z
2022-10-25T14:04:40Z
2022-10-25T14:04:39Z
2022-10-25T17:45:39Z
DEPR: Remove pandas.util.testing
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 1050eed40fbb4..e45ad840a9804 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -218,6 +218,7 @@ Removal of prior version deprecations/changes - Removed the ``truediv`` keyword from :func:`eval` (:issue:`29812`) - Removed the ``pandas.datetime`` submodule (:issue:`30489`) - Removed the ``pandas.np`` submodule (:issue:`30296`) +- Removed ``pandas.util.testing`` in favor of ``pandas.testing`` (:issue:`30745`) - Removed :meth:`Series.str.__iter__` (:issue:`28277`) - Removed ``pandas.SparseArray`` in favor of :class:`arrays.SparseArray` (:issue:`30642`) - Removed ``pandas.SparseSeries`` and ``pandas.SparseDataFrame`` (:issue:`30642`) diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index be704d8eb3e7e..b3a60c1fc5d37 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -1,8 +1,5 @@ from __future__ import annotations -import subprocess -import sys - import pytest import pandas as pd @@ -260,36 +257,6 @@ def test_testing(self): self.check(testing, self.funcs) - def test_util_testing_deprecated(self): - # avoid cache state affecting the test - sys.modules.pop("pandas.util.testing", None) - - with tm.assert_produces_warning(FutureWarning) as m: - import pandas.util.testing # noqa: F401 - - assert "pandas.util.testing is deprecated" in str(m[0].message) - assert "pandas.testing instead" in str(m[0].message) - - def test_util_testing_deprecated_direct(self): - # avoid cache state affecting the test - sys.modules.pop("pandas.util.testing", None) - with tm.assert_produces_warning(FutureWarning) as m: - from pandas.util.testing import assert_series_equal # noqa: F401 - - assert "pandas.util.testing is deprecated" in str(m[0].message) - assert "pandas.testing instead" in str(m[0].message) - def test_util_in_top_level(self): - # in a subprocess to avoid import caching issues - out = subprocess.check_output( - [ - sys.executable, - "-c", - "import pandas; pandas.util.testing.assert_series_equal", - ], - stderr=subprocess.STDOUT, - ).decode() - assert "pandas.util.testing is deprecated" in out - with pytest.raises(AttributeError, match="foo"): pd.util.foo diff --git a/pandas/util/__init__.py b/pandas/util/__init__.py index 6e6006dd28165..aa31c024fe338 100644 --- a/pandas/util/__init__.py +++ b/pandas/util/__init__.py @@ -9,12 +9,3 @@ hash_array, hash_pandas_object, ) - - -def __getattr__(name): - if name == "testing": - import pandas.util.testing - - return pandas.util.testing - else: - raise AttributeError(f"module 'pandas.util' has no attribute '{name}'") diff --git a/pandas/util/testing.py b/pandas/util/testing.py deleted file mode 100644 index db9bfc274cd78..0000000000000 --- a/pandas/util/testing.py +++ /dev/null @@ -1,14 +0,0 @@ -import warnings - -from pandas.util._exceptions import find_stack_level - -from pandas._testing import * # noqa:F401,F403,PDF014 - -warnings.warn( - ( - "pandas.util.testing is deprecated. Use the functions in the " - "public API at pandas.testing instead." - ), - FutureWarning, - stacklevel=find_stack_level(), -)
https://github.com/pandas-dev/pandas/pull/30745
https://api.github.com/repos/pandas-dev/pandas/pulls/49293
2022-10-24T23:42:44Z
2022-10-25T14:08:19Z
2022-10-25T14:08:19Z
2022-10-25T16:58:58Z
API: Series.astype(td64_unsupported) raise
diff --git a/doc/source/user_guide/timedeltas.rst b/doc/source/user_guide/timedeltas.rst index 180de1df53f9e..318ca045847f4 100644 --- a/doc/source/user_guide/timedeltas.rst +++ b/doc/source/user_guide/timedeltas.rst @@ -236,9 +236,7 @@ Numeric reduction operation for ``timedelta64[ns]`` will return ``Timedelta`` ob Frequency conversion -------------------- -Timedelta Series, ``TimedeltaIndex``, and ``Timedelta`` scalars can be converted to other 'frequencies' by dividing by another timedelta, -or by astyping to a specific timedelta type. These operations yield Series and propagate ``NaT`` -> ``nan``. -Note that division by the NumPy scalar is true division, while astyping is equivalent of floor division. +Timedelta Series and ``TimedeltaIndex``, and ``Timedelta`` can be converted to other frequencies by astyping to a specific timedelta dtype. .. ipython:: python @@ -250,14 +248,17 @@ Note that division by the NumPy scalar is true division, while astyping is equiv td[3] = np.nan td - # to days - td / np.timedelta64(1, "D") - td.astype("timedelta64[D]") - # to seconds - td / np.timedelta64(1, "s") td.astype("timedelta64[s]") +For timedelta64 resolutions other than the supported "s", "ms", "us", "ns", +an alternative is to divide by another timedelta object. Note that division by the NumPy scalar is true division, while astyping is equivalent of floor division. + +.. ipython:: python + + # to days + td / np.timedelta64(1, "D") + # to months (these are constant months) td / np.timedelta64(1, "M") diff --git a/doc/source/whatsnew/v0.13.0.rst b/doc/source/whatsnew/v0.13.0.rst index 8265ad58f7ea3..f5d3fc572ca98 100644 --- a/doc/source/whatsnew/v0.13.0.rst +++ b/doc/source/whatsnew/v0.13.0.rst @@ -532,6 +532,7 @@ Enhancements is frequency conversion. See :ref:`the docs<timedeltas.timedeltas_convert>` for the docs. .. ipython:: python + :okexcept: import datetime td = pd.Series(pd.date_range('20130101', periods=4)) - pd.Series( diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index ff26df96d1a89..37af627f30748 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -99,6 +99,91 @@ notable_bug_fix2 Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _whatsnew_200.api_breaking.astype_to_unsupported_datetimelike: + +Disallow astype conversion to non-supported datetime64/timedelta64 dtypes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +In previous versions, converting a :class:`Series` or :class:`DataFrame` +from ``datetime64[ns]`` to a different ``datetime64[X]`` dtype would return +with ``datetime64[ns]`` dtype instead of the requested dtype. In pandas 2.0, +support is added for "datetime64[s]", "datetime64[ms]", and "datetime64[us]" dtypes, +so converting to those dtypes gives exactly the requested dtype: + +*Previous behavior*: + +.. ipython:: python + + idx = pd.date_range("2016-01-01", periods=3) + ser = pd.Series(idx) + +*Previous behavior*: + +.. code-block:: ipython + + In [4]: ser.astype("datetime64[s]") + Out[4]: + 0 2016-01-01 + 1 2016-01-02 + 2 2016-01-03 + dtype: datetime64[ns] + +With the new behavior, we get exactly the requested dtype: + +*New behavior*: + +.. ipython:: python + + ser.astype("datetime64[s]") + +For non-supported resolutions e.g. "datetime64[D]", we raise instead of silently +ignoring the requested dtype: + +*New behavior*: + +.. ipython:: python + :okexcept: + + ser.astype("datetime64[D]") + +For conversion from ``timedelta64[ns]`` dtypes, the old behavior converted +to a floating point format. + +*Previous behavior*: + +.. ipython:: python + + idx = pd.timedelta_range("1 Day", periods=3) + ser = pd.Series(idx) + +*Previous behavior*: + +.. code-block:: ipython + + In [7]: ser.astype("timedelta64[s]") + Out[7]: + 0 86400.0 + 1 172800.0 + 2 259200.0 + dtype: float64 + + In [8]: ser.astype("timedelta64[D]") + Out[8]: + 0 1.0 + 1 2.0 + 2 3.0 + dtype: float64 + +The new behavior, as for datetime64, either gives exactly the requested dtype or raises: + +*New behavior*: + +.. ipython:: python + :okexcept: + + ser.astype("timedelta64[s]") + ser.astype("timedelta64[D]") + .. _whatsnew_200.api_breaking.deps: Increased minimum versions for dependencies diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 92b9222cfc9bc..32c90de6f1ce9 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -45,7 +45,6 @@ from pandas.compat.numpy import function as nv from pandas.util._validators import validate_endpoints -from pandas.core.dtypes.astype import astype_td64_unit_conversion from pandas.core.dtypes.common import ( TD64NS_DTYPE, is_dtype_equal, @@ -327,8 +326,11 @@ def astype(self, dtype, copy: bool = True): return type(self)._simple_new( res_values, dtype=res_values.dtype, freq=self.freq ) - - return astype_td64_unit_conversion(self._ndarray, dtype, copy=copy) + else: + raise ValueError( + f"Cannot convert from {self.dtype} to {dtype}. " + "Supported resolutions are 's', 'ms', 'us', 'ns'" + ) return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy=copy) diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index 718badc2e4085..d95b71a5ea890 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -13,11 +13,6 @@ import numpy as np from pandas._libs import lib -from pandas._libs.tslibs import ( - get_unit_from_dtype, - is_supported_unit, - is_unitless, -) from pandas._libs.tslibs.timedeltas import array_to_timedelta64 from pandas._typing import ( ArrayLike, @@ -132,12 +127,10 @@ def astype_nansafe( # TODO(2.0): change to use the same logic as TDA.astype, i.e. # giving the requested dtype for supported units (s, ms, us, ns) # and doing the old convert-to-float behavior otherwise. - if is_supported_unit(get_unit_from_dtype(arr.dtype)): - from pandas.core.construction import ensure_wrapped_if_datetimelike + from pandas.core.construction import ensure_wrapped_if_datetimelike - arr = ensure_wrapped_if_datetimelike(arr) - return arr.astype(dtype, copy=copy) - return astype_td64_unit_conversion(arr, dtype, copy=copy) + arr = ensure_wrapped_if_datetimelike(arr) + return arr.astype(dtype, copy=copy) raise TypeError(f"cannot astype a timedelta from [{arr.dtype}] to [{dtype}]") @@ -292,20 +285,6 @@ def astype_array_safe( # Ensure we don't end up with a PandasArray dtype = dtype.numpy_dtype - if ( - is_datetime64_dtype(values.dtype) - # need to do np.dtype check instead of is_datetime64_dtype - # otherwise pyright complains - and isinstance(dtype, np.dtype) - and dtype.kind == "M" - and not is_unitless(dtype) - and not is_dtype_equal(dtype, values.dtype) - and not is_supported_unit(get_unit_from_dtype(dtype)) - ): - # Supported units we handle in DatetimeArray.astype; but that raises - # on non-supported units, so we handle that here. - return np.asarray(values).astype(dtype) - try: new_values = astype_array(values, dtype, copy=copy) except (ValueError, TypeError): @@ -317,36 +296,3 @@ def astype_array_safe( raise return new_values - - -def astype_td64_unit_conversion( - values: np.ndarray, dtype: np.dtype, copy: bool -) -> np.ndarray: - """ - By pandas convention, converting to non-nano timedelta64 - returns an int64-dtyped array with ints representing multiples - of the desired timedelta unit. This is essentially division. - - Parameters - ---------- - values : np.ndarray[timedelta64[ns]] - dtype : np.dtype - timedelta64 with unit not-necessarily nano - copy : bool - - Returns - ------- - np.ndarray - """ - if is_dtype_equal(values.dtype, dtype): - if copy: - return values.copy() - return values - - # otherwise we are converting to non-nano - result = values.astype(dtype, copy=False) # avoid double-copying - result = result.astype(np.float64) - - mask = isna(values) - np.putmask(result, mask, np.nan) - return result diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 56c97ac7a4dc5..6955b2e7b6aca 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -1861,8 +1861,8 @@ def test_is_timedelta(self): assert is_timedelta64_ns_dtype(tdi.astype("timedelta64[ns]")) # Conversion to Int64Index: - assert not is_timedelta64_ns_dtype(tdi.astype("timedelta64")) - assert not is_timedelta64_ns_dtype(tdi.astype("timedelta64[h]")) + assert not is_timedelta64_ns_dtype(Index([], dtype=np.float64)) + assert not is_timedelta64_ns_dtype(Index([], dtype=np.int64)) class TestIsScalar: diff --git a/pandas/tests/frame/constructors/test_from_records.py b/pandas/tests/frame/constructors/test_from_records.py index b2efa0713b513..7c4ed68dfd0ef 100644 --- a/pandas/tests/frame/constructors/test_from_records.py +++ b/pandas/tests/frame/constructors/test_from_records.py @@ -44,7 +44,8 @@ def test_from_records_with_datetimes(self): dtypes = [("EXPIRY", "<M8[m]")] recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) result = DataFrame.from_records(recarray) - expected["EXPIRY"] = expected["EXPIRY"].astype("M8[m]") + # we get the closest supported unit, "s" + expected["EXPIRY"] = expected["EXPIRY"].astype("M8[s]") tm.assert_frame_equal(result, expected) def test_from_records_sequencelike(self): diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index 69087b6822f2e..12f7606cc410b 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -418,14 +418,28 @@ def test_astype_to_datetime_unit(self, unit): idx = pd.Index(ser) dta = ser._values - result = df.astype(dtype) - if unit in ["ns", "us", "ms", "s"]: # GH#48928 exp_dtype = dtype + result = df.astype(dtype) else: # we use the nearest supported dtype (i.e. M8[s]) exp_dtype = "M8[s]" + msg = rf"Cannot cast DatetimeArray to dtype datetime64\[{unit}\]" + with pytest.raises(TypeError, match=msg): + df.astype(dtype) + + with pytest.raises(TypeError, match=msg): + ser.astype(dtype) + + with pytest.raises(TypeError, match=msg.replace("Array", "Index")): + idx.astype(dtype) + + with pytest.raises(TypeError, match=msg): + dta.astype(dtype) + + return + # TODO(2.0): once DataFrame constructor doesn't cast ndarray inputs. # can simplify this exp_values = arr.astype(exp_dtype) @@ -437,32 +451,22 @@ def test_astype_to_datetime_unit(self, unit): tm.assert_frame_equal(result, exp_df) - # TODO(2.0): make Series/DataFrame raise like Index and DTA? res_ser = ser.astype(dtype) exp_ser = exp_df.iloc[:, 0] assert exp_ser.dtype == exp_dtype tm.assert_series_equal(res_ser, exp_ser) - if unit in ["ns", "us", "ms", "s"]: - exp_dta = exp_ser._values + exp_dta = exp_ser._values - res_index = idx.astype(dtype) - # TODO(2.0): should be able to just call pd.Index(exp_ser) - exp_index = pd.DatetimeIndex._simple_new(exp_dta, name=idx.name) - assert exp_index.dtype == exp_dtype - tm.assert_index_equal(res_index, exp_index) + res_index = idx.astype(dtype) + # TODO(2.0): should be able to just call pd.Index(exp_ser) + exp_index = pd.DatetimeIndex._simple_new(exp_dta, name=idx.name) + assert exp_index.dtype == exp_dtype + tm.assert_index_equal(res_index, exp_index) - res_dta = dta.astype(dtype) - assert exp_dta.dtype == exp_dtype - tm.assert_extension_array_equal(res_dta, exp_dta) - else: - msg = rf"Cannot cast DatetimeIndex to dtype datetime64\[{unit}\]" - with pytest.raises(TypeError, match=msg): - idx.astype(dtype) - - msg = rf"Cannot cast DatetimeArray to dtype datetime64\[{unit}\]" - with pytest.raises(TypeError, match=msg): - dta.astype(dtype) + res_dta = dta.astype(dtype) + assert exp_dta.dtype == exp_dtype + tm.assert_extension_array_equal(res_dta, exp_dta) @pytest.mark.parametrize("unit", ["ns"]) def test_astype_to_timedelta_unit_ns(self, unit): @@ -483,22 +487,35 @@ def test_astype_to_timedelta_unit(self, unit): dtype = f"m8[{unit}]" arr = np.array([[1, 2, 3]], dtype=dtype) df = DataFrame(arr) + ser = df.iloc[:, 0] + tdi = pd.Index(ser) + tda = tdi._values + if unit in ["us", "ms", "s"]: assert (df.dtypes == dtype).all() + result = df.astype(dtype) else: # We get the nearest supported unit, i.e. "s" assert (df.dtypes == "m8[s]").all() - result = df.astype(dtype) - if unit in ["m", "h", "D"]: - # We don't support these, so we use the pre-2.0 logic to convert to float - # (xref GH#48979) - - expected = DataFrame(df.values.astype(dtype).astype(float)) - else: - # The conversion is a no-op, so we just get a copy - expected = df + msg = ( + rf"Cannot convert from timedelta64\[s\] to timedelta64\[{unit}\]. " + "Supported resolutions are 's', 'ms', 'us', 'ns'" + ) + with pytest.raises(ValueError, match=msg): + df.astype(dtype) + with pytest.raises(ValueError, match=msg): + ser.astype(dtype) + with pytest.raises(ValueError, match=msg): + tdi.astype(dtype) + with pytest.raises(ValueError, match=msg): + tda.astype(dtype) + + return + result = df.astype(dtype) + # The conversion is a no-op, so we just get a copy + expected = df tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"]) diff --git a/pandas/tests/indexes/timedeltas/methods/test_astype.py b/pandas/tests/indexes/timedeltas/methods/test_astype.py index aa2f7b7af8d98..6302f8784e29b 100644 --- a/pandas/tests/indexes/timedeltas/methods/test_astype.py +++ b/pandas/tests/indexes/timedeltas/methods/test_astype.py @@ -13,7 +13,6 @@ ) import pandas._testing as tm from pandas.core.api import ( - Float64Index, Int64Index, UInt64Index, ) @@ -89,9 +88,12 @@ def test_astype_timedelta64(self): # GH 13149, GH 13209 idx = TimedeltaIndex([1e14, "NaT", NaT, np.NaN]) - result = idx.astype("timedelta64") - expected = Float64Index([1e14] + [np.NaN] * 3, dtype="float64") - tm.assert_index_equal(result, expected) + msg = ( + r"Cannot convert from timedelta64\[ns\] to timedelta64. " + "Supported resolutions are 's', 'ms', 'us', 'ns'" + ) + with pytest.raises(ValueError, match=msg): + idx.astype("timedelta64") result = idx.astype("timedelta64[ns]") tm.assert_index_equal(result, idx) diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 701d737535116..01efbfb9ae0c0 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -141,9 +141,12 @@ def test_freq_conversion(self, index_or_series): # We don't support "D" reso, so we use the pre-2.0 behavior # casting to float64 - result = td.astype("timedelta64[D]") - expected = index_or_series([31, 31, 31, np.nan]) - tm.assert_equal(result, expected) + msg = ( + r"Cannot convert from timedelta64\[ns\] to timedelta64\[D\]. " + "Supported resolutions are 's', 'ms', 'us', 'ns'" + ) + with pytest.raises(ValueError, match=msg): + td.astype("timedelta64[D]") result = td / np.timedelta64(1, "s") expected = index_or_series( diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 3490d05f13e9d..f27f61b71bef6 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -672,11 +672,11 @@ def test_loc_setitem_consistency_slice_column_len(self): ) with tm.assert_produces_warning(None, match=msg): - # timedelta64[m] -> float64, so this cannot be done inplace, so + # timedelta64[m] -> float, so this cannot be done inplace, so # no warning df.loc[:, ("Respondent", "Duration")] = df.loc[ :, ("Respondent", "Duration") - ].astype("timedelta64[m]") + ] / Timedelta(60_000_000_000) expected = Series( [23.0, 12.0, 14.0, 36.0], index=df.index, name=("Respondent", "Duration")
- [x] closes #48979 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. .astype analogue to #49285. cc @jreback @mroeschke
https://api.github.com/repos/pandas-dev/pandas/pulls/49290
2022-10-24T22:59:37Z
2022-11-03T17:47:46Z
2022-11-03T17:47:46Z
2022-11-03T18:21:35Z
DEP: Disallow abbreviations for orient in to_dict
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 060de8ff8ef09..845812572d872 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -214,6 +214,7 @@ Removal of prior version deprecations/changes - Removed :meth:`Series.slice_shift` and :meth:`DataFrame.slice_shift` (:issue:`37601`) - Remove :meth:`DataFrameGroupBy.pad` and :meth:`DataFrameGroupBy.backfill` (:issue:`45076`) - Remove ``numpy`` argument from :func:`read_json` (:issue:`30636`) +- Disallow passing abbreviations for ``orient`` in :meth:`DataFrame.to_dict` (:issue:`32516`) - Removed the ``center`` keyword in :meth:`DataFrame.expanding` (:issue:`20647`) - Removed the ``truediv`` keyword from :func:`eval` (:issue:`29812`) - Removed the ``pandas.datetime`` submodule (:issue:`30489`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index cc2bca1bcece6..3b4b5a04fcf2b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1855,9 +1855,6 @@ def to_dict( [{column -> value}, ... , {column -> value}] - 'index' : dict like {index -> {column -> value}} - Abbreviations are allowed. `s` indicates `series` and `sp` - indicates `split`. - .. versionadded:: 1.4.0 'tight' as an allowed value for the ``orient`` argument @@ -1948,36 +1945,6 @@ def to_dict( # variable has type "Literal['dict', 'list', 'series', 'split', 'tight', # 'records', 'index']") orient = orient.lower() # type: ignore[assignment] - # GH32515 - if orient.startswith(("d", "l", "s", "r", "i")) and orient not in { - "dict", - "list", - "series", - "split", - "records", - "index", - }: - warnings.warn( - "Using short name for 'orient' is deprecated. Only the " - "options: ('dict', list, 'series', 'split', 'records', 'index') " - "will be used in a future version. Use one of the above " - "to silence this warning.", - FutureWarning, - stacklevel=find_stack_level(), - ) - - if orient.startswith("d"): - orient = "dict" - elif orient.startswith("l"): - orient = "list" - elif orient.startswith("sp"): - orient = "split" - elif orient.startswith("s"): - orient = "series" - elif orient.startswith("r"): - orient = "records" - elif orient.startswith("i"): - orient = "index" if not index and orient not in ["split", "tight"]: raise ValueError( diff --git a/pandas/tests/frame/methods/test_to_dict.py b/pandas/tests/frame/methods/test_to_dict.py index 613f7147a4a7d..521f6ead2e69e 100644 --- a/pandas/tests/frame/methods/test_to_dict.py +++ b/pandas/tests/frame/methods/test_to_dict.py @@ -80,11 +80,10 @@ def test_to_dict_invalid_orient(self): df.to_dict(orient="xinvalid") @pytest.mark.parametrize("orient", ["d", "l", "r", "sp", "s", "i"]) - def test_to_dict_short_orient_warns(self, orient): + def test_to_dict_short_orient_raises(self, orient): # GH#32515 df = DataFrame({"A": [0, 1]}) - msg = "Using short name for 'orient' is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): + with pytest.raises(ValueError, match="not understood"): df.to_dict(orient=orient) @pytest.mark.parametrize("mapping", [dict, defaultdict(list), OrderedDict])
#32516
https://api.github.com/repos/pandas-dev/pandas/pulls/49289
2022-10-24T22:06:24Z
2022-10-25T18:35:03Z
2022-10-25T18:35:03Z
2022-10-31T09:47:30Z
DEP: Enforce fname to path renaming
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 8a628dbce3ca7..0f8afe14a2369 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -229,6 +229,7 @@ Removal of prior version deprecations/changes - Enforced disallowing a string column label into ``times`` in :meth:`DataFrame.ewm` (:issue:`43265`) - Removed setting Categorical._codes directly (:issue:`41429`) - Enforced :meth:`Rolling.count` with ``min_periods=None`` to default to the size of the window (:issue:`31302`) +- Renamed ``fname`` to ``path`` in :meth:`DataFrame.to_parquet`, :meth:`DataFrame.to_stata` and :meth:`DataFrame.to_feather` (:issue:`30338`) - Enforced the ``display.max_colwidth`` option to not accept negative integers (:issue:`31569`) - Removed the ``display.column_space`` option in favor of ``df.to_string(col_space=...)`` (:issue:`47280`) - Removed the deprecated method ``mad`` from pandas classes (:issue:`11787`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 3b4b5a04fcf2b..d741ca21d8ca7 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2550,7 +2550,6 @@ def _from_arrays( storage_options=_shared_docs["storage_options"], compression_options=_shared_docs["compression_options"] % "path", ) - @deprecate_kwarg(old_arg_name="fname", new_arg_name="path") def to_stata( self, path: FilePath | WriteBuffer[bytes], @@ -2710,7 +2709,6 @@ def to_stata( ) writer.write_file() - @deprecate_kwarg(old_arg_name="fname", new_arg_name="path") def to_feather(self, path: FilePath | WriteBuffer[bytes], **kwargs) -> None: """ Write a DataFrame to the binary Feather format. @@ -2820,7 +2818,6 @@ def to_parquet( ... @doc(storage_options=_shared_docs["storage_options"]) - @deprecate_kwarg(old_arg_name="fname", new_arg_name="path") def to_parquet( self, path: FilePath | WriteBuffer[bytes] | None = None,
#30338
https://api.github.com/repos/pandas-dev/pandas/pulls/49288
2022-10-24T22:00:21Z
2022-10-25T21:07:43Z
2022-10-25T21:07:43Z
2022-10-25T21:57:55Z
CI: Catch FutureWarnings
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 744d06d6cf339..963ed24cb434b 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -168,7 +168,15 @@ class TestDataFrameAnalytics: ], ) def test_stat_op_api_float_string_frame(self, float_string_frame, axis, opname): - getattr(float_string_frame, opname)(axis=axis) + if opname in ["sum", "min", "max"] and axis == 0: + warn = None + elif opname not in ["count", "nunique"]: + warn = FutureWarning + else: + warn = None + msg = "nuisance columns|default value of numeric_only" + with tm.assert_produces_warning(warn, match=msg): + getattr(float_string_frame, opname)(axis=axis) if opname != "nunique": getattr(float_string_frame, opname)(axis=axis, numeric_only=True)
The warnings show up since a couple of days ago
https://api.github.com/repos/pandas-dev/pandas/pulls/49287
2022-10-24T21:53:50Z
2022-10-26T09:40:18Z
2022-10-26T09:40:18Z
2022-10-31T09:47:51Z
TST: update exception messages for lxml tests
diff --git a/pandas/tests/io/xml/test_to_xml.py b/pandas/tests/io/xml/test_to_xml.py index d3247eb9dd47e..0f42c7e070c4a 100644 --- a/pandas/tests/io/xml/test_to_xml.py +++ b/pandas/tests/io/xml/test_to_xml.py @@ -1037,9 +1037,16 @@ def test_stylesheet_wrong_path(): def test_empty_string_stylesheet(val): from lxml.etree import XMLSyntaxError - with pytest.raises( - XMLSyntaxError, match=("Document is empty|Start tag expected, '<' not found") - ): + msg = "|".join( + [ + "Document is empty", + "Start tag expected, '<' not found", + # Seen on Mac with lxml 4.9.1 + r"None \(line 0\)", + ] + ) + + with pytest.raises(XMLSyntaxError, match=msg): geom_df.to_xml(stylesheet=val) diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py index 935a44d0e0901..baebc562fc5ff 100644 --- a/pandas/tests/io/xml/test_xml.py +++ b/pandas/tests/io/xml/test_xml.py @@ -471,7 +471,14 @@ def test_file_handle_close(datapath, parser): def test_empty_string_lxml(val): from lxml.etree import XMLSyntaxError - with pytest.raises(XMLSyntaxError, match="Document is empty"): + msg = "|".join( + [ + "Document is empty", + # Seen on Mac with lxml 4.91 + r"None \(line 0\)", + ] + ) + with pytest.raises(XMLSyntaxError, match=msg): read_xml(val, parser="lxml")
These have been failing locally since I upgraded lxml.
https://api.github.com/repos/pandas-dev/pandas/pulls/49286
2022-10-24T21:52:04Z
2022-10-25T14:06:38Z
2022-10-25T14:06:38Z
2022-10-25T15:01:49Z
API: raise on unsupported dtype instead of silently swapping
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 1c170f3d6caee..1b7b917625c0f 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -113,6 +113,48 @@ notable_bug_fix2 Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. _whatsnew_200.api_breaking.unsupported_datetimelike_dtype_arg: + +Construction with datetime64 or timedelta64 dtype with unsupported resolution +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +In past versions, when constructing a :class:`Series` or :class:`DataFrame` and +passing a "datetime64" or "timedelta64" dtype with unsupported resolution +(i.e. anything other than "ns"), pandas would silently replace the given dtype +with its nanosecond analogue: + +*Previous behavior*: + +.. code-block:: ipython + + In [5]: pd.Series(["2016-01-01"], dtype="datetime64[s]") + Out[5]: + 0 2016-01-01 + dtype: datetime64[ns] + + In [6] pd.Series(["2016-01-01"], dtype="datetime64[D]") + Out[6]: + 0 2016-01-01 + dtype: datetime64[ns] + +In pandas 2.0 we support resolutions "s", "ms", "us", and "ns". When passing +a supported dtype (e.g. "datetime64[s]"), the result now has exactly +the requested dtype: + +*New behavior*: + +.. ipython:: python + + pd.Series(["2016-01-01"], dtype="datetime64[s]") + +With an un-supported dtype, pandas now raises instead of silently swapping in +a supported dtype: + +*New behavior*: + +.. ipython:: python + :okexcept: + + pd.Series(["2016-01-01"], dtype="datetime64[D]") .. _whatsnew_200.api_breaking.astype_to_unsupported_datetimelike: diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 1c7effa93f4ef..c470170724a2c 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -29,10 +29,8 @@ Timedelta, Timestamp, astype_overflowsafe, - get_supported_reso, get_unit_from_dtype, is_supported_unit, - npy_unit_to_abbrev, ) from pandas._libs.tslibs.timedeltas import array_to_timedelta64 from pandas._typing import ( @@ -1336,17 +1334,19 @@ def _ensure_nanosecond_dtype(dtype: DtypeObj) -> DtypeObj: """ Convert dtypes with granularity less than nanosecond to nanosecond - >>> _ensure_nanosecond_dtype(np.dtype("M8[D]")) - dtype('<M8[s]') - >>> _ensure_nanosecond_dtype(np.dtype("M8[us]")) dtype('<M8[us]') + >>> _ensure_nanosecond_dtype(np.dtype("M8[D]")) + Traceback (most recent call last): + ... + TypeError: dtype=datetime64[D] is not supported. Supported resolutions are 's', 'ms', 'us', and 'ns' + >>> _ensure_nanosecond_dtype(np.dtype("m8[ps]")) Traceback (most recent call last): ... - TypeError: cannot convert timedeltalike to dtype [timedelta64[ps]] - """ + TypeError: dtype=timedelta64[ps] is not supported. Supported resolutions are 's', 'ms', 'us', and 'ns' + """ # noqa:E501 msg = ( f"The '{dtype.name}' dtype has no unit. " f"Please pass in '{dtype.name}[ns]' instead." @@ -1359,29 +1359,19 @@ def _ensure_nanosecond_dtype(dtype: DtypeObj) -> DtypeObj: # i.e. datetime64tz pass - elif dtype.kind == "M" and not is_supported_unit(get_unit_from_dtype(dtype)): - # pandas supports dtype whose granularity is less than [ns] - # e.g., [ps], [fs], [as] - if dtype <= np.dtype("M8[ns]"): - if dtype.name == "datetime64": + elif dtype.kind in ["m", "M"]: + reso = get_unit_from_dtype(dtype) + if not is_supported_unit(reso): + # pre-2.0 we would silently swap in nanos for lower-resolutions, + # raise for above-nano resolutions + if dtype.name in ["datetime64", "timedelta64"]: raise ValueError(msg) - reso = get_supported_reso(get_unit_from_dtype(dtype)) - unit = npy_unit_to_abbrev(reso) - dtype = np.dtype(f"M8[{unit}]") - else: - raise TypeError(f"cannot convert datetimelike to dtype [{dtype}]") - - elif dtype.kind == "m" and dtype != TD64NS_DTYPE: - # pandas supports dtype whose granularity is less than [ns] - # e.g., [ps], [fs], [as] - if dtype <= np.dtype("m8[ns]"): - if dtype.name == "timedelta64": - raise ValueError(msg) - reso = get_supported_reso(get_unit_from_dtype(dtype)) - unit = npy_unit_to_abbrev(reso) - dtype = np.dtype(f"m8[{unit}]") - else: - raise TypeError(f"cannot convert timedeltalike to dtype [{dtype}]") + # TODO: ValueError or TypeError? existing test + # test_constructor_generic_timestamp_bad_frequency expects TypeError + raise TypeError( + f"dtype={dtype} is not supported. Supported resolutions are 's', " + "'ms', 'us', and 'ns'" + ) return dtype diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index abb0ca5407505..1209d92ffa14a 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1665,19 +1665,23 @@ def test_constructor_generic_timestamp_no_frequency(self, dtype, request): with pytest.raises(ValueError, match=msg): Series([], dtype=dtype) - @pytest.mark.parametrize( - "dtype,msg", - [ - ("m8[ps]", "cannot convert timedeltalike"), - ("M8[ps]", "cannot convert datetimelike"), - ], - ) - def test_constructor_generic_timestamp_bad_frequency(self, dtype, msg): + @pytest.mark.parametrize("unit", ["ps", "as", "fs", "Y", "M", "W", "D", "h", "m"]) + @pytest.mark.parametrize("kind", ["m", "M"]) + def test_constructor_generic_timestamp_bad_frequency(self, kind, unit): # see gh-15524, gh-15987 + # as of 2.0 we raise on any non-supported unit rather than silently + # cast to nanos; previously we only raised for frequencies higher + # than ns + dtype = f"{kind}8[{unit}]" + msg = "dtype=.* is not supported. Supported resolutions are" with pytest.raises(TypeError, match=msg): Series([], dtype=dtype) + with pytest.raises(TypeError, match=msg): + # pre-2.0 the DataFrame cast raised but the Series case did not + DataFrame([[0]], dtype=dtype) + @pytest.mark.parametrize("dtype", [None, "uint8", "category"]) def test_constructor_range_dtype(self, dtype): # GH 16804
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Looks like ATM the DataFrame case raises bc it goes through a different path, while the Series case does not. mentioned in (but this does not close) #48979
https://api.github.com/repos/pandas-dev/pandas/pulls/49285
2022-10-24T21:07:05Z
2022-11-08T20:04:23Z
2022-11-08T20:04:23Z
2022-11-08T20:35:16Z
REGR: MultiIndex.join does not work for ea dtypes
diff --git a/doc/source/whatsnew/v1.5.2.rst b/doc/source/whatsnew/v1.5.2.rst index e65be3bcecd76..572d6c74e767f 100644 --- a/doc/source/whatsnew/v1.5.2.rst +++ b/doc/source/whatsnew/v1.5.2.rst @@ -13,6 +13,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ +- Fixed regression in :meth:`MultiIndex.join` for extension array dtypes (:issue:`49277`) - Fixed regression in :meth:`Series.replace` raising ``RecursionError`` with numeric dtype and when specifying ``value=None`` (:issue:`45725`) - Fixed regression in :meth:`DataFrame.plot` preventing :class:`~matplotlib.colors.Colormap` instance from being passed using the ``colormap`` argument if Matplotlib 3.6+ is used (:issue:`49374`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 540ea2d113f9e..27672c82fdf15 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4456,8 +4456,10 @@ def join( return self._join_non_unique(other, how=how) elif not self.is_unique or not other.is_unique: if self.is_monotonic_increasing and other.is_monotonic_increasing: - if self._can_use_libjoin: + if not is_interval_dtype(self.dtype): # otherwise we will fall through to _join_via_get_indexer + # GH#39133 + # go through object dtype for ea till engine is supported properly return self._join_monotonic(other, how=how) else: return self._join_non_unique(other, how=how) @@ -4832,7 +4834,7 @@ def _wrap_joined_index(self: _IndexT, joined: ArrayLike, other: _IndexT) -> _Ind return self._constructor(joined, name=name) # type: ignore[return-value] else: name = get_op_result_name(self, other) - return self._constructor._with_infer(joined, name=name) + return self._constructor._with_infer(joined, name=name, dtype=self.dtype) @cache_readonly def _can_use_libjoin(self) -> bool: diff --git a/pandas/tests/indexes/multi/test_join.py b/pandas/tests/indexes/multi/test_join.py index 23d5325dde2bb..aa2f2ca5af7bd 100644 --- a/pandas/tests/indexes/multi/test_join.py +++ b/pandas/tests/indexes/multi/test_join.py @@ -6,6 +6,8 @@ Index, Interval, MultiIndex, + Series, + StringDtype, ) import pandas._testing as tm @@ -161,6 +163,52 @@ def test_join_overlapping_interval_level(): tm.assert_index_equal(result, expected) +def test_join_midx_ea(): + # GH#49277 + midx = MultiIndex.from_arrays( + [Series([1, 1, 3], dtype="Int64"), Series([1, 2, 3], dtype="Int64")], + names=["a", "b"], + ) + midx2 = MultiIndex.from_arrays( + [Series([1], dtype="Int64"), Series([3], dtype="Int64")], names=["a", "c"] + ) + result = midx.join(midx2, how="inner") + expected = MultiIndex.from_arrays( + [ + Series([1, 1], dtype="Int64"), + Series([1, 2], dtype="Int64"), + Series([3, 3], dtype="Int64"), + ], + names=["a", "b", "c"], + ) + tm.assert_index_equal(result, expected) + + +def test_join_midx_string(): + # GH#49277 + midx = MultiIndex.from_arrays( + [ + Series(["a", "a", "c"], dtype=StringDtype()), + Series(["a", "b", "c"], dtype=StringDtype()), + ], + names=["a", "b"], + ) + midx2 = MultiIndex.from_arrays( + [Series(["a"], dtype=StringDtype()), Series(["c"], dtype=StringDtype())], + names=["a", "c"], + ) + result = midx.join(midx2, how="inner") + expected = MultiIndex.from_arrays( + [ + Series(["a", "a"], dtype=StringDtype()), + Series(["a", "b"], dtype=StringDtype()), + Series(["c", "c"], dtype=StringDtype()), + ], + names=["a", "b", "c"], + ) + tm.assert_index_equal(result, expected) + + def test_join_multi_with_nan(): # GH29252 df1 = DataFrame(
- [x] closes #49277 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This can not fall through for regular ea dtypes, rather go through object path
https://api.github.com/repos/pandas-dev/pandas/pulls/49284
2022-10-24T20:27:06Z
2022-11-10T20:33:22Z
2022-11-10T20:33:22Z
2022-11-10T20:39:52Z
DOC: Fix doc timeout
diff --git a/doc/source/whatsnew/v0.12.0.rst b/doc/source/whatsnew/v0.12.0.rst index 6a8008b1e7c82..091efe1b421c7 100644 --- a/doc/source/whatsnew/v0.12.0.rst +++ b/doc/source/whatsnew/v0.12.0.rst @@ -433,17 +433,46 @@ Bug fixes a ``Series`` with either a single character at each index of the original ``Series`` or ``NaN``. For example, - .. ipython:: python - :okexcept: - - strs = "go", "bow", "joe", "slow" - ds = pd.Series(strs) - - for s in ds.str: - print(s) + .. code-block:: ipython - s - s.dropna().values.item() == "w" + In [38]: strs = "go", "bow", "joe", "slow" + + In [32]: ds = pd.Series(strs) + + In [33]: for s in ds.str: + ...: print(s) + + 0 g + 1 b + 2 j + 3 s + dtype: object + 0 o + 1 o + 2 o + 3 l + dtype: object + 0 NaN + 1 w + 2 e + 3 o + dtype: object + 0 NaN + 1 NaN + 2 NaN + 3 w + dtype: object + + In [41]: s + Out[41]: + 0 NaN + 1 NaN + 2 NaN + 3 w + dtype: object + + In [42]: s.dropna().values.item() == "w" + Out[42]: True The last element yielded by the iterator will be a ``Series`` containing the last element of the longest string in the ``Series`` with all other
cc @mroeschke The iter deprecation caused a doc timeout, sorry for not commenting earlier
https://api.github.com/repos/pandas-dev/pandas/pulls/49283
2022-10-24T20:02:20Z
2022-10-24T21:29:56Z
2022-10-24T21:29:56Z
2022-10-24T21:37:01Z
DEPR: tz arg in Period.to_timestamp
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 9d654439273a6..e9ce0c64c2370 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -181,6 +181,7 @@ Removal of prior version deprecations/changes - Removed :meth:`MultiIndex.is_lexsorted` and :meth:`MultiIndex.lexsort_depth` (:issue:`38701`) - Removed argument ``how`` from :meth:`PeriodIndex.astype`, use :meth:`PeriodIndex.to_timestamp` instead (:issue:`37982`) - Removed argument ``try_cast`` from :meth:`DataFrame.mask`, :meth:`DataFrame.where`, :meth:`Series.mask` and :meth:`Series.where` (:issue:`38836`) +- Removed argument ``tz`` from :meth:`Period.to_timestamp`, use ``obj.to_timestamp(...).tz_localize(tz)`` instead (:issue:`34522`) - Removed argument ``is_copy`` from :meth:`DataFrame.take` and :meth:`Series.take` (:issue:`30615`) - Disallow passing non-round floats to :class:`Timestamp` with ``unit="M"`` or ``unit="Y"`` (:issue:`47266`) - Remove keywords ``convert_float`` and ``mangle_dupe_cols`` from :func:`read_excel` (:issue:`41176`) diff --git a/pandas/_libs/tslibs/period.pyi b/pandas/_libs/tslibs/period.pyi index 5ad919649262c..946ae1215f1e3 100644 --- a/pandas/_libs/tslibs/period.pyi +++ b/pandas/_libs/tslibs/period.pyi @@ -8,7 +8,6 @@ from pandas._libs.tslibs.offsets import BaseOffset from pandas._libs.tslibs.timestamps import Timestamp from pandas._typing import ( Frequency, - Timezone, npt, ) @@ -88,7 +87,6 @@ class Period(PeriodMixin): self, freq: str | BaseOffset | None = ..., how: str = ..., - tz: Timezone | None = ..., ) -> Timestamp: ... def asfreq(self, freq: str | BaseOffset, how: str = ...) -> Period: ... @property diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index a516565ff3f8d..be6f87791284e 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1,7 +1,3 @@ -import warnings - -from pandas.util._exceptions import find_stack_level - cimport numpy as cnp from cpython.object cimport ( Py_EQ, @@ -1802,7 +1798,7 @@ cdef class _Period(PeriodMixin): return Period(ordinal=ordinal, freq=freq) - def to_timestamp(self, freq=None, how='start', tz=None) -> Timestamp: + def to_timestamp(self, freq=None, how="start") -> Timestamp: """ Return the Timestamp representation of the Period. @@ -1822,16 +1818,6 @@ cdef class _Period(PeriodMixin): ------- Timestamp """ - if tz is not None: - # GH#34522 - warnings.warn( - "Period.to_timestamp `tz` argument is deprecated and will " - "be removed in a future version. Use " - "`per.to_timestamp(...).tz_localize(tz)` instead.", - FutureWarning, - stacklevel=find_stack_level(), - ) - how = validate_end_alias(how) end = how == 'E' @@ -1853,7 +1839,7 @@ cdef class _Period(PeriodMixin): val = self.asfreq(freq, how) dt64 = period_ordinal_to_dt64(val.ordinal, base) - return Timestamp(dt64, tz=tz) + return Timestamp(dt64) @property def year(self) -> int: diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index b8baaaeaeecf8..b5491c606ec7b 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -6,7 +6,6 @@ import numpy as np import pytest -import pytz from pandas._libs.tslibs import ( iNaT, @@ -22,10 +21,6 @@ INVALID_FREQ_ERR_MSG, IncompatibleFrequency, ) -from pandas._libs.tslibs.timezones import ( - dateutil_gettz, - maybe_get_tz, -) import pandas as pd from pandas import ( @@ -583,70 +578,6 @@ def test_hash(self): # -------------------------------------------------------------- # to_timestamp - @pytest.mark.parametrize("tzstr", ["Europe/Brussels", "Asia/Tokyo", "US/Pacific"]) - def test_to_timestamp_tz_arg(self, tzstr): - # GH#34522 tz kwarg deprecated - with tm.assert_produces_warning(FutureWarning): - p = Period("1/1/2005", freq="M").to_timestamp(tz=tzstr) - exp = Timestamp("1/1/2005", tz="UTC").tz_convert(tzstr) - exp_zone = pytz.timezone(tzstr).normalize(p) - - assert p == exp - assert p.tz == exp_zone.tzinfo - assert p.tz == exp.tz - - with tm.assert_produces_warning(FutureWarning): - p = Period("1/1/2005", freq="3H").to_timestamp(tz=tzstr) - exp = Timestamp("1/1/2005", tz="UTC").tz_convert(tzstr) - exp_zone = pytz.timezone(tzstr).normalize(p) - - assert p == exp - assert p.tz == exp_zone.tzinfo - assert p.tz == exp.tz - - with tm.assert_produces_warning(FutureWarning): - p = Period("1/1/2005", freq="A").to_timestamp(freq="A", tz=tzstr) - exp = Timestamp(day=31, month=12, year=2005, tz="UTC").tz_convert(tzstr) - exp_zone = pytz.timezone(tzstr).normalize(p) - - assert p == exp - assert p.tz == exp_zone.tzinfo - assert p.tz == exp.tz - - with tm.assert_produces_warning(FutureWarning): - p = Period("1/1/2005", freq="A").to_timestamp(freq="3H", tz=tzstr) - exp = Timestamp("1/1/2005", tz="UTC").tz_convert(tzstr) - exp_zone = pytz.timezone(tzstr).normalize(p) - - assert p == exp - assert p.tz == exp_zone.tzinfo - assert p.tz == exp.tz - - @pytest.mark.parametrize( - "tzstr", - ["dateutil/Europe/Brussels", "dateutil/Asia/Tokyo", "dateutil/US/Pacific"], - ) - def test_to_timestamp_tz_arg_dateutil(self, tzstr): - tz = maybe_get_tz(tzstr) - with tm.assert_produces_warning(FutureWarning): - p = Period("1/1/2005", freq="M").to_timestamp(tz=tz) - exp = Timestamp("1/1/2005", tz="UTC").tz_convert(tzstr) - assert p == exp - assert p.tz == dateutil_gettz(tzstr.split("/", 1)[1]) - assert p.tz == exp.tz - - with tm.assert_produces_warning(FutureWarning): - p = Period("1/1/2005", freq="M").to_timestamp(freq="3H", tz=tz) - exp = Timestamp("1/1/2005", tz="UTC").tz_convert(tzstr) - assert p == exp - assert p.tz == dateutil_gettz(tzstr.split("/", 1)[1]) - assert p.tz == exp.tz - - def test_to_timestamp_tz_arg_dateutil_from_string(self): - with tm.assert_produces_warning(FutureWarning): - p = Period("1/1/2005", freq="M").to_timestamp(tz="dateutil/Europe/Brussels") - assert p.tz == dateutil_gettz("Europe/Brussels") - def test_to_timestamp_mult(self): p = Period("2011-01", freq="M") assert p.to_timestamp(how="S") == Timestamp("2011-01-01")
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49280
2022-10-24T16:37:44Z
2022-10-24T20:29:04Z
2022-10-24T20:29:04Z
2022-10-24T20:32:05Z
DOC: Updates to documentation
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index cc2bca1bcece6..eef86ce7294a7 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -490,7 +490,9 @@ class DataFrame(NDFrame, OpsMixin): data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame Dict can contain Series, arrays, constants, dataclass or list-like objects. If data is a dict, column order follows insertion-order. If a dict contains Series - which have an index defined, it is aligned by its index. + which have an index defined, it is aligned by its index. This alignment also + occurs if data is a Series or a DataFrame itself. Alignment is done on + Series/DataFrame inputs. .. versionchanged:: 0.25.0 If data is a list of dicts, column order follows insertion-order. @@ -592,6 +594,22 @@ class DataFrame(NDFrame, OpsMixin): 0 0 0 1 0 3 2 2 3 + + Constructing DataFrame from Series/DataFrame: + + >>> ser = pd.Series([1, 2, 3], index=["a", "b", "c"]) + >>> df = pd.DataFrame(data=ser, index=["a", "c"]) + >>> df + 0 + a 1 + c 3 + + >>> df1 = pd.DataFrame([1, 2, 3], index=["a", "b", "c"], columns=["x"]) + >>> df2 = pd.DataFrame(data=df1, index=["a", "c"]) + >>> df2 + x + a 1 + c 3 """ _internal_names_set = {"columns", "index"} | NDFrame._internal_names_set
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added an entry in the latest `pandas/core/frame.py` file. - [ ] closes #48674 index constructor updates to the frame.py file to indicate index alignment.
https://api.github.com/repos/pandas-dev/pandas/pulls/49278
2022-10-24T14:45:19Z
2022-10-26T15:49:07Z
2022-10-26T15:49:07Z
2022-10-26T15:49:14Z
PERF: GH28635 Add ASV benchmark for resample after groupby
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index 97f48a3a6f69f..2225cbd74d718 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -14,6 +14,7 @@ Timestamp, date_range, period_range, + to_timedelta, ) from .pandas_vb_common import tm @@ -987,4 +988,31 @@ def time_sample_weights(self): self.df.groupby(self.groups).sample(n=1, weights=self.weights) +class Resample: + # GH 28635 + def setup(self): + num_timedeltas = 20_000 + num_groups = 3 + + index = MultiIndex.from_product( + [ + np.arange(num_groups), + to_timedelta(np.arange(num_timedeltas), unit="s"), + ], + names=["groups", "timedeltas"], + ) + data = np.random.randint(0, 1000, size=(len(index))) + + self.df = DataFrame(data, index=index).reset_index("timedeltas") + self.df_multiindex = DataFrame(data, index=index) + + def time_resample(self): + self.df.groupby(level="groups").resample("10s", on="timedeltas").mean() + + def time_resample_multiindex(self): + self.df_multiindex.groupby(level="groups").resample( + "10s", level="timedeltas" + ).mean() + + from .pandas_vb_common import setup # noqa: F401 isort:skip
- [x] closes #28635 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49274
2022-10-24T09:12:12Z
2022-10-24T15:41:07Z
2022-10-24T15:41:07Z
2022-10-25T08:19:18Z
DEPR: enforce deprecation of slice_shift
diff --git a/doc/redirects.csv b/doc/redirects.csv index 8a55c48996e84..d730356bd88cc 100644 --- a/doc/redirects.csv +++ b/doc/redirects.csv @@ -484,7 +484,6 @@ generated/pandas.DataFrame.shape,../reference/api/pandas.DataFrame.shape generated/pandas.DataFrame.shift,../reference/api/pandas.DataFrame.shift generated/pandas.DataFrame.size,../reference/api/pandas.DataFrame.size generated/pandas.DataFrame.skew,../reference/api/pandas.DataFrame.skew -generated/pandas.DataFrame.slice_shift,../reference/api/pandas.DataFrame.slice_shift generated/pandas.DataFrame.sort_index,../reference/api/pandas.DataFrame.sort_index generated/pandas.DataFrame.sort_values,../reference/api/pandas.DataFrame.sort_values generated/pandas.DataFrame.squeeze,../reference/api/pandas.DataFrame.squeeze @@ -1166,7 +1165,6 @@ generated/pandas.Series.shape,../reference/api/pandas.Series.shape generated/pandas.Series.shift,../reference/api/pandas.Series.shift generated/pandas.Series.size,../reference/api/pandas.Series.size generated/pandas.Series.skew,../reference/api/pandas.Series.skew -generated/pandas.Series.slice_shift,../reference/api/pandas.Series.slice_shift generated/pandas.Series.sort_index,../reference/api/pandas.Series.sort_index generated/pandas.Series.sort_values,../reference/api/pandas.Series.sort_values generated/pandas.Series.sparse.density,../reference/api/pandas.Series.sparse.density diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst index cc38f6cc42972..9bb3156224d39 100644 --- a/doc/source/reference/frame.rst +++ b/doc/source/reference/frame.rst @@ -266,7 +266,6 @@ Time Series-related DataFrame.asfreq DataFrame.asof DataFrame.shift - DataFrame.slice_shift DataFrame.first_valid_index DataFrame.last_valid_index DataFrame.resample diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst index 0beac55c8b86c..6753dd45ed0d6 100644 --- a/doc/source/reference/series.rst +++ b/doc/source/reference/series.rst @@ -268,7 +268,6 @@ Time Series-related Series.tz_localize Series.at_time Series.between_time - Series.slice_shift Accessors --------- diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 00e57d738ca6e..c7056290a0be2 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -192,6 +192,7 @@ Removal of prior version deprecations/changes - Removed the ``numeric_only`` keyword from :meth:`Categorical.min` and :meth:`Categorical.max` in favor of ``skipna`` (:issue:`48821`) - Removed :func:`is_extension_type` in favor of :func:`is_extension_array_dtype` (:issue:`29457`) - Removed :meth:`Index.get_value` and :meth:`Index.set_value` (:issue:`33907`, :issue:`28621`) +- Removed :meth:`Series.slice_shift` and :meth:`DataFrame.slice_shift` (:issue:`37601`) - Remove :meth:`DataFrameGroupBy.pad` and :meth:`DataFrameGroupBy.backfill` (:issue:`45076`) - Remove ``numpy`` argument from :func:`read_json` (:issue:`30636`) - Removed the ``center`` keyword in :meth:`DataFrame.expanding` (:issue:`20647`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f46b429a5fc75..2e1d5a286b386 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -10219,57 +10219,6 @@ def shift( result = self.set_axis(new_ax, axis=axis) return result.__finalize__(self, method="shift") - @final - def slice_shift(self: NDFrameT, periods: int = 1, axis: Axis = 0) -> NDFrameT: - """ - Equivalent to `shift` without copying data. - - .. deprecated:: 1.2.0 - slice_shift is deprecated, - use DataFrame/Series.shift instead. - - The shifted data will not include the dropped periods and the - shifted axis will be smaller than the original. - - Parameters - ---------- - periods : int - Number of periods to move, can be positive or negative. - axis : {0 or 'index', 1 or 'columns', None}, default 0 - For `Series` this parameter is unused and defaults to 0. - - Returns - ------- - shifted : same type as caller - - Notes - ----- - While the `slice_shift` is faster than `shift`, you may pay for it - later during alignment. - """ - - msg = ( - "The 'slice_shift' method is deprecated " - "and will be removed in a future version. " - "You can use DataFrame/Series.shift instead." - ) - warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) - - if periods == 0: - return self - - if periods > 0: - vslicer = slice(None, -periods) - islicer = slice(periods, None) - else: - vslicer = slice(-periods, None) - islicer = slice(None, periods) - - new_obj = self._slice(vslicer, axis=axis) - shifted_axis = self._get_axis(axis)[islicer] - new_obj = new_obj.set_axis(shifted_axis, axis=axis, copy=False) - return new_obj.__finalize__(self, method="slice_shift") - def truncate( self: NDFrameT, before=None, diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index a6c516b51c6c5..8ea3d1c9c2396 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -462,11 +462,3 @@ def test_flags_identity(self, frame_or_series): assert obj.flags is obj.flags obj2 = obj.copy() assert obj2.flags is not obj.flags - - def test_slice_shift_deprecated(self, frame_or_series): - # GH 37601 - obj = DataFrame({"A": [1, 2, 3, 4]}) - obj = tm.get_obj(obj, frame_or_series) - - with tm.assert_produces_warning(FutureWarning): - obj.slice_shift()
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.0.0.rst` file if fixing a bug or adding a new feature. Deprecation introduced in #37601
https://api.github.com/repos/pandas-dev/pandas/pulls/49271
2022-10-24T02:02:22Z
2022-10-24T05:48:23Z
2022-10-24T05:48:23Z
2022-10-26T10:17:55Z
TST: un-xfail clipboard test on mac
diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py index d76b731ba43f9..c47a963e0fa3c 100644 --- a/pandas/tests/io/test_clipboard.py +++ b/pandas/tests/io/test_clipboard.py @@ -4,6 +4,7 @@ import numpy as np import pytest +from pandas.compat import is_platform_mac from pandas.errors import ( PyperclipException, PyperclipWindowsException, @@ -393,7 +394,7 @@ def test_round_trip_valid_encodings(self, enc, df): @pytest.mark.single_cpu @pytest.mark.parametrize("data", ["\U0001f44d...", "Ωœ∑´...", "abcd..."]) @pytest.mark.xfail( - os.environ.get("DISPLAY") is None, + os.environ.get("DISPLAY") is None and not is_platform_mac(), reason="Cannot be runed if a headless system is not put in place with Xvfb", strict=True, )
- [x] closes #48721 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49270
2022-10-24T00:21:20Z
2022-10-24T05:46:07Z
2022-10-24T05:46:07Z
2022-10-24T14:32:13Z
DEP: Remove Series.str.__iter__
diff --git a/doc/source/whatsnew/v0.12.0.rst b/doc/source/whatsnew/v0.12.0.rst index c12adb2f1334f..6a8008b1e7c82 100644 --- a/doc/source/whatsnew/v0.12.0.rst +++ b/doc/source/whatsnew/v0.12.0.rst @@ -434,7 +434,7 @@ Bug fixes ``Series`` or ``NaN``. For example, .. ipython:: python - :okwarning: + :okexcept: strs = "go", "bow", "joe", "slow" ds = pd.Series(strs) diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 6239ddf9442e7..c1619af190613 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -196,6 +196,7 @@ Removal of prior version deprecations/changes - Removed the ``center`` keyword in :meth:`DataFrame.expanding` (:issue:`20647`) - Removed the ``pandas.datetime`` submodule (:issue:`30489`) - Removed the ``pandas.np`` submodule (:issue:`30296`) +- Removed :meth:`Series.str.__iter__` (:issue:`28277`) - Removed ``pandas.SparseArray`` in favor of :class:`arrays.SparseArray` (:issue:`30642`) - Removed ``pandas.SparseSeries`` and ``pandas.SparseDataFrame`` (:issue:`30642`) - Enforced disallowing a string column label into ``times`` in :meth:`DataFrame.ewm` (:issue:`43265`) diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 67eb4932a6a5c..ff9c72b74e5eb 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -7,7 +7,6 @@ TYPE_CHECKING, Callable, Hashable, - Iterator, Literal, cast, ) @@ -242,19 +241,6 @@ def __getitem__(self, key): result = self._data.array._str_getitem(key) return self._wrap_result(result) - def __iter__(self) -> Iterator: - warnings.warn( - "Columnar iteration over characters will be deprecated in future releases.", - FutureWarning, - stacklevel=find_stack_level(), - ) - i = 0 - g = self.get(i) - while g.notna().any(): - yield g - i += 1 - g = self.get(i) - def _wrap_result( self, result, diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 46bc6d82b55db..56c97ac7a4dc5 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -146,8 +146,8 @@ def shape(self): ((_ for _ in []), True, "generator-empty"), (Series([1]), True, "Series"), (Series([], dtype=object), True, "Series-empty"), - (Series(["a"]).str, True, "StringMethods"), - (Series([], dtype="O").str, True, "StringMethods-empty"), + (Series(["a"]).str, False, "StringMethods"), + (Series([], dtype="O").str, False, "StringMethods-empty"), (Index([1]), True, "Index"), (Index([]), True, "Index-empty"), (DataFrame([[1]]), True, "DataFrame"), diff --git a/pandas/tests/strings/test_cat.py b/pandas/tests/strings/test_cat.py index 4decdff8063a8..01c5bf25e0601 100644 --- a/pandas/tests/strings/test_cat.py +++ b/pandas/tests/strings/test_cat.py @@ -1,3 +1,5 @@ +import re + import numpy as np import pytest @@ -380,18 +382,13 @@ def test_cat_different_classes(klass): def test_cat_on_series_dot_str(): # GH 28277 - # Test future warning of `Series.str.__iter__` ps = Series(["AbC", "de", "FGHI", "j", "kLLLm"]) - with tm.assert_produces_warning(FutureWarning): + + message = re.escape( + "others must be Series, Index, DataFrame, np.ndarray " + "or list-like (either containing only strings or " + "containing only objects of type Series/Index/" + "np.ndarray[1-dim])" + ) + with pytest.raises(TypeError, match=message): ps.str.cat(others=ps.str) - # TODO(2.0): The following code can be uncommented - # when `Series.str.__iter__` is removed. - - # message = re.escape( - # "others must be Series, Index, DataFrame, np.ndarray " - # "or list-like (either containing only strings or " - # "containing only objects of type Series/Index/" - # "np.ndarray[1-dim])" - # ) - # with pytest.raises(TypeError, match=message): - # ps.str.cat(others=ps.str) diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py index d62858f139b0b..beda123facb26 100644 --- a/pandas/tests/strings/test_strings.py +++ b/pandas/tests/strings/test_strings.py @@ -11,7 +11,6 @@ Index, MultiIndex, Series, - isna, ) import pandas._testing as tm @@ -34,74 +33,6 @@ def assert_series_or_index_equal(left, right): tm.assert_index_equal(left, right) -def test_iter(): - # GH3638 - strs = "google", "wikimedia", "wikipedia", "wikitravel" - ser = Series(strs) - - with tm.assert_produces_warning(FutureWarning): - for s in ser.str: - # iter must yield a Series - assert isinstance(s, Series) - - # indices of each yielded Series should be equal to the index of - # the original Series - tm.assert_index_equal(s.index, ser.index) - - for el in s: - # each element of the series is either a basestring/str or nan - assert isinstance(el, str) or isna(el) - - # desired behavior is to iterate until everything would be nan on the - # next iter so make sure the last element of the iterator was 'l' in - # this case since 'wikitravel' is the longest string - assert s.dropna().values.item() == "l" - - -def test_iter_empty(any_string_dtype): - ser = Series([], dtype=any_string_dtype) - - i, s = 100, 1 - - with tm.assert_produces_warning(FutureWarning): - for i, s in enumerate(ser.str): - pass - - # nothing to iterate over so nothing defined values should remain - # unchanged - assert i == 100 - assert s == 1 - - -def test_iter_single_element(any_string_dtype): - ser = Series(["a"], dtype=any_string_dtype) - - with tm.assert_produces_warning(FutureWarning): - for i, s in enumerate(ser.str): - pass - - assert not i - tm.assert_series_equal(ser, s) - - -def test_iter_object_try_string(): - ser = Series( - [ - slice(None, np.random.randint(10), np.random.randint(10, 20)) - for _ in range(4) - ] - ) - - i, s = 100, "h" - - with tm.assert_produces_warning(FutureWarning): - for i, s in enumerate(ser.str): - pass - - assert i == 100 - assert s == "h" - - # test integer/float dtypes (inferred by constructor) and mixed
#28277
https://api.github.com/repos/pandas-dev/pandas/pulls/49268
2022-10-23T22:35:41Z
2022-10-24T18:20:38Z
2022-10-24T18:20:37Z
2022-10-24T21:38:09Z
DEP: Remove truediv from eval
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 6239ddf9442e7..736beffe0418e 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -194,6 +194,7 @@ Removal of prior version deprecations/changes - Remove :meth:`DataFrameGroupBy.pad` and :meth:`DataFrameGroupBy.backfill` (:issue:`45076`) - Remove ``numpy`` argument from :func:`read_json` (:issue:`30636`) - Removed the ``center`` keyword in :meth:`DataFrame.expanding` (:issue:`20647`) +- Removed the ``truediv`` keyword from :func:`eval` (:issue:`29812`) - Removed the ``pandas.datetime`` submodule (:issue:`30489`) - Removed the ``pandas.np`` submodule (:issue:`30296`) - Removed ``pandas.SparseArray`` in favor of :class:`arrays.SparseArray` (:issue:`30642`) diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index baf8c837d7f78..bc8c37b9273ce 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -7,8 +7,6 @@ from typing import TYPE_CHECKING import warnings -from pandas._libs.lib import no_default -from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_bool_kwarg from pandas.core.computation.engines import ENGINES @@ -171,7 +169,6 @@ def eval( expr: str | BinOp, # we leave BinOp out of the docstr bc it isn't for users parser: str = "pandas", engine: str | None = None, - truediv=no_default, local_dict=None, global_dict=None, resolvers=(), @@ -217,12 +214,6 @@ def eval( level python. This engine is generally not that useful. More backends may be available in the future. - - truediv : bool, optional - Whether to use true division, like in Python >= 3. - - .. deprecated:: 1.0.0 - local_dict : dict or None, optional A dictionary of local variables, taken from locals() by default. global_dict : dict or None, optional @@ -305,16 +296,6 @@ def eval( """ inplace = validate_bool_kwarg(inplace, "inplace") - if truediv is not no_default: - warnings.warn( - ( - "The `truediv` parameter in pd.eval is deprecated and " - "will be removed in a future version." - ), - FutureWarning, - stacklevel=find_stack_level(), - ) - exprs: list[str | BinOp] if isinstance(expr, str): _check_expression(expr) diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 6548422c5d2b7..7fce4e9d9c38e 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -1105,40 +1105,6 @@ def test_single_variable(self): df2 = self.eval("df", local_dict={"df": df}) tm.assert_frame_equal(df, df2) - def test_truediv(self): - s = np.array([1]) # noqa:F841 - ex = "s / 1" - - # FutureWarning: The `truediv` parameter in pd.eval is deprecated and will be - # removed in a future version. - with tm.assert_produces_warning(FutureWarning): - res = self.eval(ex, truediv=False) - tm.assert_numpy_array_equal(res, np.array([1.0])) - - with tm.assert_produces_warning(FutureWarning): - res = self.eval(ex, truediv=True) - tm.assert_numpy_array_equal(res, np.array([1.0])) - - with tm.assert_produces_warning(FutureWarning): - res = self.eval("1 / 2", truediv=True) - expec = 0.5 - assert res == expec - - with tm.assert_produces_warning(FutureWarning): - res = self.eval("1 / 2", truediv=False) - expec = 0.5 - assert res == expec - - with tm.assert_produces_warning(FutureWarning): - res = self.eval("s / 2", truediv=False) - expec = 0.5 - assert res == expec - - with tm.assert_produces_warning(FutureWarning): - res = self.eval("s / 2", truediv=True) - expec = 0.5 - assert res == expec - def test_failing_subscript_with_name_error(self): df = DataFrame(np.random.randn(5, 3)) # noqa:F841 with pytest.raises(NameError, match="name 'x' is not defined"): @@ -1859,23 +1825,6 @@ def test_inf(engine, parser): assert result == expected -def test_truediv_deprecated(engine, parser): - # GH#29182 - match = "The `truediv` parameter in pd.eval is deprecated" - - with tm.assert_produces_warning(FutureWarning) as m: - pd.eval("1+1", engine=engine, parser=parser, truediv=True) - - assert len(m) == 1 - assert match in str(m[0].message) - - with tm.assert_produces_warning(FutureWarning) as m: - pd.eval("1+1", engine=engine, parser=parser, truediv=False) - - assert len(m) == 1 - assert match in str(m[0].message) - - @pytest.mark.parametrize("column", ["Temp(°C)", "Capacitance(μF)"]) def test_query_token(engine, column): # See: https://github.com/pandas-dev/pandas/pull/42826
#29812
https://api.github.com/repos/pandas-dev/pandas/pulls/49267
2022-10-23T22:28:30Z
2022-10-24T16:22:10Z
2022-10-24T16:22:09Z
2022-10-24T21:37:58Z
DEP: Remove index.set_value
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 6239ddf9442e7..94fccb95d9a11 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -190,7 +190,7 @@ Removal of prior version deprecations/changes - Removed deprecated :meth:`Categorical.replace`, use :meth:`Series.replace` instead (:issue:`44929`) - Removed the ``numeric_only`` keyword from :meth:`Categorical.min` and :meth:`Categorical.max` in favor of ``skipna`` (:issue:`48821`) - Removed :func:`is_extension_type` in favor of :func:`is_extension_array_dtype` (:issue:`29457`) -- Removed :meth:`Index.get_value` (:issue:`33907`) +- Removed :meth:`Index.get_value` and :meth:`Index.set_value` (:issue:`33907`, :issue:`28621`) - Remove :meth:`DataFrameGroupBy.pad` and :meth:`DataFrameGroupBy.backfill` (:issue:`45076`) - Remove ``numpy`` argument from :func:`read_json` (:issue:`30636`) - Removed the ``center`` keyword in :meth:`DataFrame.expanding` (:issue:`20647`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 7d680688f4731..e89fa7806cba9 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -5905,30 +5905,6 @@ def _get_values_for_loc(self, series: Series, loc, key): return series.iloc[loc] - @final - def set_value(self, arr, key, value) -> None: - """ - Fast lookup of value from 1-dimensional ndarray. - - .. deprecated:: 1.0 - - Notes - ----- - Only use this if you know what you're doing. - """ - warnings.warn( - ( - "The 'set_value' method is deprecated, and " - "will be removed in a future version." - ), - FutureWarning, - stacklevel=find_stack_level(), - ) - loc = self._engine.get_loc(key) - if not can_hold_element(arr, value): - raise ValueError - arr[loc] = value - _index_shared_docs[ "get_indexer_non_unique" ] = """ diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index ff08b72b4a10d..bfe462cdf6c15 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -813,14 +813,6 @@ def test_is_monotonic_incomparable(self, attr): index = Index([5, datetime.now(), 7]) assert not getattr(index, attr) - def test_set_value_deprecated(self, simple_index): - # GH 28621 - idx = simple_index - arr = np.array([1, 2, 3]) - with tm.assert_produces_warning(FutureWarning): - idx.set_value(arr, idx[1], 80) - assert arr[1] == 80 - @pytest.mark.parametrize("values", [["foo", "bar", "quux"], {"foo", "bar", "quux"}]) @pytest.mark.parametrize( "index,expected",
#28621
https://api.github.com/repos/pandas-dev/pandas/pulls/49266
2022-10-23T22:22:35Z
2022-10-24T00:23:32Z
2022-10-24T00:23:32Z
2022-10-24T21:38:03Z
DEPR: kind kwarg in Index.get_slice_bound, Index.slice_indexer, Index.slice_locs
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 6239ddf9442e7..3f26d09a54a76 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -180,6 +180,7 @@ Removal of prior version deprecations/changes - Removed argument ``how`` from :meth:`PeriodIndex.astype`, use :meth:`PeriodIndex.to_timestamp` instead (:issue:`37982`) - Removed argument ``try_cast`` from :meth:`DataFrame.mask`, :meth:`DataFrame.where`, :meth:`Series.mask` and :meth:`Series.where` (:issue:`38836`) - Removed argument ``is_copy`` from :meth:`DataFrame.take` and :meth:`Series.take` (:issue:`30615`) +- Removed argument ``kind`` from :meth:`Index.get_slice_bound`, :meth:`Index.slice_indexer` and :meth:`Index.slice_locs` (:issue:`41378`) - Disallow passing non-round floats to :class:`Timestamp` with ``unit="M"`` or ``unit="Y"`` (:issue:`47266`) - Remove keywords ``convert_float`` and ``mangle_dupe_cols`` from :func:`read_excel` (:issue:`41176`) - Disallow passing non-keyword arguments to :func:`read_excel` except ``io`` and ``sheet_name`` (:issue:`34418`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 7d680688f4731..4e513dcc8b551 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -6471,7 +6471,6 @@ def slice_indexer( start: Hashable | None = None, end: Hashable | None = None, step: int | None = None, - kind=no_default, ) -> slice: """ Compute the slice indexer for input labels and step. @@ -6485,9 +6484,6 @@ def slice_indexer( end : label, default None If None, defaults to the end. step : int, default None - kind : str, default None - - .. deprecated:: 1.4.0 Returns ------- @@ -6514,8 +6510,6 @@ def slice_indexer( >>> idx.slice_indexer(start='b', end=('c', 'g')) slice(1, 3, None) """ - self._deprecated_arg(kind, "kind", "slice_indexer") - start_slice, end_slice = self.slice_locs(start, end, step=step) # return a slice @@ -6550,7 +6544,7 @@ def _validate_indexer(self, form: str_t, key, kind: str_t) -> None: if key is not None and not is_integer(key): self._raise_invalid_indexer(form, key) - def _maybe_cast_slice_bound(self, label, side: str_t, kind=no_default): + def _maybe_cast_slice_bound(self, label, side: str_t): """ This function should be overloaded in subclasses that allow non-trivial casting on label-slice bounds, e.g. datetime-like indices allowing @@ -6560,9 +6554,6 @@ def _maybe_cast_slice_bound(self, label, side: str_t, kind=no_default): ---------- label : object side : {'left', 'right'} - kind : {'loc', 'getitem'} or None - - .. deprecated:: 1.3.0 Returns ------- @@ -6572,8 +6563,6 @@ def _maybe_cast_slice_bound(self, label, side: str_t, kind=no_default): ----- Value of `side` parameter should be validated in caller. """ - assert kind in ["loc", "getitem", None, no_default] - self._deprecated_arg(kind, "kind", "_maybe_cast_slice_bound") # We are a plain index here (sub-class override this method if they # wish to have special treatment for floats/ints, e.g. Float64Index and @@ -6598,9 +6587,7 @@ def _searchsorted_monotonic(self, label, side: Literal["left", "right"] = "left" raise ValueError("index must be monotonic increasing or decreasing") - def get_slice_bound( - self, label, side: Literal["left", "right"], kind=no_default - ) -> int: + def get_slice_bound(self, label, side: Literal["left", "right"]) -> int: """ Calculate slice bound that corresponds to given label. @@ -6611,17 +6598,12 @@ def get_slice_bound( ---------- label : object side : {'left', 'right'} - kind : {'loc', 'getitem'} or None - - .. deprecated:: 1.4.0 Returns ------- int Index of label. """ - assert kind in ["loc", "getitem", None, no_default] - self._deprecated_arg(kind, "kind", "get_slice_bound") if side not in ("left", "right"): raise ValueError( @@ -6667,9 +6649,7 @@ def get_slice_bound( else: return slc - def slice_locs( - self, start=None, end=None, step=None, kind=no_default - ) -> tuple[int, int]: + def slice_locs(self, start=None, end=None, step=None) -> tuple[int, int]: """ Compute slice locations for input labels. @@ -6681,9 +6661,6 @@ def slice_locs( If None, defaults to the end. step : int, defaults None If None, defaults to 1. - kind : {'loc', 'getitem'} or None - - .. deprecated:: 1.4.0 Returns ------- @@ -6703,7 +6680,6 @@ def slice_locs( >>> idx.slice_locs(start='b', end='c') (1, 3) """ - self._deprecated_arg(kind, "kind", "slice_locs") inc = step is None or step >= 0 if not inc: diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 3cf3e50a24c3f..c6c8695ab01da 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -290,7 +290,7 @@ def _partial_date_slice( # try to find the dates return (lhs_mask & rhs_mask).nonzero()[0] - def _maybe_cast_slice_bound(self, label, side: str, kind=lib.no_default): + def _maybe_cast_slice_bound(self, label, side: str): """ If label is a string, cast it to scalar type according to resolution. @@ -298,7 +298,6 @@ def _maybe_cast_slice_bound(self, label, side: str, kind=lib.no_default): ---------- label : object side : {'left', 'right'} - kind : {'loc', 'getitem'} or None Returns ------- @@ -308,9 +307,6 @@ def _maybe_cast_slice_bound(self, label, side: str, kind=lib.no_default): ----- Value of `side` parameter should be validated in caller. """ - assert kind in ["loc", "getitem", None, lib.no_default] - self._deprecated_arg(kind, "kind", "_maybe_cast_slice_bound") - if isinstance(label, str): try: parsed, reso = self._parse_with_reso(label) diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index b08a0d3a60526..32a4b87e9cb33 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -714,7 +714,7 @@ def _maybe_cast_for_get_loc(self, key) -> Timestamp: return key @doc(DatetimeTimedeltaMixin._maybe_cast_slice_bound) - def _maybe_cast_slice_bound(self, label, side: str, kind=lib.no_default): + def _maybe_cast_slice_bound(self, label, side: str): # GH#42855 handle date here instead of get_slice_bound if isinstance(label, date) and not isinstance(label, datetime): @@ -722,11 +722,11 @@ def _maybe_cast_slice_bound(self, label, side: str, kind=lib.no_default): # https://github.com/pandas-dev/pandas/issues/31501 label = Timestamp(label).to_pydatetime() - label = super()._maybe_cast_slice_bound(label, side, kind=kind) + label = super()._maybe_cast_slice_bound(label, side) self._deprecate_mismatched_indexing(label) return self._maybe_cast_for_get_loc(label) - def slice_indexer(self, start=None, end=None, step=None, kind=lib.no_default): + def slice_indexer(self, start=None, end=None, step=None): """ Return indexer for specified label slice. Index.slice_indexer, customized to handle time slicing. @@ -740,8 +740,6 @@ def slice_indexer(self, start=None, end=None, step=None, kind=lib.no_default): value-based selection in non-monotonic cases. """ - self._deprecated_arg(kind, "kind", "slice_indexer") - # For historical reasons DatetimeIndex supports slices between two # instances of datetime.time as if it were applying a slice mask to # an array of (self.hour, self.minute, self.seconds, self.microsecond). @@ -764,7 +762,7 @@ def check_str_or_none(point) -> bool: or check_str_or_none(end) or self.is_monotonic_increasing ): - return Index.slice_indexer(self, start, end, step, kind=kind) + return Index.slice_indexer(self, start, end, step) mask = np.array(True) deprecation_mask = np.array(True) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 3eb3226328a61..8507280a6cc8d 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -786,8 +786,7 @@ def _should_fallback_to_positional(self) -> bool: # ExtensionDtype]" has no attribute "subtype" return self.dtype.subtype.kind in ["m", "M"] # type: ignore[union-attr] - def _maybe_cast_slice_bound(self, label, side: str, kind=lib.no_default): - self._deprecated_arg(kind, "kind", "_maybe_cast_slice_bound") + def _maybe_cast_slice_bound(self, label, side: str): return getattr(self, side)._maybe_cast_slice_bound(label, side) def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 59a0179f93c10..4f8586a4bba13 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2627,7 +2627,6 @@ def get_slice_bound( self, label: Hashable | Sequence[Hashable], side: Literal["left", "right"], - kind=lib.no_default, ) -> int: """ For an ordered MultiIndex, compute slice bound @@ -2640,9 +2639,6 @@ def get_slice_bound( ---------- label : object or tuple of objects side : {'left', 'right'} - kind : {'loc', 'getitem', None} - - .. deprecated:: 1.4.0 Returns ------- @@ -2675,15 +2671,11 @@ def get_slice_bound( MultiIndex.get_locs : Get location for a label/slice/list/mask or a sequence of such. """ - self._deprecated_arg(kind, "kind", "get_slice_bound") - if not isinstance(label, tuple): label = (label,) return self._partial_tup_index(label, side=side) - def slice_locs( - self, start=None, end=None, step=None, kind=lib.no_default - ) -> tuple[int, int]: + def slice_locs(self, start=None, end=None, step=None) -> tuple[int, int]: """ For an ordered MultiIndex, compute the slice locations for input labels. @@ -2700,9 +2692,6 @@ def slice_locs( If None, defaults to the end step : int or None Slice step - kind : string, optional, defaults None - - .. deprecated:: 1.4.0 Returns ------- @@ -2737,7 +2726,6 @@ def slice_locs( MultiIndex.get_locs : Get location for a label/slice/list/mask or a sequence of such. """ - self._deprecated_arg(kind, "kind", "slice_locs") # This function adds nothing to its parent implementation (the magic # happens in get_slice_bound method), but it adds meaningful doc. return super().slice_locs(start, end, step) diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index f0f6dfe4eb147..2cb814be6472c 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -233,10 +233,7 @@ def _convert_slice_indexer(self, key: slice, kind: str, is_frame: bool = False): return super()._convert_slice_indexer(key, kind=kind, is_frame=is_frame) @doc(Index._maybe_cast_slice_bound) - def _maybe_cast_slice_bound(self, label, side: str, kind=lib.no_default): - assert kind in ["loc", "getitem", None, lib.no_default] - self._deprecated_arg(kind, "kind", "_maybe_cast_slice_bound") - + def _maybe_cast_slice_bound(self, label, side: str): # we will try to coerce to integers return self._maybe_cast_indexer(label) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index d67bcfdc78261..a09b987496a40 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -8,10 +8,7 @@ import numpy as np -from pandas._libs import ( - index as libindex, - lib, -) +from pandas._libs import index as libindex from pandas._libs.tslibs import ( BaseOffset, NaT, @@ -474,11 +471,11 @@ def _cast_partial_indexing_scalar(self, label): return key @doc(DatetimeIndexOpsMixin._maybe_cast_slice_bound) - def _maybe_cast_slice_bound(self, label, side: str, kind=lib.no_default): + def _maybe_cast_slice_bound(self, label, side: str): if isinstance(label, datetime): label = self._cast_partial_indexing_scalar(label) - return super()._maybe_cast_slice_bound(label, side, kind=kind) + return super()._maybe_cast_slice_bound(label, side) def _parsed_string_to_bounds(self, reso: Resolution, parsed: datetime): iv = Period(parsed, freq=reso.attr_abbrev) diff --git a/pandas/tests/indexes/base_class/test_indexing.py b/pandas/tests/indexes/base_class/test_indexing.py index 770fa3f6e5dc1..070fec47b90e6 100644 --- a/pandas/tests/indexes/base_class/test_indexing.py +++ b/pandas/tests/indexes/base_class/test_indexing.py @@ -10,23 +10,19 @@ class TestGetSliceBounds: - @pytest.mark.parametrize("kind", ["getitem", "loc", None]) @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)]) - def test_get_slice_bounds_within(self, kind, side, expected): + def test_get_slice_bounds_within(self, side, expected): index = Index(list("abcdef")) - with tm.assert_produces_warning(FutureWarning, match="'kind' argument"): - result = index.get_slice_bound("e", kind=kind, side=side) + result = index.get_slice_bound("e", side=side) assert result == expected - @pytest.mark.parametrize("kind", ["getitem", "loc", None]) @pytest.mark.parametrize("side", ["left", "right"]) @pytest.mark.parametrize( "data, bound, expected", [(list("abcdef"), "x", 6), (list("bcdefg"), "a", 0)] ) - def test_get_slice_bounds_outside(self, kind, side, expected, data, bound): + def test_get_slice_bounds_outside(self, side, expected, data, bound): index = Index(data) - with tm.assert_produces_warning(FutureWarning, match="'kind' argument"): - result = index.get_slice_bound(bound, kind=kind, side=side) + result = index.get_slice_bound(bound, side=side) assert result == expected def test_get_slice_bounds_invalid_side(self): diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 5c8724a2a1c22..87bf0199b2528 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -712,10 +712,9 @@ def test_maybe_cast_slice_duplicate_monotonic(self): class TestGetSliceBounds: @pytest.mark.parametrize("box", [date, datetime, Timestamp]) - @pytest.mark.parametrize("kind", ["getitem", "loc", None]) @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)]) def test_get_slice_bounds_datetime_within( - self, box, kind, side, expected, tz_aware_fixture + self, box, side, expected, tz_aware_fixture ): # GH 35690 tz = tz_aware_fixture @@ -725,15 +724,14 @@ def test_get_slice_bounds_datetime_within( warn = None if tz is None else FutureWarning with tm.assert_produces_warning(warn): # GH#36148 will require tzawareness-compat - result = index.get_slice_bound(key, kind=kind, side=side) + result = index.get_slice_bound(key, side=side) assert result == expected @pytest.mark.parametrize("box", [datetime, Timestamp]) - @pytest.mark.parametrize("kind", ["getitem", "loc", None]) @pytest.mark.parametrize("side", ["left", "right"]) @pytest.mark.parametrize("year, expected", [(1999, 0), (2020, 30)]) def test_get_slice_bounds_datetime_outside( - self, box, kind, side, year, expected, tz_aware_fixture + self, box, side, year, expected, tz_aware_fixture ): # GH 35690 tz = tz_aware_fixture @@ -743,12 +741,11 @@ def test_get_slice_bounds_datetime_outside( warn = None if tz is None else FutureWarning with tm.assert_produces_warning(warn): # GH#36148 will require tzawareness-compat - result = index.get_slice_bound(key, kind=kind, side=side) + result = index.get_slice_bound(key, side=side) assert result == expected @pytest.mark.parametrize("box", [datetime, Timestamp]) - @pytest.mark.parametrize("kind", ["getitem", "loc", None]) - def test_slice_datetime_locs(self, box, kind, tz_aware_fixture): + def test_slice_datetime_locs(self, box, tz_aware_fixture): # GH 34077 tz = tz_aware_fixture index = DatetimeIndex(["2010-01-01", "2010-01-03"]).tz_localize(tz) diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index 7519a3e10811d..fce3da6dd6aee 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -841,8 +841,7 @@ def test_timestamp_multiindex_indexer(): def test_get_slice_bound_with_missing_value(index_arr, expected, target, algo): # issue 19132 idx = MultiIndex.from_arrays(index_arr) - with tm.assert_produces_warning(FutureWarning, match="'kind' argument"): - result = idx.get_slice_bound(target, side=algo, kind="loc") + result = idx.get_slice_bound(target, side=algo) assert result == expected diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py index 1c4cbd21a988e..0c2c5e0b903bc 100644 --- a/pandas/tests/indexes/numeric/test_indexing.py +++ b/pandas/tests/indexes/numeric/test_indexing.py @@ -576,20 +576,15 @@ def test_slice_locs_na_raises(self): class TestGetSliceBounds: - @pytest.mark.parametrize("kind", ["getitem", "loc", None]) @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)]) - def test_get_slice_bounds_within(self, kind, side, expected): + def test_get_slice_bounds_within(self, side, expected): index = Index(range(6)) - with tm.assert_produces_warning(FutureWarning, match="'kind' argument"): - - result = index.get_slice_bound(4, kind=kind, side=side) + result = index.get_slice_bound(4, side=side) assert result == expected - @pytest.mark.parametrize("kind", ["getitem", "loc", None]) @pytest.mark.parametrize("side", ["left", "right"]) @pytest.mark.parametrize("bound, expected", [(-1, 0), (10, 6)]) - def test_get_slice_bounds_outside(self, kind, side, expected, bound): + def test_get_slice_bounds_outside(self, side, expected, bound): index = Index(range(6)) - with tm.assert_produces_warning(FutureWarning, match="'kind' argument"): - result = index.get_slice_bound(bound, kind=kind, side=side) + result = index.get_slice_bound(bound, side=side) assert result == expected diff --git a/pandas/tests/indexes/test_indexing.py b/pandas/tests/indexes/test_indexing.py index a0cb6691cb6a0..2b7c5745e0c67 100644 --- a/pandas/tests/indexes/test_indexing.py +++ b/pandas/tests/indexes/test_indexing.py @@ -297,19 +297,6 @@ def test_getitem_deprecated_float(idx): assert result == expected -def test_maybe_cast_slice_bound_kind_deprecated(index): - if not len(index): - return - - with tm.assert_produces_warning(FutureWarning): - # passed as keyword - index._maybe_cast_slice_bound(index[0], "left", kind="loc") - - with tm.assert_produces_warning(FutureWarning): - # pass as positional - index._maybe_cast_slice_bound(index[0], "left", "loc") - - @pytest.mark.parametrize( "idx,target,expected", [
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.0.0.rst` file if fixing a bug or adding a new feature. Deprecation introduced in #41378
https://api.github.com/repos/pandas-dev/pandas/pulls/49265
2022-10-23T21:19:46Z
2022-10-24T18:23:24Z
2022-10-24T18:23:24Z
2022-10-26T10:17:55Z
Improve error message about duplicate columns in df.explode
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d741ca21d8ca7..52e85b86342b6 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8939,7 +8939,11 @@ def explode( 3 4 1 e """ if not self.columns.is_unique: - raise ValueError("columns must be unique") + duplicate_cols = self.columns[self.columns.duplicated()].tolist() + raise ValueError( + "DataFrame columns must be unique. " + + f"Duplicate columns: {duplicate_cols}" + ) columns: list[Hashable] if is_scalar(column) or isinstance(column, tuple): diff --git a/pandas/tests/frame/methods/test_explode.py b/pandas/tests/frame/methods/test_explode.py index 8716a181120f6..6d9874dc58c17 100644 --- a/pandas/tests/frame/methods/test_explode.py +++ b/pandas/tests/frame/methods/test_explode.py @@ -1,3 +1,5 @@ +import re + import numpy as np import pytest @@ -18,7 +20,10 @@ def test_error(): df.explode(list("AA")) df.columns = list("AA") - with pytest.raises(ValueError, match="columns must be unique"): + with pytest.raises( + ValueError, + match=re.escape("DataFrame columns must be unique. Duplicate columns: ['A']"), + ): df.explode("A")
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This is an attempt to improve the error message happening when exploding a column in a data frame with duplicate columns. As a newbie with pandas, it was really confusing to me why this happens – I was looking for a key inside the exploded column that would cause a duplicate. Eventually, I had to go to the source code to understand that it was not related. If listing the duplicate columns is too much/not a standard practice, I would vote for changing it at least to something like `data frame columns must be unique`.
https://api.github.com/repos/pandas-dev/pandas/pulls/49264
2022-10-23T19:30:54Z
2022-10-26T19:06:58Z
2022-10-26T19:06:58Z
2022-10-26T19:23:29Z