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
TST: test custom _formatter for ExtensionArray + revert ExtensionArrayFormatter removal
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 18aa0580d7df7..24fcb32d09d27 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1061,9 +1061,11 @@ def _format_with_header(self, header, **kwargs): def _format_native_types(self, na_rep='NaN', quoting=None, **kwargs): """ actually format my specific types """ - from pandas.io.formats.format import format_array - return format_array(values=self, na_rep=na_rep, justify='all', - leading_space=False) + from pandas.io.formats.format import ExtensionArrayFormatter + return ExtensionArrayFormatter(values=self, + na_rep=na_rep, + justify='all', + leading_space=False).get_result() def _format_data(self, name=None): diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 66af6c2172344..f632bc13a5b24 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -849,7 +849,7 @@ def _get_column_name_list(self): # Array formatters -def format_array(values, formatter=None, float_format=None, na_rep='NaN', +def format_array(values, formatter, float_format=None, na_rep='NaN', digits=None, space=None, justify='right', decimal='.', leading_space=None): """ @@ -879,23 +879,14 @@ def format_array(values, formatter=None, float_format=None, na_rep='NaN', List[str] """ - if is_extension_array_dtype(values.dtype): - if isinstance(values, (ABCIndexClass, ABCSeries)): - values = values._values - - if is_categorical_dtype(values.dtype): - # Categorical is special for now, so that we can preserve tzinfo - values = values.get_values() - - if not is_datetime64tz_dtype(values.dtype): - values = np.asarray(values) - if is_datetime64_dtype(values.dtype): fmt_klass = Datetime64Formatter elif is_datetime64tz_dtype(values): fmt_klass = Datetime64TZFormatter elif is_timedelta64_dtype(values.dtype): fmt_klass = Timedelta64Formatter + elif is_extension_array_dtype(values.dtype): + fmt_klass = ExtensionArrayFormatter elif is_float_dtype(values.dtype) or is_complex_dtype(values.dtype): fmt_klass = FloatArrayFormatter elif is_integer_dtype(values.dtype): @@ -1190,6 +1181,29 @@ def _format_strings(self): return fmt_values.tolist() +class ExtensionArrayFormatter(GenericArrayFormatter): + def _format_strings(self): + values = self.values + if isinstance(values, (ABCIndexClass, ABCSeries)): + values = values._values + + formatter = values._formatter(boxed=True) + + if is_categorical_dtype(values.dtype): + # Categorical is special for now, so that we can preserve tzinfo + array = values.get_values() + else: + array = np.asarray(values) + + fmt_values = format_array(array, + formatter, + float_format=self.float_format, + na_rep=self.na_rep, digits=self.digits, + space=self.space, justify=self.justify, + leading_space=self.leading_space) + return fmt_values + + def format_percentiles(percentiles): """ Outputs rounded and formatted percentiles. diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 1823eeb4d7fc0..3b95c8d919eb1 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -137,6 +137,11 @@ def isna(self): def _na_value(self): return decimal.Decimal('NaN') + def _formatter(self, boxed=False): + if boxed: + return "Decimal: {0}".format + return repr + @classmethod def _concat_same_type(cls, to_concat): return cls(np.concatenate([x._data for x in to_concat])) diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 97fae41bcc720..94c0b61c6382a 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -200,7 +200,13 @@ class TestSetitem(BaseDecimal, base.BaseSetitemTests): class TestPrinting(BaseDecimal, base.BasePrintingTests): - pass + + def test_series_repr(self, data): + # Overriding this base test to explicitly test that + # the custom _formatter is used + ser = pd.Series(data) + assert data.dtype.name in repr(ser) + assert "Decimal: " in repr(ser) # TODO(extension)
xref https://github.com/pandas-dev/pandas/pull/26833#issuecomment-502012046 @simonjayhawkins this would be a test for the `_formatter` functionality (it is passing on master before the removal of ExtensionArrayFormatter Adds an actual test for EA._formatter + reverts https://github.com/pandas-dev/pandas/pull/26833 until we have a more complete solution for simplifying the formatters that take the EA._formatter into account.
https://api.github.com/repos/pandas-dev/pandas/pulls/26845
2019-06-14T08:17:02Z
2019-06-14T12:51:06Z
2019-06-14T12:51:05Z
2019-06-14T13:01:35Z
DEPR: deprecate Timedelta.resolution
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index fd47ca14dc788..d3851662c34ec 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -501,7 +501,7 @@ Other Deprecations Use the public attributes :attr:`~RangeIndex.start`, :attr:`~RangeIndex.stop` and :attr:`~RangeIndex.step` instead (:issue:`26581`). - The :meth:`Series.ftype`, :meth:`Series.ftypes` and :meth:`DataFrame.ftypes` methods are deprecated and will be removed in a future version. Instead, use :meth:`Series.dtype` and :meth:`DataFrame.dtypes` (:issue:`26705`). - +- :meth:`Timedelta.resolution` is deprecated and replaced with :meth:`Timedelta.resolution_string`. In a future version, :meth:`Timedelta.resolution` will be changed to behave like the standard library :attr:`timedelta.resolution` (:issue:`21344`) .. _whatsnew_0250.prior_deprecations: diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index ad60165e98d4f..6a32553fe2d38 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -950,7 +950,7 @@ cdef class _Timedelta(timedelta): return np.int64(self.value).view('m8[ns]') @property - def resolution(self): + def resolution_string(self): """ Return a string representing the lowest timedelta resolution. @@ -991,7 +991,6 @@ cdef class _Timedelta(timedelta): >>> td.resolution 'U' """ - self._ensure_components() if self._ns: return "N" @@ -1008,6 +1007,56 @@ cdef class _Timedelta(timedelta): else: return "D" + @property + def resolution(self): + """ + Return a string representing the lowest timedelta resolution. + + Each timedelta has a defined resolution that represents the lowest OR + most granular level of precision. Each level of resolution is + represented by a short string as defined below: + + Resolution: Return value + + * Days: 'D' + * Hours: 'H' + * Minutes: 'T' + * Seconds: 'S' + * Milliseconds: 'L' + * Microseconds: 'U' + * Nanoseconds: 'N' + + Returns + ------- + str + Timedelta resolution. + + Examples + -------- + >>> td = pd.Timedelta('1 days 2 min 3 us 42 ns') + >>> td.resolution + 'N' + + >>> td = pd.Timedelta('1 days 2 min 3 us') + >>> td.resolution + 'U' + + >>> td = pd.Timedelta('2 min 3 s') + >>> td.resolution + 'S' + + >>> td = pd.Timedelta(36, unit='us') + >>> td.resolution + 'U' + """ + # See GH#21344 + warnings.warn("Timedelta.resolution is deprecated, in a future " + "version will behave like the standard library " + "datetime.timedelta.resolution attribute. " + "Use Timedelta.resolution_string instead.", + FutureWarning) + return self.resolution_string + @property def nanoseconds(self): """ diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index f5362c0b6bb5d..ba5507fa71e8c 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -551,11 +551,11 @@ def _maybe_cast_slice_bound(self, label, side, kind): if isinstance(label, str): parsed = Timedelta(label) - lbound = parsed.round(parsed.resolution) + lbound = parsed.round(parsed.resolution_string) if side == 'left': return lbound else: - return (lbound + to_offset(parsed.resolution) - + return (lbound + to_offset(parsed.resolution_string) - Timedelta(1, 'ns')) elif ((is_integer(label) or is_float(label)) and not is_timedelta64_dtype(label)): diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 0ae4d107d85bd..19426c3bf3ffb 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -142,8 +142,8 @@ def test_nat_iso_format(get_nat): @pytest.mark.parametrize("klass,expected", [ (Timestamp, ["freqstr", "normalize", "to_julian_date", "to_period", "tz"]), - (Timedelta, ["components", "delta", "is_populated", "to_pytimedelta", - "to_timedelta64", "view"]) + (Timedelta, ["components", "delta", "is_populated", "resolution_string", + "to_pytimedelta", "to_timedelta64", "view"]) ]) def test_missing_public_nat_methods(klass, expected): # see gh-17327 diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index 57b3705640202..f10876531e66a 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -742,6 +742,22 @@ def test_components(self): assert not result.iloc[0].isna().all() assert result.iloc[1].isna().all() + def test_resolution_string(self): + assert Timedelta(days=1).resolution_string == 'D' + assert Timedelta(days=1, hours=6).resolution_string == 'H' + assert Timedelta(days=1, minutes=6).resolution_string == 'T' + assert Timedelta(days=1, seconds=6).resolution_string == 'S' + assert Timedelta(days=1, milliseconds=6).resolution_string == 'L' + assert Timedelta(days=1, microseconds=6).resolution_string == 'U' + assert Timedelta(days=1, nanoseconds=6).resolution_string == 'N' + + def test_resolution_deprecated(self): + # GH#21344 + td = Timedelta(days=4, hours=3) + with tm.assert_produces_warning(FutureWarning) as w: + td.resolution + assert "Use Timedelta.resolution_string instead" in str(w[0].message) + @pytest.mark.parametrize('value, expected', [ (Timedelta('10S'), True),
- [x] closes #21344 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry AFAICT we don't have any tests specifically for Timedelta.resolution, so added one for reso_str.
https://api.github.com/repos/pandas-dev/pandas/pulls/26839
2019-06-13T23:00:13Z
2019-06-17T11:44:40Z
2019-06-17T11:44:40Z
2019-06-17T17:06:27Z
BUG: Handle NA values for ExtensionArrays in Series.count
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 76ee21b4c9a50..d7cf8f6a24f6e 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -729,11 +729,16 @@ Sparse - Bug in :class:`SparseDataFrame` when adding a column in which the length of values does not match length of index, ``AssertionError`` is raised instead of raising ``ValueError`` (:issue:`25484`) - Introduce a better error message in :meth:`Series.sparse.from_coo` so it returns a ``TypeError`` for inputs that are not coo matrices (:issue:`26554`) +ExtensionArray +^^^^^^^^^^^^^^ + +- Bug in :func:`factorize` when passing an ``ExtensionArray`` with a custom ``na_sentinel`` (:issue:`25696`). +- :meth:`Series.count` miscounts NA values in ExtensionArrays (:issue:`26835`) + Other ^^^^^ - Removed unused C functions from vendored UltraJSON implementation (:issue:`26198`) -- Bug in :func:`factorize` when passing an ``ExtensionArray`` with a custom ``na_sentinel`` (:issue:`25696`). - Allow :class:`Index` and :class:`RangeIndex` to be passed to numpy ``min`` and ``max`` functions (:issue:`26125`) .. _whatsnew_0.250.contributors: diff --git a/pandas/core/series.py b/pandas/core/series.py index f0362596920a6..9f94ecff26138 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1651,7 +1651,7 @@ def count(self, level=None): 2 """ if level is None: - return notna(com.values_from_object(self)).sum() + return notna(self.array).sum() if isinstance(level, str): level = self.index._get_level_number(level) diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index 1852edaa9e748..c8fd4d1b708e5 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -30,6 +30,13 @@ def test_count(self, data_missing): expected = pd.Series([0, 1]) self.assert_series_equal(result, expected) + def test_series_count(self, data_missing): + # GH#26835 + ser = pd.Series(data_missing) + result = ser.count() + expected = 1 + assert result == expected + def test_apply_simple_series(self, data): result = pd.Series(data).apply(id) assert isinstance(result, pd.Series)
- [X] closes #26835 - [x] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/26836
2019-06-13T18:22:27Z
2019-06-21T21:19:59Z
2019-06-21T21:19:58Z
2019-06-22T03:02:48Z
DOC: array class docstring pages without autosummary tables
diff --git a/doc/source/reference/arrays.rst b/doc/source/reference/arrays.rst index fb9a95b6736d5..38406bf5b2656 100644 --- a/doc/source/reference/arrays.rst +++ b/doc/source/reference/arrays.rst @@ -144,6 +144,7 @@ If the data are tz-aware, then every value in the array must have the same timez .. autosummary:: :toctree: api/ + :template: autosummary/class_without_autosummary.rst arrays.DatetimeArray @@ -204,6 +205,7 @@ A collection of timedeltas may be stored in a :class:`TimedeltaArray`. .. autosummary:: :toctree: api/ + :template: autosummary/class_without_autosummary.rst arrays.TimedeltaArray @@ -263,6 +265,7 @@ Every period in a ``PeriodArray`` must have the same ``freq``. .. autosummary:: :toctree: api/ + :template: autosummary/class_without_autosummary.rst arrays.PeriodArray @@ -304,6 +307,7 @@ A collection of intervals may be stored in an :class:`arrays.IntervalArray`. .. autosummary:: :toctree: api/ + :template: autosummary/class_without_autosummary.rst arrays.IntervalArray @@ -313,6 +317,29 @@ A collection of intervals may be stored in an :class:`arrays.IntervalArray`. IntervalDtype + +.. Those attributes and methods are included in the API because the docstrings +.. of IntervalIndex and IntervalArray are shared. Including it here to make +.. sure a docstring page is built for them to avoid warnings + +.. + .. autosummary:: + :toctree: api/ + + arrays.IntervalArray.left + arrays.IntervalArray.right + arrays.IntervalArray.closed + arrays.IntervalArray.mid + arrays.IntervalArray.length + arrays.IntervalArray.is_non_overlapping_monotonic + arrays.IntervalArray.from_arrays + arrays.IntervalArray.from_tuples + arrays.IntervalArray.from_breaks + arrays.IntervalArray.overlaps + arrays.IntervalArray.set_closed + arrays.IntervalArray.to_tuples + + .. _api.arrays.integer_na: Nullable Integer @@ -323,6 +350,7 @@ Pandas provides this through :class:`arrays.IntegerArray`. .. autosummary:: :toctree: api/ + :template: autosummary/class_without_autosummary.rst arrays.IntegerArray @@ -414,6 +442,7 @@ be stored efficiently as a :class:`SparseArray`. .. autosummary:: :toctree: api/ + :template: autosummary/class_without_autosummary.rst SparseArray diff --git a/doc/source/reference/extensions.rst b/doc/source/reference/extensions.rst index 6146e34fab274..34f76642119c8 100644 --- a/doc/source/reference/extensions.rst +++ b/doc/source/reference/extensions.rst @@ -19,4 +19,9 @@ objects. api.extensions.register_index_accessor api.extensions.ExtensionDtype api.extensions.ExtensionArray + +.. autosummary:: + :toctree: api/ + :template: autosummary/class_without_autosummary.rst + arrays.PandasArray diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index bf7bd0668595d..47aef3c84c9f7 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -236,6 +236,14 @@ class DatetimeArray(dtl.DatetimeLikeArrayMixin, freq : str or Offset, optional copy : bool, default False Whether to copy the underlying array of values. + + Attributes + ---------- + None + + Methods + ------- + None """ _typ = "datetimearray" _scalar_type = Timestamp diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 29337b7f76131..589e98f016f69 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -244,6 +244,14 @@ class IntegerArray(ExtensionArray, ExtensionOpsMixin): copy : bool, default False Whether to copy the `values` and `mask`. + Attributes + ---------- + None + + Methods + ------- + None + Returns ------- IntegerArray diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 0deefd2b10b6e..f651f89fab834 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -98,6 +98,14 @@ class PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin): The NumPy ndarray to wrap. Must be 1-dimensional. copy : bool, default False Whether to copy `values`. + + Attributes + ---------- + None + + Methods + ------- + None """ # If you're wondering why pd.Series(cls) doesn't put the array in an # ExtensionBlock, search for `ABCPandasArray`. We check for diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index a6e282462af68..ece05567d3343 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -112,6 +112,14 @@ class PeriodArray(dtl.DatetimeLikeArrayMixin, dtl.DatelikeOps): copy : bool, default False Whether to copy the ordinals before storing. + Attributes + ---------- + None + + Methods + ------- + None + See Also -------- period_array : Create a new PeriodArray. diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py index ca6e2c04f5a69..5e636b5105e56 100644 --- a/pandas/core/arrays/sparse.py +++ b/pandas/core/arrays/sparse.py @@ -572,6 +572,14 @@ class SparseArray(PandasObject, ExtensionArray, ExtensionOpsMixin): this determines ``self.sp_values`` and ``self.fill_value``. copy : bool, default False Whether to explicitly copy the incoming `data` array. + + Attributes + ---------- + None + + Methods + ------- + None """ _pandas_ftype = 'sparse' diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 3ba6829b4ac28..50bc8d6d3ae6b 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -127,6 +127,14 @@ class TimedeltaArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps): freq : Offset, optional copy : bool, default False Whether to copy the underlying array of data. + + Attributes + ---------- + None + + Methods + ------- + None """ _typ = "timedeltaarray" _scalar_type = Timedelta
See discussion in https://github.com/pandas-dev/pandas/pull/26810 This just adds the "class_without_autosummary". Longer term, we could choose to add certain methods of the Array API to the html api pages, but for now just wanted to do this to get rid of the warnings.
https://api.github.com/repos/pandas-dev/pandas/pulls/26834
2019-06-13T17:48:09Z
2019-06-14T06:43:55Z
2019-06-14T06:43:54Z
2019-06-14T06:43:58Z
REF: remove ExtensionArrayFormatter
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 24fcb32d09d27..18aa0580d7df7 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1061,11 +1061,9 @@ def _format_with_header(self, header, **kwargs): def _format_native_types(self, na_rep='NaN', quoting=None, **kwargs): """ actually format my specific types """ - from pandas.io.formats.format import ExtensionArrayFormatter - return ExtensionArrayFormatter(values=self, - na_rep=na_rep, - justify='all', - leading_space=False).get_result() + from pandas.io.formats.format import format_array + return format_array(values=self, na_rep=na_rep, justify='all', + leading_space=False) def _format_data(self, name=None): diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index f632bc13a5b24..66af6c2172344 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -849,7 +849,7 @@ def _get_column_name_list(self): # Array formatters -def format_array(values, formatter, float_format=None, na_rep='NaN', +def format_array(values, formatter=None, float_format=None, na_rep='NaN', digits=None, space=None, justify='right', decimal='.', leading_space=None): """ @@ -879,14 +879,23 @@ def format_array(values, formatter, float_format=None, na_rep='NaN', List[str] """ + if is_extension_array_dtype(values.dtype): + if isinstance(values, (ABCIndexClass, ABCSeries)): + values = values._values + + if is_categorical_dtype(values.dtype): + # Categorical is special for now, so that we can preserve tzinfo + values = values.get_values() + + if not is_datetime64tz_dtype(values.dtype): + values = np.asarray(values) + if is_datetime64_dtype(values.dtype): fmt_klass = Datetime64Formatter elif is_datetime64tz_dtype(values): fmt_klass = Datetime64TZFormatter elif is_timedelta64_dtype(values.dtype): fmt_klass = Timedelta64Formatter - elif is_extension_array_dtype(values.dtype): - fmt_klass = ExtensionArrayFormatter elif is_float_dtype(values.dtype) or is_complex_dtype(values.dtype): fmt_klass = FloatArrayFormatter elif is_integer_dtype(values.dtype): @@ -1181,29 +1190,6 @@ def _format_strings(self): return fmt_values.tolist() -class ExtensionArrayFormatter(GenericArrayFormatter): - def _format_strings(self): - values = self.values - if isinstance(values, (ABCIndexClass, ABCSeries)): - values = values._values - - formatter = values._formatter(boxed=True) - - if is_categorical_dtype(values.dtype): - # Categorical is special for now, so that we can preserve tzinfo - array = values.get_values() - else: - array = np.asarray(values) - - fmt_values = format_array(array, - formatter, - float_format=self.float_format, - na_rep=self.na_rep, digits=self.digits, - space=self.space, justify=self.justify, - leading_space=self.leading_space) - return fmt_values - - def format_percentiles(percentiles): """ Outputs rounded and formatted percentiles.
- [ ] precursor #26000 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/26833
2019-06-13T17:42:06Z
2019-06-13T19:04:29Z
2019-06-13T19:04:29Z
2019-06-21T09:53:42Z
Bump minimum verions
diff --git a/ci/deps/azure-35-compat.yaml b/ci/deps/azure-35-compat.yaml index 6643f804eb6f7..c783670e78d52 100644 --- a/ci/deps/azure-35-compat.yaml +++ b/ci/deps/azure-35-compat.yaml @@ -3,20 +3,20 @@ channels: - defaults - conda-forge dependencies: - - beautifulsoup4=4.4.1 + - beautifulsoup4=4.6.0 - bottleneck=1.2.1 - jinja2=2.8 - numexpr=2.6.2 - numpy=1.13.3 - - openpyxl=2.4.0 + - openpyxl=2.4.8 - pytables=3.4.2 - - python-dateutil=2.5.0 + - python-dateutil=2.6.1 - python=3.5.* - - pytz=2015.4 + - pytz=2017.2 - scipy=0.19.0 - - xlrd=1.0.0 - - xlsxwriter=0.7.7 - - xlwt=1.0.0 + - xlrd=1.1.0 + - xlsxwriter=0.9.8 + - xlwt=1.2.0 # universal - cython=0.28.2 - hypothesis>=3.58.0 diff --git a/ci/deps/azure-36-locale.yaml b/ci/deps/azure-36-locale.yaml index 320839756befb..fbb240734d45d 100644 --- a/ci/deps/azure-36-locale.yaml +++ b/ci/deps/azure-36-locale.yaml @@ -3,21 +3,21 @@ channels: - defaults - conda-forge dependencies: - - beautifulsoup4==4.5.1 + - beautifulsoup4==4.6.0 - bottleneck=1.2.* - cython=0.28.2 - lxml - matplotlib=2.2.2 - numpy=1.14.* - - openpyxl=2.4.0 + - openpyxl=2.4.8 - python-dateutil - python-blosc - python=3.6.* - - pytz=2016.10 + - pytz=2017.2 - scipy - sqlalchemy=1.1.4 - - xlrd=1.0.0 - - xlsxwriter=0.9.4 + - xlrd=1.1.0 + - xlsxwriter=0.9.8 - xlwt=1.2.0 # universal - pytest>=4.0.2 diff --git a/ci/deps/azure-macos-35.yaml b/ci/deps/azure-macos-35.yaml index 30290277fd644..8ed48b46b5b5a 100644 --- a/ci/deps/azure-macos-35.yaml +++ b/ci/deps/azure-macos-35.yaml @@ -16,13 +16,13 @@ dependencies: - pyarrow - pytables - python=3.5.* + - python-dateutil==2.6.1 - pytz - xarray - xlrd - xlsxwriter - xlwt - pip: - - python-dateutil==2.5.3 # universal - pytest==4.5.0 - pytest-xdist diff --git a/doc/source/install.rst b/doc/source/install.rst index 2b8352ff9a1a5..db31d75e3013e 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -220,13 +220,19 @@ installed), make sure you have `pytest ==================== 12130 passed, 12 skipped in 368.339 seconds ===================== +.. _install.dependencies: + Dependencies ------------ -* `setuptools <https://setuptools.readthedocs.io/en/latest/>`__: 24.2.0 or higher -* `NumPy <http://www.numpy.org>`__: 1.13.3 or higher -* `python-dateutil <https://dateutil.readthedocs.io/en/stable/>`__: 2.5.0 or higher -* `pytz <http://pytz.sourceforge.net/>`__: 2015.4 or higher +================================================================ ========================== +Package Minimum supported version +================================================================ ========================== +`setuptools <https://setuptools.readthedocs.io/en/latest/>`__ 24.2.0 +`NumPy <http://www.numpy.org>`__ 1.13.3 +`python-dateutil <https://dateutil.readthedocs.io/en/stable/>`__ 2.6.1 +`pytz <http://pytz.sourceforge.net/>`__ 2017.2 +================================================================ ========================== .. _install.recommended_dependencies: @@ -260,21 +266,21 @@ the method requiring that dependency is called. ========================= ================== ============================================================= Dependency Minimum Version Notes ========================= ================== ============================================================= -BeautifulSoup4 4.4.1 HTML parser for read_html (see :ref:`note <optional_html>`) +BeautifulSoup4 4.6.0 HTML parser for read_html (see :ref:`note <optional_html>`) Jinja2 Conditional formatting with DataFrame.style PyQt4 Clipboard I/O PyQt5 Clipboard I/O PyTables 3.4.2 HDF5-based reading / writing SQLAlchemy 1.1.4 SQL support for databases other than sqlite SciPy 0.19.0 Miscellaneous statistical functions -XLsxWriter Excel writing +XLsxWriter 0.9.8 Excel writing blosc Compression for msgpack fastparquet 0.2.1 Parquet reading / writing gcsfs 0.1.0 Google Cloud Storage access html5lib HTML parser for read_html (see :ref:`note <optional_html>`) lxml HTML parser for read_html (see :ref:`note <optional_html>`) matplotlib 2.2.2 Visualization -openpyxl 2.4.0 Reading / writing for xlsx files +openpyxl 2.4.8 Reading / writing for xlsx files pandas-gbq 0.8.0 Google Big Query access psycopg2 PostgreSQL engine for sqlalchemy pyarrow 0.9.0 Parquet and feather reading / writing @@ -283,8 +289,8 @@ qtpy Clipboard I/O s3fs 0.0.8 Amazon S3 access xarray 0.8.2 pandas-like API for N-dimensional data xclip Clipboard I/O on linux -xlrd 1.0.0 Excel reading -xlwt 2.4.0 Excel writing +xlrd 1.1.0 Excel reading +xlwt 1.2.0 Excel writing xsel Clipboard I/O on linux zlib Compression for msgpack ========================= ================== ============================================================= diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 76ee21b4c9a50..c1d4797af9145 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -401,6 +401,8 @@ If installed, we now require: +-----------------+-----------------+----------+ | pytz | 2015.4 | X | +-----------------+-----------------+----------+ +| python-dateutil | 2.6.1 | X | ++-----------------+-----------------+----------+ | bottleneck | 1.2.1 | | +-----------------+-----------------+----------+ | numexpr | 2.6.2 | | @@ -415,11 +417,13 @@ Optional libraries below the lowest tested version may still work, but are not c +-----------------+-----------------+ | Package | Minimum Version | +=================+=================+ +| beautifulsoup4 | 4.6.0 | ++-----------------+-----------------+ | fastparquet | 0.2.1 | +-----------------+-----------------+ | matplotlib | 2.2.2 | +-----------------+-----------------+ -| openpyxl | 2.4.0 | +| openpyxl | 2.4.8 | +-----------------+-----------------+ | pyarrow | 0.9.0 | +-----------------+-----------------+ @@ -431,13 +435,15 @@ Optional libraries below the lowest tested version may still work, but are not c +-----------------+-----------------+ | xarray | 0.8.2 | +-----------------+-----------------+ -| xlrd | 1.0.0 | +| xlrd | 1.1.0 | +-----------------+-----------------+ -| xlsxwriter | 0.7.7 | +| xlsxwriter | 0.9.8 | +-----------------+-----------------+ -| xlwt | 1.0.0 | +| xlwt | 1.2.0 | +-----------------+-----------------+ +See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more. + .. _whatsnew_0250.api.other: Other API Changes diff --git a/environment.yml b/environment.yml index 200aa0428f1e1..7db2ec72ccb3b 100644 --- a/environment.yml +++ b/environment.yml @@ -6,7 +6,7 @@ dependencies: # required - numpy>=1.15 - python=3 - - python-dateutil>=2.5.0 + - python-dateutil>=2.6.1 - pytz # benchmarks @@ -64,7 +64,7 @@ dependencies: - scipy>=1.1 # optional for io - - beautifulsoup4>=4.2.1 # pandas.read_html + - beautifulsoup4>=4.6.0 # pandas.read_html - fastparquet>=0.2.1 # pandas.read_parquet, DataFrame.to_parquet - html5lib # pandas.read_html - lxml # pandas.read_html diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index f36ff5c2b8abd..4a7b8c4e88649 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -6,13 +6,13 @@ # Update install.rst when updating versions! VERSIONS = { - "bs4": "4.4.1", + "bs4": "4.6.0", "bottleneck": "1.2.1", "fastparquet": "0.2.1", "gcsfs": "0.1.0", "matplotlib": "2.2.2", "numexpr": "2.6.2", - "openpyxl": "2.4.0", + "openpyxl": "2.4.8", "pandas_gbq": "0.8.0", "pyarrow": "0.9.0", "pytables": "3.4.2", @@ -20,8 +20,9 @@ "scipy": "0.19.0", "sqlalchemy": "1.1.4", "xarray": "0.8.2", - "xlrd": "1.0.0", - "xlwt": "2.4.0", + "xlrd": "1.1.0", + "xlwt": "1.2.0", + "xlsxwriter": "0.9.8", } message = ( diff --git a/requirements-dev.txt b/requirements-dev.txt index 46e857f2e9e0f..b40aa86e946b6 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,5 +1,5 @@ numpy>=1.15 -python-dateutil>=2.5.0 +python-dateutil>=2.6.1 pytz asv cython>=0.28.2 @@ -38,7 +38,7 @@ jinja2 matplotlib>=2.2.2 numexpr>=2.6.8 scipy>=1.1 -beautifulsoup4>=4.2.1 +beautifulsoup4>=4.6.0 fastparquet>=0.2.1 html5lib lxml diff --git a/setup.py b/setup.py index cb9d4ace8161e..4579bbfa59797 100755 --- a/setup.py +++ b/setup.py @@ -33,8 +33,8 @@ def is_platform_mac(): min_numpy_ver = '1.13.3' setuptools_kwargs = { 'install_requires': [ - 'python-dateutil >= 2.5.0', - 'pytz >= 2015.4', + 'python-dateutil >= 2.6.1', + 'pytz >= 2017.2', 'numpy >= {numpy_ver}'.format(numpy_ver=min_numpy_ver), ], 'setup_requires': ['numpy >= {numpy_ver}'.format(numpy_ver=min_numpy_ver)],
xref https://github.com/pandas-dev/pandas/pull/26595#issuecomment-500934897
https://api.github.com/repos/pandas-dev/pandas/pulls/26832
2019-06-13T16:56:52Z
2019-06-13T19:53:56Z
2019-06-13T19:53:56Z
2019-06-13T19:53:57Z
DOC: Replacing travis doc deps by environment.yml
diff --git a/.travis.yml b/.travis.yml index fd59544d9b3c6..4d1281819e2cd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -51,14 +51,14 @@ matrix: # In allow_failures - dist: trusty env: - - JOB="3.6, doc" ENV_FILE="ci/deps/travis-36-doc.yaml" DOC=true + - JOB="3.6, doc" ENV_FILE="environment.yml" DOC=true allow_failures: - dist: trusty env: - JOB="3.6, slow" ENV_FILE="ci/deps/travis-36-slow.yaml" PATTERN="slow" - dist: trusty env: - - JOB="3.6, doc" ENV_FILE="ci/deps/travis-36-doc.yaml" DOC=true + - JOB="3.6, doc" ENV_FILE="environment.yml" DOC=true before_install: - echo "before_install" diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 9238c27002337..597b5f92796c0 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -123,7 +123,7 @@ jobs: timeoutInMinutes: 90 steps: - script: | - echo '##vso[task.setvariable variable=ENV_FILE]ci/deps/travis-36-doc.yaml' + echo '##vso[task.setvariable variable=ENV_FILE]environment.yml' displayName: 'Setting environment variables' - script: | diff --git a/ci/deps/travis-36-doc.yaml b/ci/deps/travis-36-doc.yaml deleted file mode 100644 index 9419543e601e2..0000000000000 --- a/ci/deps/travis-36-doc.yaml +++ /dev/null @@ -1,46 +0,0 @@ -name: pandas-dev -channels: - - defaults - - conda-forge -dependencies: - - beautifulsoup4 - - bottleneck - - cython>=0.28.2 - - fastparquet>=0.2.1 - - gitpython - - html5lib - - hypothesis>=3.58.0 - - ipykernel - - ipython - - ipywidgets - - lxml - - matplotlib - - nbconvert>=5.4.1 - - nbformat - - nbsphinx - - notebook>=5.7.5 - - numexpr - - numpy - - numpydoc - - openpyxl - - pandoc - - pyarrow - - pyqt - - pytables - - python-dateutil - - python-snappy - - python=3.6.* - - pytz - - scipy - - seaborn - # some styling is broken with sphinx >= 2 (https://github.com/pandas-dev/pandas/issues/26058) - - sphinx=1.8.5 - - sqlalchemy - - statsmodels - - xarray - - xlrd - - xlsxwriter - - xlwt - # universal - - pytest>=4.0.2 - - pytest-xdist
Let's see if #26656 is now fixed. We shouldn't see the pyarrow warnings in either travis or azure builds. CC: @minggli
https://api.github.com/repos/pandas-dev/pandas/pulls/26829
2019-06-13T11:36:17Z
2019-06-18T11:38:29Z
2019-06-18T11:38:29Z
2019-06-18T11:38:29Z
DOC: Fixing more doc warnings
diff --git a/doc/source/reference/indexing.rst b/doc/source/reference/indexing.rst index 6d27e225b681e..8931caf394388 100644 --- a/doc/source/reference/indexing.rst +++ b/doc/source/reference/indexing.rst @@ -190,6 +190,9 @@ Numeric Index .. autosummary:: :toctree: api/ + RangeIndex.start + RangeIndex.stop + RangeIndex.step RangeIndex.from_range .. _api.categoricalindex: diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst index 92f62a812d23b..a061f696f4b30 100644 --- a/doc/source/reference/series.rst +++ b/doc/source/reference/series.rst @@ -473,6 +473,7 @@ strings and apply several methods to it. These can be accessed like Series.cat Series.dt Series.sparse + DataFrame.sparse Index.str .. _api.series.cat: diff --git a/doc/source/user_guide/sparse.rst b/doc/source/user_guide/sparse.rst index 09ed895a847ff..6ee11bd78fee9 100644 --- a/doc/source/user_guide/sparse.rst +++ b/doc/source/user_guide/sparse.rst @@ -77,6 +77,8 @@ A sparse array can be converted to a regular (dense) ndarray with :meth:`numpy.a np.asarray(sparr) +.. _sparse.dtype: + SparseDtype ----------- diff --git a/doc/source/whatsnew/v0.20.0.rst b/doc/source/whatsnew/v0.20.0.rst index 55b5f12d3ea70..8e6ad07ec8435 100644 --- a/doc/source/whatsnew/v0.20.0.rst +++ b/doc/source/whatsnew/v0.20.0.rst @@ -1564,7 +1564,7 @@ Removal of prior version deprecations/changes - The ``pandas.rpy`` module is removed. Similar functionality can be accessed through the `rpy2 <https://rpy2.readthedocs.io/>`__ project. - See the :ref:`R interfacing docs <https://pandas.pydata.org/pandas-docs/version/0.20/r_interface.html>`__ for more details. + See the `R interfacing docs <https://pandas.pydata.org/pandas-docs/version/0.20/r_interface.html>`__ for more details. - The ``pandas.io.ga`` module with a ``google-analytics`` interface is removed (:issue:`11308`). Similar functionality can be found in the `Google2Pandas <https://github.com/panalysis/Google2Pandas>`__ package. - ``pd.to_datetime`` and ``pd.to_timedelta`` have dropped the ``coerce`` parameter in favor of ``errors`` (:issue:`13602`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ef406ce3d6b02..d2d0525a0a0ff 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6284,8 +6284,8 @@ def _gotitem(self, index (default) or the column axis. This behavior is different from `numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`, `var`), where the default is to compute the aggregation of the flattened - array, e.g., ``numpy.mean(arr_2d)`` as opposed to ``numpy.mean(arr_2d, - axis=0)``. + array, e.g., ``numpy.mean(arr_2d)`` as opposed to + ``numpy.mean(arr_2d, axis=0)``. `agg` is an alias for `aggregate`. Use the alias. diff --git a/pandas/core/strings.py b/pandas/core/strings.py index bd756491abd2f..619b49438cdbb 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -2360,13 +2360,13 @@ def cat(self, others=None, sep=None, na_rep=None, join=None): See Also -------- - Series.str.split : Split strings around given separator/delimiter. - Series.str.rsplit : Splits string around given separator/delimiter, - starting from the right. - Series.str.join : Join lists contained as elements in the Series/Index - with passed delimiter. - str.split : Standard library version for split. - str.rsplit : Standard library version for rsplit. + Series.str.split : Split strings around given separator/delimiter. + Series.str.rsplit : Splits string around given separator/delimiter, + starting from the right. + Series.str.join : Join lists contained as elements in the Series/Index + with passed delimiter. + str.split : Standard library version for split. + str.rsplit : Standard library version for rsplit. Notes ----- @@ -2383,7 +2383,12 @@ def cat(self, others=None, sep=None, na_rep=None, join=None): Examples -------- >>> s = pd.Series(["this is a regular sentence", - "https://docs.python.org/3/tutorial/index.html", np.nan]) + ... "https://docs.python.org/3/tutorial/index.html", + ... np.nan]) + 0 this is a regular sentence + 1 https://docs.python.org/3/tutorial/index.html + 2 NaN + dtype: object In the default setting, the string is split by whitespace. @@ -2434,7 +2439,6 @@ def cat(self, others=None, sep=None, na_rep=None, join=None): 0 this is a regular 1 https://docs.python.org/3/tutorial/index.html None None None 2 NaN NaN NaN NaN \ - 4 0 sentence 1 None diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 73119671550a5..8e6331fe44e6b 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -456,7 +456,7 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, - If False returns ndarray of values. .. deprecated:: 0.25.0 - Use :meth:`.to_numpy` or :meth:`Timestamp.to_datetime64` + Use :meth:`Series.to_numpy` or :meth:`Timestamp.to_datetime64` instead to get an ndarray of values or numpy.datetime64, respectively. diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index 41dca3bfe7500..5e89b73c8754e 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -44,7 +44,7 @@ def to_timedelta(arg, unit='ns', box=True, errors='raise'): values of dtype timedelta64[ns]. .. deprecated:: 0.25.0 - Use :meth:`.to_numpy` or :meth:`Timedelta.to_timedelta64` + Use :meth:`Series.to_numpy` or :meth:`Timedelta.to_timedelta64` instead to get an ndarray of values or numpy.timedelta64, respectively.
- [X] xref #24173 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Another set of doc warning fixes. CC: @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/26826
2019-06-13T07:33:15Z
2019-06-13T08:17:21Z
2019-06-13T08:17:21Z
2019-06-13T08:17:21Z
BUG: fix tzaware dataframe transpose bug
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 18a3785867714..0d6e94cb1e3d0 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -775,6 +775,7 @@ Reshaping - Bug in :func:`DataFrame.sort_index` where an error is thrown when a multi-indexed ``DataFrame`` is sorted on all levels with the initial level sorted last (:issue:`26053`) - Bug in :meth:`Series.nlargest` treats ``True`` as smaller than ``False`` (:issue:`26154`) - Bug in :func:`DataFrame.pivot_table` with a :class:`IntervalIndex` as pivot index would raise ``TypeError`` (:issue:`25814`) +- Bug in :meth:`DataFrame.transpose` where transposing a DataFrame with a timezone-aware datetime column would incorrectly raise ``ValueError`` (:issue:`26825`) Sparse ^^^^^^ @@ -802,6 +803,7 @@ Other - Removed unused C functions from vendored UltraJSON implementation (:issue:`26198`) - Allow :class:`Index` and :class:`RangeIndex` to be passed to numpy ``min`` and ``max`` functions (:issue:`26125`) - Use actual class name in repr of empty objects of a ``Series`` subclass (:issue:`27001`). +- Bug in :class:`DataFrame` where passing an object array of timezone-aware `datetime` objects would incorrectly raise ``ValueError`` (:issue:`13287`) .. _whatsnew_0.250.contributors: diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 1b4e001620286..a10920b7a5afb 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -21,10 +21,12 @@ from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, Substitution -from pandas.core.dtypes.cast import maybe_downcast_to_dtype +from pandas.core.dtypes.cast import ( + maybe_convert_objects, maybe_downcast_to_dtype) from pandas.core.dtypes.common import ( ensure_int64, ensure_platform_int, is_bool, is_datetimelike, - is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_scalar) + is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype, + is_scalar) from pandas.core.dtypes.missing import isna, notna from pandas._typing import FrameOrSeries @@ -334,7 +336,6 @@ def _decide_output_index(self, output, labels): def _wrap_applied_output(self, keys, values, not_indexed_same=False): from pandas.core.index import _all_indexes_same - from pandas.core.tools.numeric import to_numeric if len(keys) == 0: return DataFrame(index=keys) @@ -406,7 +407,6 @@ def first_not_none(values): # provide a reduction (Frame -> Series) if groups are # unique if self.squeeze: - # assign the name to this series if singular_series: values[0].name = keys[0] @@ -481,14 +481,7 @@ def first_not_none(values): # as we are stacking can easily have object dtypes here so = self._selected_obj if so.ndim == 2 and so.dtypes.apply(is_datetimelike).any(): - result = result.apply( - lambda x: to_numeric(x, errors='ignore')) - date_cols = self._selected_obj.select_dtypes( - include=['datetime', 'timedelta']).columns - date_cols = date_cols.intersection(result.columns) - result[date_cols] = (result[date_cols] - ._convert(datetime=True, - coerce=True)) + result = _recast_datetimelike_result(result) else: result = result._convert(datetime=True) @@ -1710,3 +1703,35 @@ def _normalize_keyword_aggregation(kwargs): order.append((column, com.get_callable_name(aggfunc) or aggfunc)) return aggspec, columns, order + + +def _recast_datetimelike_result(result: DataFrame) -> DataFrame: + """ + If we have date/time like in the original, then coerce dates + as we are stacking can easily have object dtypes here. + + Parameters + ---------- + result : DataFrame + + Returns + ------- + DataFrame + + Notes + ----- + - Assumes Groupby._selected_obj has ndim==2 and at least one + datetimelike column + """ + result = result.copy() + + obj_cols = [idx for idx in range(len(result.columns)) + if is_object_dtype(result.dtypes[idx])] + + # See GH#26285 + for n in obj_cols: + converted = maybe_convert_objects(result.iloc[:, n].values, + convert_numeric=False) + + result.iloc[:, n] = converted + return result diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index d766d7f06d34a..ecdf8a1f77b94 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -159,9 +159,28 @@ def init_ndarray(values, index, columns, dtype=None, copy=False): # on the entire block; this is to convert if we have datetimelike's # embedded in an object type if dtype is None and is_object_dtype(values): - values = maybe_infer_to_datetimelike(values) - return create_block_manager_from_blocks([values], [columns, index]) + if values.ndim == 2 and values.shape[0] != 1: + # transpose and separate blocks + + dvals_list = [maybe_infer_to_datetimelike(row) for row in values] + for n in range(len(dvals_list)): + if isinstance(dvals_list[n], np.ndarray): + dvals_list[n] = dvals_list[n].reshape(1, -1) + + from pandas.core.internals.blocks import make_block + + # TODO: What about re-joining object columns? + block_values = [make_block(dvals_list[n], placement=[n]) + for n in range(len(dvals_list))] + + else: + datelike_vals = maybe_infer_to_datetimelike(values) + block_values = [datelike_vals] + else: + block_values = [values] + + return create_block_manager_from_blocks(block_values, [columns, index]) def init_dict(data, index, columns, dtype=None): diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 64b4e162483f1..b1091d38c10d0 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -448,8 +448,7 @@ def test_dti_cmp_null_scalar_inequality(self, tz_naive_fixture, other, # GH#19301 tz = tz_naive_fixture dti = pd.date_range('2016-01-01', periods=2, tz=tz) - # FIXME: ValueError with transpose - dtarr = tm.box_expected(dti, box_with_array, transpose=False) + dtarr = tm.box_expected(dti, box_with_array) msg = 'Invalid comparison between' with pytest.raises(TypeError, match=msg): dtarr < other @@ -597,49 +596,63 @@ def test_dti_cmp_nat_behaves_like_float_cmp_nan(self): @pytest.mark.parametrize('op', [operator.eq, operator.ne, operator.gt, operator.ge, operator.lt, operator.le]) - def test_comparison_tzawareness_compat(self, op, box_with_array): + def test_comparison_tzawareness_compat(self, op, box_df_fail): # GH#18162 + box = box_df_fail + dr = pd.date_range('2016-01-01', periods=6) dz = dr.tz_localize('US/Pacific') - # FIXME: ValueError with transpose - dr = tm.box_expected(dr, box_with_array, transpose=False) - dz = tm.box_expected(dz, box_with_array, transpose=False) + dr = tm.box_expected(dr, box) + dz = tm.box_expected(dz, box) msg = 'Cannot compare tz-naive and tz-aware' with pytest.raises(TypeError, match=msg): op(dr, dz) - if box_with_array is not pd.DataFrame: - # DataFrame op is invalid until transpose bug is fixed - with pytest.raises(TypeError, match=msg): - op(dr, list(dz)) - with pytest.raises(TypeError, match=msg): - op(dr, np.array(list(dz), dtype=object)) + # FIXME: DataFrame case fails to raise for == and !=, wrong + # message for inequalities + with pytest.raises(TypeError, match=msg): + op(dr, list(dz)) + with pytest.raises(TypeError, match=msg): + op(dr, np.array(list(dz), dtype=object)) with pytest.raises(TypeError, match=msg): op(dz, dr) - if box_with_array is not pd.DataFrame: - # DataFrame op is invalid until transpose bug is fixed - with pytest.raises(TypeError, match=msg): - op(dz, list(dr)) - with pytest.raises(TypeError, match=msg): - op(dz, np.array(list(dr), dtype=object)) + + # FIXME: DataFrame case fails to raise for == and !=, wrong + # message for inequalities + with pytest.raises(TypeError, match=msg): + op(dz, list(dr)) + with pytest.raises(TypeError, match=msg): + op(dz, np.array(list(dr), dtype=object)) # Check that there isn't a problem aware-aware and naive-naive do not # raise assert_all(dr == dr) assert_all(dz == dz) - if box_with_array is not pd.DataFrame: - # DataFrame doesn't align the lists correctly unless we transpose, - # which we cannot do at the moment - assert (dr == list(dr)).all() - assert (dz == list(dz)).all() + + # FIXME: DataFrame case fails to raise for == and !=, wrong + # message for inequalities + assert (dr == list(dr)).all() + assert (dz == list(dz)).all() + + @pytest.mark.parametrize('op', [operator.eq, operator.ne, + operator.gt, operator.ge, + operator.lt, operator.le]) + def test_comparison_tzawareness_compat_scalars(self, op, box_with_array): + # GH#18162 + dr = pd.date_range('2016-01-01', periods=6) + dz = dr.tz_localize('US/Pacific') + + dr = tm.box_expected(dr, box_with_array) + dz = tm.box_expected(dz, box_with_array) # Check comparisons against scalar Timestamps ts = pd.Timestamp('2000-03-14 01:59') ts_tz = pd.Timestamp('2000-03-14 01:59', tz='Europe/Amsterdam') assert_all(dr > ts) + msg = 'Cannot compare tz-naive and tz-aware' with pytest.raises(TypeError, match=msg): op(dr, ts_tz) @@ -662,8 +675,7 @@ def test_scalar_comparison_tzawareness(self, op, other, tz_aware_fixture, tz = tz_aware_fixture dti = pd.date_range('2016-01-01', periods=2, tz=tz) - # FIXME: ValueError with transpose - dtarr = tm.box_expected(dti, box_with_array, transpose=False) + dtarr = tm.box_expected(dti, box_with_array) msg = 'Cannot compare tz-naive and tz-aware' with pytest.raises(TypeError, match=msg): op(dtarr, other) @@ -725,17 +737,16 @@ def test_dt64arr_cmp_scalar_invalid(self, other, tz_naive_fixture, xbox = box_with_array if box_with_array is not pd.Index else np.ndarray rng = date_range('1/1/2000', periods=10, tz=tz) - # FIXME: ValueError with transpose - rng = tm.box_expected(rng, box_with_array, transpose=False) + rng = tm.box_expected(rng, box_with_array) result = rng == other expected = np.array([False] * 10) - expected = tm.box_expected(expected, xbox, transpose=False) + expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected) result = rng != other expected = np.array([True] * 10) - expected = tm.box_expected(expected, xbox, transpose=False) + expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected) msg = 'Invalid comparison between' with pytest.raises(TypeError, match=msg): @@ -826,9 +837,8 @@ def test_dt64arr_add_timedeltalike_scalar(self, tz_naive_fixture, expected = pd.date_range('2000-01-01 02:00', '2000-02-01 02:00', tz=tz) - # FIXME: calling with transpose=True raises ValueError - rng = tm.box_expected(rng, box_with_array, transpose=False) - expected = tm.box_expected(expected, box_with_array, transpose=False) + rng = tm.box_expected(rng, box_with_array) + expected = tm.box_expected(expected, box_with_array) result = rng + two_hours tm.assert_equal(result, expected) @@ -841,9 +851,8 @@ def test_dt64arr_iadd_timedeltalike_scalar(self, tz_naive_fixture, expected = pd.date_range('2000-01-01 02:00', '2000-02-01 02:00', tz=tz) - # FIXME: calling with transpose=True raises ValueError - rng = tm.box_expected(rng, box_with_array, transpose=False) - expected = tm.box_expected(expected, box_with_array, transpose=False) + rng = tm.box_expected(rng, box_with_array) + expected = tm.box_expected(expected, box_with_array) rng += two_hours tm.assert_equal(rng, expected) @@ -856,9 +865,8 @@ def test_dt64arr_sub_timedeltalike_scalar(self, tz_naive_fixture, expected = pd.date_range('1999-12-31 22:00', '2000-01-31 22:00', tz=tz) - # FIXME: calling with transpose=True raises ValueError - rng = tm.box_expected(rng, box_with_array, transpose=False) - expected = tm.box_expected(expected, box_with_array, transpose=False) + rng = tm.box_expected(rng, box_with_array) + expected = tm.box_expected(expected, box_with_array) result = rng - two_hours tm.assert_equal(result, expected) @@ -871,9 +879,8 @@ def test_dt64arr_isub_timedeltalike_scalar(self, tz_naive_fixture, expected = pd.date_range('1999-12-31 22:00', '2000-01-31 22:00', tz=tz) - # FIXME: calling with transpose=True raises ValueError - rng = tm.box_expected(rng, box_with_array, transpose=False) - expected = tm.box_expected(expected, box_with_array, transpose=False) + rng = tm.box_expected(rng, box_with_array) + expected = tm.box_expected(expected, box_with_array) rng -= two_hours tm.assert_equal(rng, expected) @@ -928,9 +935,6 @@ def test_dt64arr_add_sub_td64_nat(self, box_with_array, tz_naive_fixture): def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array): - if box_with_array is pd.DataFrame: - pytest.xfail("FIXME: ValueError with transpose; " - "alignment error without") tz = tz_naive_fixture dti = pd.date_range('2016-01-01', periods=3, tz=tz) @@ -952,7 +956,7 @@ def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, result = dtarr - tdarr tm.assert_equal(result, expected) - msg = 'cannot subtract' + msg = 'cannot subtract|bad operand type for unary -' with pytest.raises(TypeError, match=msg): tdarr - dtarr @@ -997,13 +1001,11 @@ def test_dt64arr_sub_timestamp(self, box_with_array): tz='US/Eastern') ts = ser[0] - # FIXME: transpose raises ValueError - ser = tm.box_expected(ser, box_with_array, transpose=False) + ser = tm.box_expected(ser, box_with_array) delta_series = pd.Series([np.timedelta64(0, 'D'), np.timedelta64(1, 'D')]) - expected = tm.box_expected(delta_series, box_with_array, - transpose=False) + expected = tm.box_expected(delta_series, box_with_array) tm.assert_equal(ser - ts, expected) tm.assert_equal(ts - ser, -expected) @@ -1011,20 +1013,19 @@ def test_dt64arr_sub_timestamp(self, box_with_array): def test_dt64arr_sub_NaT(self, box_with_array): # GH#18808 dti = pd.DatetimeIndex([pd.NaT, pd.Timestamp('19900315')]) - ser = tm.box_expected(dti, box_with_array, transpose=False) + ser = tm.box_expected(dti, box_with_array) result = ser - pd.NaT expected = pd.Series([pd.NaT, pd.NaT], dtype='timedelta64[ns]') - # FIXME: raises ValueError with transpose - expected = tm.box_expected(expected, box_with_array, transpose=False) + expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected) dti_tz = dti.tz_localize('Asia/Tokyo') - ser_tz = tm.box_expected(dti_tz, box_with_array, transpose=False) + ser_tz = tm.box_expected(dti_tz, box_with_array) result = ser_tz - pd.NaT expected = pd.Series([pd.NaT, pd.NaT], dtype='timedelta64[ns]') - expected = tm.box_expected(expected, box_with_array, transpose=False) + expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected) # ------------------------------------------------------------- @@ -1044,16 +1045,13 @@ def test_dt64arr_naive_sub_dt64ndarray(self, box_with_array): def test_dt64arr_aware_sub_dt64ndarray_raises(self, tz_aware_fixture, box_with_array): - if box_with_array is pd.DataFrame: - pytest.xfail("FIXME: ValueError with transpose; " - "alignment error without") tz = tz_aware_fixture dti = pd.date_range('2016-01-01', periods=3, tz=tz) dt64vals = dti.values dtarr = tm.box_expected(dti, box_with_array) - msg = 'DatetimeArray subtraction must have the same timezones or' + msg = 'subtraction must have the same timezones or' with pytest.raises(TypeError, match=msg): dtarr - dt64vals with pytest.raises(TypeError, match=msg): @@ -1064,9 +1062,6 @@ def test_dt64arr_aware_sub_dt64ndarray_raises(self, tz_aware_fixture, def test_dt64arr_add_dt64ndarray_raises(self, tz_naive_fixture, box_with_array): - if box_with_array is pd.DataFrame: - pytest.xfail("FIXME: ValueError with transpose; " - "alignment error without") tz = tz_naive_fixture dti = pd.date_range('2016-01-01', periods=3, tz=tz) @@ -1214,9 +1209,8 @@ def test_dti_add_tick_tzaware(self, tz_aware_fixture, box_with_array): expected = DatetimeIndex(['2010-11-01 05:00', '2010-11-01 06:00', '2010-11-01 07:00'], freq='H', tz=tz) - # FIXME: these raise ValueError with transpose=True - dates = tm.box_expected(dates, box_with_array, transpose=False) - expected = tm.box_expected(expected, box_with_array, transpose=False) + dates = tm.box_expected(dates, box_with_array) + expected = tm.box_expected(expected, box_with_array) # TODO: parametrize over the scalar being added? radd? sub? offset = dates + pd.offsets.Hour(5) @@ -1369,26 +1363,25 @@ def test_dt64arr_add_sub_DateOffset(self, box_with_array): s = DatetimeIndex([Timestamp('2000-01-15 00:15:00', tz='US/Central'), Timestamp('2000-02-15', tz='US/Central')], name='a') - # FIXME: ValueError with tzaware DataFrame transpose - s = tm.box_expected(s, box_with_array, transpose=False) + s = tm.box_expected(s, box_with_array) result = s + pd.offsets.Day() result2 = pd.offsets.Day() + s exp = DatetimeIndex([Timestamp('2000-01-16 00:15:00', tz='US/Central'), Timestamp('2000-02-16', tz='US/Central')], name='a') - exp = tm.box_expected(exp, box_with_array, transpose=False) + exp = tm.box_expected(exp, box_with_array) tm.assert_equal(result, exp) tm.assert_equal(result2, exp) s = DatetimeIndex([Timestamp('2000-01-15 00:15:00', tz='US/Central'), Timestamp('2000-02-15', tz='US/Central')], name='a') - s = tm.box_expected(s, box_with_array, transpose=False) + s = tm.box_expected(s, box_with_array) result = s + pd.offsets.MonthEnd() result2 = pd.offsets.MonthEnd() + s exp = DatetimeIndex([Timestamp('2000-01-31 00:15:00', tz='US/Central'), Timestamp('2000-02-29', tz='US/Central')], name='a') - exp = tm.box_expected(exp, box_with_array, transpose=False) + exp = tm.box_expected(exp, box_with_array) tm.assert_equal(result, exp) tm.assert_equal(result2, exp) @@ -1425,9 +1418,6 @@ def test_dt64arr_add_mixed_offset_array(self, box_with_array): def test_dt64arr_add_sub_offset_ndarray(self, tz_naive_fixture, box_with_array): # GH#18849 - if box_with_array is pd.DataFrame: - pytest.xfail("FIXME: ValueError with transpose; " - "alignment error without") tz = tz_naive_fixture dti = pd.date_range('2017-01-01', periods=2, tz=tz) diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 22b5fd452d661..0ae325cfce787 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -869,10 +869,8 @@ def test_td64arr_add_timestamp(self, box_with_array, tz_naive_fixture): idx = TimedeltaIndex(['1 day', '2 day']) expected = DatetimeIndex(['2011-01-02', '2011-01-03'], tz=tz) - # FIXME: fails with transpose=True because of tz-aware DataFrame - # transpose bug - idx = tm.box_expected(idx, box_with_array, transpose=False) - expected = tm.box_expected(expected, box_with_array, transpose=False) + idx = tm.box_expected(idx, box_with_array) + expected = tm.box_expected(expected, box_with_array) result = idx + other tm.assert_equal(result, expected) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index c6508072cb8c7..434ee2f8bf0af 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2400,3 +2400,32 @@ def test_nested_dict_construction(self): index=pd.Index([2001, 2002, 2003]) ) tm.assert_frame_equal(result, expected) + + def test_from_tzaware_object_array(self): + # GH#26825 2D object array of tzaware timestamps should not raise + dti = pd.date_range('2016-04-05 04:30', periods=3, tz='UTC') + data = dti._data.astype(object).reshape(1, -1) + df = pd.DataFrame(data) + assert df.shape == (1, 3) + assert (df.dtypes == dti.dtype).all() + assert (df == dti).all().all() + + def test_from_tzaware_mixed_object_array(self): + # GH#26825 + arr = np.array([ + [Timestamp('2013-01-01 00:00:00'), + Timestamp('2013-01-02 00:00:00'), + Timestamp('2013-01-03 00:00:00')], + [Timestamp('2013-01-01 00:00:00-0500', tz='US/Eastern'), + pd.NaT, + Timestamp('2013-01-03 00:00:00-0500', tz='US/Eastern')], + [Timestamp('2013-01-01 00:00:00+0100', tz='CET'), + pd.NaT, + Timestamp('2013-01-03 00:00:00+0100', tz='CET')]], + dtype=object).T + res = DataFrame(arr, columns=['A', 'B', 'C']) + + expected_dtypes = ['datetime64[ns]', + 'datetime64[ns, US/Eastern]', + 'datetime64[ns, CET]'] + assert (res.dtypes == expected_dtypes).all() diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 96cf70483d4e7..7ed601e4f7046 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -978,9 +978,11 @@ def test_astype(self): Timestamp('2013-01-03 00:00:00+0100', tz='CET')]], dtype=object).T + expected = DataFrame(expected, + index=self.tzframe.index, + columns=self.tzframe.columns, dtype=object) result = self.tzframe.astype(object) - assert_frame_equal(result, DataFrame( - expected, index=self.tzframe.index, columns=self.tzframe.columns)) + assert_frame_equal(result, expected) result = self.tzframe.astype('datetime64[ns]') expected = DataFrame({'A': date_range('20130101', periods=3), diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index f1c8445bf98e0..1e932879e9ad0 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -793,3 +793,44 @@ def test_no_warning(self, all_arithmetic_operators): b = df['B'] with tm.assert_produces_warning(None): getattr(df, all_arithmetic_operators)(b, 0) + + +class TestTranspose: + def test_transpose_tzaware_1col_single_tz(self): + # GH#26825 + dti = pd.date_range('2016-04-05 04:30', periods=3, tz='UTC') + + df = pd.DataFrame(dti) + assert (df.dtypes == dti.dtype).all() + res = df.T + assert (res.dtypes == dti.dtype).all() + + def test_transpose_tzaware_2col_single_tz(self): + # GH#26825 + dti = pd.date_range('2016-04-05 04:30', periods=3, tz='UTC') + + df3 = pd.DataFrame({'A': dti, 'B': dti}) + assert (df3.dtypes == dti.dtype).all() + res3 = df3.T + assert (res3.dtypes == dti.dtype).all() + + def test_transpose_tzaware_2col_mixed_tz(self): + # GH#26825 + dti = pd.date_range('2016-04-05 04:30', periods=3, tz='UTC') + dti2 = dti.tz_convert('US/Pacific') + + df4 = pd.DataFrame({'A': dti, 'B': dti2}) + assert (df4.dtypes == [dti.dtype, dti2.dtype]).all() + assert (df4.T.dtypes == object).all() + tm.assert_frame_equal(df4.T.T, df4) + + def test_transpose_object_to_tzaware_mixed_tz(self): + # GH#26825 + dti = pd.date_range('2016-04-05 04:30', periods=3, tz='UTC') + dti2 = dti.tz_convert('US/Pacific') + + # mixed all-tzaware dtypes + df2 = pd.DataFrame([dti, dti2]) + assert (df2.dtypes == object).all() + res2 = df2.T + assert (res2.dtypes == [dti.dtype, dti2.dtype]).all() diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 3d9bfcd126377..14f27f0c4c7d8 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -963,12 +963,14 @@ def test_count(): df['9th'] = df['9th'].astype('category') - for key in '1st', '2nd', ['1st', '2nd']: + for key in ['1st', '2nd', ['1st', '2nd']]: left = df.groupby(key).count() right = df.groupby(key).apply(DataFrame.count).drop(key, axis=1) tm.assert_frame_equal(left, right) - # GH5610 + +def test_count_non_nulls(): + # GH#5610 # count counts non-nulls df = pd.DataFrame([[1, 2, 'foo'], [1, np.nan, 'bar'], diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 3da3ab22b643b..dcd0d3938c6a5 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -129,12 +129,14 @@ def func(dataf): result = df.groupby('X', squeeze=False).count() assert isinstance(result, DataFrame) + +def test_inconsistent_return_type(): # GH5592 # inconsistent return type df = DataFrame(dict(A=['Tiger', 'Tiger', 'Tiger', 'Lamb', 'Lamb', - 'Pony', 'Pony'], B=Series( - np.arange(7), dtype='int64'), C=date_range( - '20130101', periods=7))) + 'Pony', 'Pony'], + B=Series(np.arange(7), dtype='int64'), + C=date_range('20130101', periods=7))) def f(grp): return grp.iloc[0]
This allows us to get rid of a bunch of xfails and FIXMEs in arithmetic tests. Changes in groupby are the most likely to need attention; this is not an area of the code I know well. Not sure if TestTranspose belongs somewhere else. Suggestions welcome. Split a couple of too-widely-scoped groupby tests. Will follow-up with issues this closes, whatsnew entry, and GH references added to tests. xref #23988 - [x] closes #13287 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/26825
2019-06-13T04:10:08Z
2019-06-27T20:39:25Z
2019-06-27T20:39:25Z
2019-06-27T20:40:20Z
Remove annotations to make CI happy
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index a3c0e6691dd22..f36ff5c2b8abd 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -1,7 +1,6 @@ import distutils.version import importlib import types -from typing import Optional import warnings # Update install.rst when updating versions! @@ -53,7 +52,7 @@ def import_optional_dependency( extra: str = "", raise_on_missing: bool = True, on_version: str = "raise", -) -> Optional[types.ModuleType]: +): """ Import an optional dependency. diff --git a/pandas/io/gcs.py b/pandas/io/gcs.py index 310a1f9f398e9..862ccbb291c01 100644 --- a/pandas/io/gcs.py +++ b/pandas/io/gcs.py @@ -15,5 +15,5 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None, fs = gcsfs.GCSFileSystem() filepath_or_buffer = fs.open( - filepath_or_buffer, mode) # type: gcsfs.GCSFile + filepath_or_buffer, mode) return filepath_or_buffer, None, compression, True diff --git a/pandas/io/s3.py b/pandas/io/s3.py index 61fd984789f78..d784e8d473aac 100644 --- a/pandas/io/s3.py +++ b/pandas/io/s3.py @@ -34,5 +34,5 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None, # for that bucket. fs = s3fs.S3FileSystem(anon=True) filepath_or_buffer = fs.open( - _strip_schema(filepath_or_buffer), mode) # type: s3fs.S3File + _strip_schema(filepath_or_buffer), mode) return filepath_or_buffer, None, compression, True
I must have been a little quick in merging #26802 as it looks like this is causing mypy failures in CI. Most of these are pretty niche and I think a result of import machinery. Will try to dive deeper later but this should get things green for now
https://api.github.com/repos/pandas-dev/pandas/pulls/26820
2019-06-12T21:12:05Z
2019-06-13T00:00:11Z
2019-06-13T00:00:11Z
2019-06-13T00:00:15Z
CLN: remove util._decorators.make_signature and make related changes
diff --git a/pandas/_typing.py b/pandas/_typing.py index a2bb168c1e2da..0044b269eb7b5 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -9,7 +9,7 @@ from pandas.core.dtypes.dtypes import ExtensionDtype from pandas.core.dtypes.generic import ( - ABCExtensionArray, ABCIndexClass, ABCSeries, ABCSparseSeries) + ABCDataFrame, ABCExtensionArray, ABCIndexClass, ABCSeries, ABCSparseSeries) AnyArrayLike = TypeVar('AnyArrayLike', ABCExtensionArray, @@ -22,3 +22,5 @@ Timedelta) Dtype = Union[str, np.dtype, ExtensionDtype] FilePathOrBuffer = Union[str, Path, IO[AnyStr]] + +FrameOrSeries = TypeVar('FrameOrSeries', ABCSeries, ABCDataFrame) diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index 823a4155bc2b8..cffe0e589c6bc 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -3,11 +3,6 @@ hold the whitelist of methods that are exposed on the SeriesGroupBy and the DataFrameGroupBy objects. """ - -import types - -from pandas.util._decorators import make_signature - from pandas.core.dtypes.common import is_list_like, is_scalar @@ -91,67 +86,3 @@ def _gotitem(self, key, ndim, subset=None): cython_cast_blacklist = frozenset(['rank', 'count', 'size', 'idxmin', 'idxmax']) - - -def whitelist_method_generator(base, klass, whitelist): - """ - Yields all GroupBy member defs for DataFrame/Series names in whitelist. - - Parameters - ---------- - base : class - base class - klass : class - class where members are defined. - Should be Series or DataFrame - whitelist : list - list of names of klass methods to be constructed - - Returns - ------- - The generator yields a sequence of strings, each suitable for exec'ing, - that define implementations of the named methods for DataFrameGroupBy - or SeriesGroupBy. - - Since we don't want to override methods explicitly defined in the - base class, any such name is skipped. - """ - - method_wrapper_template = \ - """def %(name)s(%(sig)s) : - \""" - %(doc)s - \""" - f = %(self)s.__getattr__('%(name)s') - return f(%(args)s)""" - property_wrapper_template = \ - """@property -def %(name)s(self) : - \"""%(doc)s\""" - return self.__getattr__('%(name)s')""" - - for name in whitelist: - # don't override anything that was explicitly defined - # in the base class - if hasattr(base, name): - continue - # ugly, but we need the name string itself in the method. - f = getattr(klass, name) - doc = f.__doc__ - doc = doc if type(doc) == str else '' - if isinstance(f, types.MethodType): - wrapper_template = method_wrapper_template - decl, args = make_signature(f) - # pass args by name to f because otherwise - # GroupBy._make_wrapper won't know whether - # we passed in an axis parameter. - args_by_name = ['{0}={0}'.format(arg) for arg in args[1:]] - params = {'name': name, - 'doc': doc, - 'sig': ','.join(decl), - 'self': args[0], - 'args': ','.join(args_by_name)} - else: - wrapper_template = property_wrapper_template - params = {'name': name, 'doc': doc} - yield wrapper_template % params diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 57d14cb4c15d7..35ffa552913ae 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -11,7 +11,7 @@ from functools import partial from textwrap import dedent import typing -from typing import Any, Callable, List, Union +from typing import Any, Callable, FrozenSet, Iterator, List, Type, Union import warnings import numpy as np @@ -27,6 +27,7 @@ is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_scalar) from pandas.core.dtypes.missing import isna, notna +from pandas._typing import FrameOrSeries import pandas.core.algorithms as algorithms from pandas.core.base import DataError, SpecificationError import pandas.core.common as com @@ -48,6 +49,51 @@ AggScalar = Union[str, Callable[..., Any]] +def whitelist_method_generator(base_class: Type[GroupBy], + klass: Type[FrameOrSeries], + whitelist: FrozenSet[str], + ) -> Iterator[str]: + """ + Yields all GroupBy member defs for DataFrame/Series names in whitelist. + + Parameters + ---------- + base_class : Groupby class + base class + klass : DataFrame or Series class + class where members are defined. + whitelist : frozenset + Set of names of klass methods to be constructed + + Returns + ------- + The generator yields a sequence of strings, each suitable for exec'ing, + that define implementations of the named methods for DataFrameGroupBy + or SeriesGroupBy. + + Since we don't want to override methods explicitly defined in the + base class, any such name is skipped. + """ + property_wrapper_template = \ + """@property +def %(name)s(self) : + \"""%(doc)s\""" + return self.__getattr__('%(name)s')""" + + for name in whitelist: + # don't override anything that was explicitly defined + # in the base class + if hasattr(base_class, name): + continue + # ugly, but we need the name string itself in the method. + f = getattr(klass, name) + doc = f.__doc__ + doc = doc if type(doc) == str else '' + wrapper_template = property_wrapper_template + params = {'name': name, 'doc': doc} + yield wrapper_template % params + + class NDFrameGroupBy(GroupBy): def _iterate_slices(self): @@ -685,7 +731,7 @@ class SeriesGroupBy(GroupBy): # Make class defs of attributes on SeriesGroupBy whitelist _apply_whitelist = base.series_apply_whitelist - for _def_str in base.whitelist_method_generator( + for _def_str in whitelist_method_generator( GroupBy, Series, _apply_whitelist): exec(_def_str) @@ -1289,7 +1335,7 @@ class DataFrameGroupBy(NDFrameGroupBy): # # Make class defs of attributes on DataFrameGroupBy whitelist. - for _def_str in base.whitelist_method_generator( + for _def_str in whitelist_method_generator( GroupBy, DataFrame, _apply_whitelist): exec(_def_str) diff --git a/pandas/tests/util/test_util.py b/pandas/tests/util/test_util.py index a3b82ecc12a1b..88ce48245dc70 100644 --- a/pandas/tests/util/test_util.py +++ b/pandas/tests/util/test_util.py @@ -5,8 +5,6 @@ import pandas.compat as compat from pandas.compat import raise_with_traceback -from pandas.util._decorators import deprecate_kwarg, make_signature -from pandas.util._validators import validate_kwargs import pandas.util.testing as tm @@ -37,22 +35,6 @@ def test_numpy_err_state_is_default(): assert np.geterr() == expected -@pytest.mark.parametrize("func,expected", [ - # Case where the func does not have default kwargs. - (validate_kwargs, (["fname", "kwargs", "compat_args"], - ["fname", "kwargs", "compat_args"])), - - # Case where the func does have default kwargs. - (deprecate_kwarg, (["old_arg_name", "new_arg_name", - "mapping=None", "stacklevel=2"], - ["old_arg_name", "new_arg_name", - "mapping", "stacklevel"])) -]) -def test_make_signature(func, expected): - # see gh-17608 - assert make_signature(func) == expected - - def test_raise_with_traceback(): with pytest.raises(LookupError, match="error_text"): try: diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index ac23fa5d7b0ad..cdda02324ba06 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -319,33 +319,3 @@ def indent(text, indents=1): return '' jointext = ''.join(['\n'] + [' '] * indents) return jointext.join(text.split('\n')) - - -def make_signature(func): - """ - Returns a tuple containing the paramenter list with defaults - and parameter list. - - Examples - -------- - >>> def f(a, b, c=2): - >>> return a * b * c - >>> print(make_signature(f)) - (['a', 'b', 'c=2'], ['a', 'b', 'c']) - """ - - spec = inspect.getfullargspec(func) - if spec.defaults is None: - n_wo_defaults = len(spec.args) - defaults = ('',) * n_wo_defaults - else: - n_wo_defaults = len(spec.args) - len(spec.defaults) - defaults = ('',) * n_wo_defaults + tuple(spec.defaults) - args = [] - for var, default in zip(spec.args, defaults): - args.append(var if default == '' else var + '=' + repr(default)) - if spec.varargs: - args.append('*' + spec.varargs) - if spec.varkw: - args.append('**' + spec.varkw) - return args, spec.args
``util._decorators.make_signature`` is only used in ``core.groupby.base.whitelist_method_generator``. However, in that function it is only used inside an if statement, that is conditional upon an attribute being a method. That however can not happen, as the function parameter only takes classes as an input, so that if-statement is never true and its content never executed. The net effect is that a nice chunk of code can just be removed, which is nice. In the future, we should just use jus use ``inspect.signature`` or ``inspect.getfullargspecs`` for signature inspection.
https://api.github.com/repos/pandas-dev/pandas/pulls/26819
2019-06-12T20:56:14Z
2019-06-14T14:22:42Z
2019-06-14T14:22:42Z
2019-06-14T15:54:01Z
COMPAT: reading generic PyTables Table format fails with sub-selection
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 77b689569d57f..467cb5a40213c 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -699,6 +699,7 @@ I/O - Bug in :func:`read_csv` not properly interpreting the UTF8 encoded filenames on Windows on Python 3.6+ (:issue:`15086`) - Improved performance in :meth:`pandas.read_stata` and :class:`pandas.io.stata.StataReader` when converting columns that have missing values (:issue:`25772`) - Bug in :meth:`DataFrame.to_html` where header numbers would ignore display options when rounding (:issue:`17280`) +- Bug in :func:`read_hdf` where reading a table from an HDF5 file written directly with PyTables fails with a ``ValueError`` when using a sub-selection via the ``start`` or ``stop`` arguments (:issue:`11188`) - Bug in :func:`read_hdf` not properly closing store after a ``KeyError`` is raised (:issue:`25766`) - Bug in ``read_csv`` which would not raise ``ValueError`` if a column index in ``usecols`` was out of bounds (:issue:`25623`) - Improved the explanation for the failure when value labels are repeated in Stata dta files and suggested work-arounds (:issue:`25772`) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 79d6d8563a162..17d580bae5cf1 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1624,7 +1624,8 @@ def infer(self, handler): new_self.read_metadata(handler) return new_self - def convert(self, values, nan_rep, encoding, errors): + def convert(self, values, nan_rep, encoding, errors, start=None, + stop=None): """ set the values from this selection: take = take ownership """ # values is a recarray @@ -1813,10 +1814,29 @@ class GenericIndexCol(IndexCol): def is_indexed(self): return False - def convert(self, values, nan_rep, encoding, errors): - """ set the values from this selection: take = take ownership """ + def convert(self, values, nan_rep, encoding, errors, start=None, + stop=None): + """ set the values from this selection: take = take ownership + + Parameters + ---------- + + values : np.ndarray + nan_rep : str + encoding : str + errors : str + start : int, optional + Table row number: the start of the sub-selection. + stop : int, optional + Table row number: the end of the sub-selection. Values larger than + the underlying table's row count are normalized to that. + """ + + start = start if start is not None else 0 + stop = (min(stop, self.table.nrows) + if stop is not None else self.table.nrows) + self.values = Int64Index(np.arange(stop - start)) - self.values = Int64Index(np.arange(self.table.nrows)) return self def get_attr(self): @@ -2159,7 +2179,8 @@ def validate_attr(self, append): raise ValueError("appended items dtype do not match existing " "items dtype in table!") - def convert(self, values, nan_rep, encoding, errors): + def convert(self, values, nan_rep, encoding, errors, start=None, + stop=None): """set the data from this selection (and convert to the correct dtype if we can) """ @@ -3431,8 +3452,11 @@ def read_axes(self, where, **kwargs): # convert the data for a in self.axes: a.set_info(self.info) + # `kwargs` may contain `start` and `stop` arguments if passed to + # `store.select()`. If set they determine the index size. a.convert(values, nan_rep=self.nan_rep, encoding=self.encoding, - errors=self.errors) + errors=self.errors, start=kwargs.get('start'), + stop=kwargs.get('stop')) return True diff --git a/pandas/tests/io/pytables/test_compat.py b/pandas/tests/io/pytables/test_compat.py new file mode 100644 index 0000000000000..d74e1218ebdb0 --- /dev/null +++ b/pandas/tests/io/pytables/test_compat.py @@ -0,0 +1,76 @@ +import pytest + +import pandas as pd +from pandas.tests.io.test_pytables import ensure_clean_path +from pandas.util.testing import assert_frame_equal + +tables = pytest.importorskip('tables') + + +@pytest.fixture +def pytables_hdf5_file(): + """Use PyTables to create a simple HDF5 file.""" + + table_schema = { + 'c0': tables.Time64Col(pos=0), + 'c1': tables.StringCol(5, pos=1), + 'c2': tables.Int64Col(pos=2), + } + + t0 = 1561105000.0 + + testsamples = [ + {'c0': t0, 'c1': 'aaaaa', 'c2': 1}, + {'c0': t0 + 1, 'c1': 'bbbbb', 'c2': 2}, + {'c0': t0 + 2, 'c1': 'ccccc', 'c2': 10**5}, + {'c0': t0 + 3, 'c1': 'ddddd', 'c2': 4294967295}, + ] + + objname = 'pandas_test_timeseries' + + with ensure_clean_path('written_with_pytables.h5') as path: + # The `ensure_clean_path` context mgr removes the temp file upon exit. + with tables.open_file(path, mode='w') as f: + t = f.create_table('/', name=objname, description=table_schema) + for sample in testsamples: + for key, value in sample.items(): + t.row[key] = value + t.row.append() + + yield path, objname, pd.DataFrame(testsamples) + + +class TestReadPyTablesHDF5: + """ + A group of tests which covers reading HDF5 files written by plain PyTables + (not written by pandas). + + Was introduced for regression-testing issue 11188. + """ + + def test_read_complete(self, pytables_hdf5_file): + path, objname, df = pytables_hdf5_file + result = pd.read_hdf(path, key=objname) + expected = df + assert_frame_equal(result, expected) + + def test_read_with_start(self, pytables_hdf5_file): + path, objname, df = pytables_hdf5_file + # This is a regression test for pandas-dev/pandas/issues/11188 + result = pd.read_hdf(path, key=objname, start=1) + expected = df[1:].reset_index(drop=True) + assert_frame_equal(result, expected) + + def test_read_with_stop(self, pytables_hdf5_file): + path, objname, df = pytables_hdf5_file + # This is a regression test for pandas-dev/pandas/issues/11188 + result = pd.read_hdf(path, key=objname, stop=1) + expected = df[:1].reset_index(drop=True) + assert_frame_equal(result, expected) + + def test_read_with_startstop(self, pytables_hdf5_file): + path, objname, df = pytables_hdf5_file + # This is a regression test for pandas-dev/pandas/issues/11188 + result = pd.read_hdf(path, key=objname, start=1, stop=2) + expected = df[1:2].reset_index(drop=True) + assert_frame_equal(result, expected) diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 299c0feb502be..ef9dbc63d873d 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -105,7 +105,7 @@ def ensure_clean_store(path, mode='a', complevel=None, complib=None, def ensure_clean_path(path): """ return essentially a named temporary file that is not opened - and deleted on existing; if path is a list, then create and + and deleted on exiting; if path is a list, then create and return list of filenames """ try:
- [x] closes #11188 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/26818
2019-06-12T20:05:26Z
2019-06-21T14:19:43Z
2019-06-21T14:19:43Z
2019-06-21T16:09:46Z
make null lowercase a missing value
diff --git a/doc/source/io.rst b/doc/source/io.rst index bca23dd18a0e3..82cb7abde4b38 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -227,7 +227,7 @@ na_values : scalar, str, list-like, or dict, default ``None`` Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: ``'-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN', '#N/A N/A', '#N/A', 'N/A', 'NA', - '#NA', 'NULL', 'NaN', '-NaN', 'nan', '-nan', ''``. + '#NA', 'NULL', 'null', 'NaN', '-NaN', 'nan', '-nan', ''``. keep_default_na : boolean, default ``True`` If na_values are specified and keep_default_na is ``False`` the default NaN values are overridden, otherwise they're appended to. diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index a6b6d704737bd..41231a8813fa5 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -38,7 +38,7 @@ Other Enhancements - :func:`read_feather` has gained the ``nthreads`` parameter for multi-threaded operations (:issue:`16359`) - :func:`DataFrame.clip()` and :func: `Series.cip()` have gained an inplace argument. (:issue: `15388`) - :func:`crosstab` has gained a ``margins_name`` parameter to define the name of the row / column that will contain the totals when margins=True. (:issue:`15972`) - +- :func:`read_csv` has gained 'null' as an additional default missing value.(:issue:`16471`) .. _whatsnew_0210.api_breaking: Backwards incompatible API changes diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 2def4dc9dcf24..7a6f366d5b1a9 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -277,7 +277,7 @@ DEFAULT_CHUNKSIZE = 256 * 1024 # no longer excluding inf representations # '1.#INF','-1.#INF', '1.#INF000000', _NA_VALUES = [b'-1.#IND', b'1.#QNAN', b'1.#IND', b'-1.#QNAN', - b'#N/A N/A', b'NA', b'#NA', b'NULL', b'NaN', + b'#N/A N/A', b'NA', b'#NA', b'NULL', b'null', b'NaN', b'nan', b''] diff --git a/pandas/io/common.py b/pandas/io/common.py index f4e12ea3fb173..1c987f6a9dfc3 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -31,7 +31,7 @@ # '1.#INF','-1.#INF', '1.#INF000000', _NA_VALUES = set([ '-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN', '#N/A N/A', '#N/A', - 'N/A', 'NA', '#NA', 'NULL', 'NaN', '-NaN', 'nan', '-nan', '' + 'N/A', 'NA', '#NA', 'NULL', 'null', 'NaN', '-NaN', 'nan', '-nan', '' ]) try: diff --git a/pandas/tests/io/parser/na_values.py b/pandas/tests/io/parser/na_values.py index 362837a46f838..6f72ed51d76c6 100644 --- a/pandas/tests/io/parser/na_values.py +++ b/pandas/tests/io/parser/na_values.py @@ -70,7 +70,7 @@ def test_non_string_na_values(self): def test_default_na_values(self): _NA_VALUES = set(['-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN', - '#N/A', 'N/A', 'NA', '#NA', 'NULL', 'NaN', + '#N/A', 'N/A', 'NA', '#NA', 'NULL', 'null', 'NaN', 'nan', '-NaN', '-nan', '#N/A N/A', '']) assert _NA_VALUES == parsers._NA_VALUES nv = len(_NA_VALUES)
xref #16079 closes https://github.com/pandas-dev/pandas/issues/16471
https://api.github.com/repos/pandas-dev/pandas/pulls/16534
2017-05-29T20:02:46Z
2017-06-01T22:19:11Z
2017-06-01T22:19:11Z
2017-06-03T12:43:39Z
COMPAT: Consider Python 2.x tarfiles file-like
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 9f88d629880ed..b21ea88bf177f 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -70,6 +70,7 @@ I/O - Bug in pd.read_csv() when comment is passed in space deliminted text files (:issue:`16472`) - Bug that would force importing of the clipboard routines unnecessarily, potentially causing an import error on startup (:issue:`16288`) - Bug that raised IndexError HTML-rendering an empty DataFrame (:issue:`15953`) +- Bug in ``pd.read_csv()`` in which tarfile object inputs were raising an error in Python 2.x for the C engine (:issue:`16530`) - Bug in ``HDFStore.select_as_multiple()`` where start/stop arguments were not respected (:issue:`16209`) diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py index a5316a83612cb..ff7e215951a1f 100644 --- a/pandas/core/dtypes/inference.py +++ b/pandas/core/dtypes/inference.py @@ -171,7 +171,7 @@ def is_file_like(obj): if not (hasattr(obj, 'read') or hasattr(obj, 'write')): return False - if not is_iterator(obj): + if not hasattr(obj, "__iter__"): return False return True diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 12b606d969c7d..aab70c8ce2cd4 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -13,7 +13,7 @@ import numpy as np from pandas import compat -from pandas.compat import (range, lrange, StringIO, lzip, +from pandas.compat import (range, lrange, PY3, StringIO, lzip, zip, string_types, map, u) from pandas.core.dtypes.common import ( is_integer, _ensure_object, @@ -31,10 +31,10 @@ from pandas.core.common import AbstractMethodError from pandas.io.date_converters import generic_parser from pandas.errors import ParserWarning, ParserError, EmptyDataError -from pandas.io.common import (get_filepath_or_buffer, _validate_header_arg, - _get_handle, UnicodeReader, UTF8Recoder, - BaseIterator, - _NA_VALUES, _infer_compression) +from pandas.io.common import (get_filepath_or_buffer, is_file_like, + _validate_header_arg, _get_handle, + UnicodeReader, UTF8Recoder, _NA_VALUES, + BaseIterator, _infer_compression) from pandas.core.tools import datetimes as tools from pandas.util._decorators import Appender @@ -755,7 +755,9 @@ def __init__(self, f, engine=None, **kwds): self.squeeze = options.pop('squeeze', False) # might mutate self.engine + self.engine = self._check_file_or_buffer(f, engine) self.options, self.engine = self._clean_options(options, engine) + if 'has_index_names' in kwds: self.options['has_index_names'] = kwds['has_index_names'] @@ -801,6 +803,23 @@ def _get_options_with_defaults(self, engine): return options + def _check_file_or_buffer(self, f, engine): + # see gh-16530 + if is_file_like(f): + next_attr = "__next__" if PY3 else "next" + + # The C engine doesn't need the file-like to have the "next" or + # "__next__" attribute. However, the Python engine explicitly calls + # "next(...)" when iterating through such an object, meaning it + # needs to have that attribute ("next" for Python 2.x, "__next__" + # for Python 3.x) + if engine != "c" and not hasattr(f, next_attr): + msg = ("The 'python' engine cannot iterate " + "through this file buffer.") + raise ValueError(msg) + + return engine + def _clean_options(self, options, engine): result = options.copy() diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index b88481abcb2ec..ec5fe45d7f610 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -120,9 +120,9 @@ class MockFile(object): m = MockFile() assert not is_file(m) + # gh-16530: Valid iterator just means we have the + # __iter__ attribute for our purposes. MockFile.__iter__ = lambda self: self - MockFile.__next__ = lambda self: 0 - MockFile.next = MockFile.__next__ # Valid write-only file m = MockFile() diff --git a/pandas/tests/io/parser/c_parser_only.py b/pandas/tests/io/parser/c_parser_only.py index 56ac10404b7b2..48812c04e3b55 100644 --- a/pandas/tests/io/parser/c_parser_only.py +++ b/pandas/tests/io/parser/c_parser_only.py @@ -7,7 +7,9 @@ further arguments when parsing. """ +import os import sys +import tarfile import pytest import numpy as np @@ -446,3 +448,37 @@ def test_comment_whitespace_delimited(self): [7, np.nan], [8, np.nan]]) tm.assert_frame_equal(df, expected) + + def test_file_like_no_next(self): + # gh-16530: the file-like need not have a "next" or "__next__" + # attribute despite having an "__iter__" attribute. + # + # NOTE: This is only true for the C engine, not Python engine. + class NoNextBuffer(StringIO): + def __next__(self): + raise AttributeError("No next method") + + next = __next__ + + data = "a\n1" + + expected = pd.DataFrame({"a": [1]}) + result = self.read_csv(NoNextBuffer(data)) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tar_suffix", [".tar", ".tar.gz"]) + def test_read_tarfile(self, tar_suffix): + # see gh-16530 + # + # Unfortunately, Python's CSV library can't handle + # tarfile objects (expects string, not bytes when + # iterating through a file-like). + tar_path = os.path.join(self.dirpath, "tar_csv" + tar_suffix) + + tar = tarfile.open(tar_path, "r") + data_file = tar.extractfile("tar_data.csv") + + out = self.read_csv(data_file) + expected = pd.DataFrame({"a": [1]}) + tm.assert_frame_equal(out, expected) diff --git a/pandas/tests/io/parser/data/tar_csv.tar b/pandas/tests/io/parser/data/tar_csv.tar new file mode 100644 index 0000000000000..d1819550e0a00 Binary files /dev/null and b/pandas/tests/io/parser/data/tar_csv.tar differ diff --git a/pandas/tests/io/parser/data/tar_csv.tar.gz b/pandas/tests/io/parser/data/tar_csv.tar.gz new file mode 100644 index 0000000000000..b5a0f3e1b5805 Binary files /dev/null and b/pandas/tests/io/parser/data/tar_csv.tar.gz differ diff --git a/pandas/tests/io/parser/test_unsupported.py b/pandas/tests/io/parser/test_unsupported.py index 3f62ff44531fb..5d248f2fef59c 100644 --- a/pandas/tests/io/parser/test_unsupported.py +++ b/pandas/tests/io/parser/test_unsupported.py @@ -16,6 +16,13 @@ from pandas.errors import ParserError from pandas.io.parsers import read_csv, read_table +import pytest + + +@pytest.fixture(params=["python", "python-fwf"], ids=lambda val: val) +def python_engine(request): + return request.param + class TestUnsupportedFeatures(object): @@ -82,7 +89,7 @@ def test_c_engine(self): with tm.assert_raises_regex(ValueError, msg): read_csv(StringIO(data), lineterminator='~~') - def test_python_engine(self): + def test_python_engine(self, python_engine): from pandas.io.parsers import _python_unsupported as py_unsupported data = """1,2,3,, @@ -90,16 +97,32 @@ def test_python_engine(self): 1,2,3,4,5 1,2,,, 1,2,3,4,""" - engines = 'python', 'python-fwf' - for engine in engines: - for default in py_unsupported: - msg = ('The %r option is not supported ' - 'with the %r engine' % (default, engine)) + for default in py_unsupported: + msg = ('The %r option is not supported ' + 'with the %r engine' % (default, python_engine)) + + kwargs = {default: object()} + with tm.assert_raises_regex(ValueError, msg): + read_csv(StringIO(data), engine=python_engine, **kwargs) - kwargs = {default: object()} - with tm.assert_raises_regex(ValueError, msg): - read_csv(StringIO(data), engine=engine, **kwargs) + def test_python_engine_file_no_next(self, python_engine): + # see gh-16530 + class NoNextBuffer(object): + def __init__(self, csv_data): + self.data = csv_data + + def __iter__(self): + return self + + def read(self): + return self.data + + data = "a\n1" + msg = "The 'python' engine cannot iterate" + + with tm.assert_raises_regex(ValueError, msg): + read_csv(NoNextBuffer(data), engine=python_engine) class TestDeprecatedFeatures(object): diff --git a/setup.py b/setup.py index 82d5f407228a9..31a3cddc3f9fd 100755 --- a/setup.py +++ b/setup.py @@ -702,6 +702,8 @@ def pxd(name): 'parser/data/*.gz', 'parser/data/*.bz2', 'parser/data/*.txt', + 'parser/data/*.tar', + 'parser/data/*.tar.gz', 'sas/data/*.csv', 'sas/data/*.xpt', 'sas/data/*.sas7bdat',
`Tarfile.ExFileObject` has no `next` method in Python 2.x, making it an invalid file-like object in `read_csv`. However, they can be read in just fine, meaning our check is too strict for file-like. This commit relaxes the check to just look for the `__iter__` attribute. Closes #16530.
https://api.github.com/repos/pandas-dev/pandas/pulls/16533
2017-05-29T17:15:56Z
2017-06-01T10:38:51Z
2017-06-01T10:38:51Z
2017-06-04T17:02:56Z
CLN: raise correct error for Panel sort_values
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index e541f1532d0a0..98999ec267c82 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2366,9 +2366,14 @@ def add_suffix(self, suffix): 1 A 1 1 """ - def sort_values(self, by, axis=0, ascending=True, inplace=False, + def sort_values(self, by=None, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last'): - raise AbstractMethodError(self) + """ + NOT IMPLEMENTED: do not call this method, as sorting values is not + supported for Panel objects and will raise an error. + """ + raise NotImplementedError("sort_values has not been implemented " + "on Panel or Panel4D objects.") _shared_docs['sort_index'] = """ Sort object by labels (along an axis) diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 3243b69a25acd..e19e42e062932 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -2429,6 +2429,11 @@ def test_all_any_unhandled(self): pytest.raises(NotImplementedError, self.panel.all, bool_only=True) pytest.raises(NotImplementedError, self.panel.any, bool_only=True) + # GH issue 15960 + def test_sort_values(self): + pytest.raises(NotImplementedError, self.panel.sort_values) + pytest.raises(NotImplementedError, self.panel.sort_values, 'ItemA') + class TestLongPanel(object): """ diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index 96f02d63712fc..e1995316e7b7c 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -939,3 +939,8 @@ def test_rename(self): def test_get_attr(self): tm.assert_panel_equal(self.panel4d['l1'], self.panel4d.l1) + + # GH issue 15960 + def test_sort_values(self): + pytest.raises(NotImplementedError, self.panel4d.sort_values) + pytest.raises(NotImplementedError, self.panel4d.sort_values, 'ItemA')
- [x] closes #15960 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry I do not believe there is a need for tests or whatsnew entry. I modified the error raised (I think NotImplementedError should reflect better the situation) and added a small docstring to explain that the method is not implemented (similar to other methods in the same class)
https://api.github.com/repos/pandas-dev/pandas/pulls/16532
2017-05-29T16:55:09Z
2017-05-31T23:10:24Z
2017-05-31T23:10:24Z
2017-05-31T23:10:29Z
TST: Skip test_database_uri_string if pg8000 importable
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 7b3717281bf89..23ec1ab820f8a 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -938,6 +938,13 @@ def test_database_uri_string(self): # using driver that will not be installed on Travis to trigger error # in sqlalchemy.create_engine -> test passing of this error to user + try: + # the rest of this test depends on pg8000's being absent + import pg8000 # noqa + pytest.skip("pg8000 is installed") + except ImportError: + pass + db_uri = "postgresql+pg8000://user:pass@host/dbname" with tm.assert_raises_regex(ImportError, "pg8000"): sql.read_sql("select * from table", db_uri)
- [x] closes #16527 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16528
2017-05-28T20:02:16Z
2017-06-01T19:50:38Z
2017-06-01T19:50:37Z
2018-02-11T23:41:09Z
TST: Specify HTML file encoding on PY3
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index 6da77bf423609..1e1d653cf94d1 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -20,7 +20,7 @@ from pandas import (DataFrame, MultiIndex, read_csv, Timestamp, Index, date_range, Series) from pandas.compat import (map, zip, StringIO, string_types, BytesIO, - is_platform_windows) + is_platform_windows, PY3) from pandas.io.common import URLError, urlopen, file_path_to_url from pandas.io.html import read_html from pandas._libs.parsers import ParserError @@ -96,6 +96,9 @@ def read_html(self, *args, **kwargs): class TestReadHtml(ReadHtmlMixin): flavor = 'bs4' spam_data = os.path.join(DATA_PATH, 'spam.html') + spam_data_kwargs = {} + if PY3: + spam_data_kwargs['encoding'] = 'UTF-8' banklist_data = os.path.join(DATA_PATH, 'banklist.html') @classmethod @@ -247,10 +250,10 @@ def test_infer_types(self): assert_framelist_equal(df1, df2) def test_string_io(self): - with open(self.spam_data) as f: + with open(self.spam_data, **self.spam_data_kwargs) as f: data1 = StringIO(f.read()) - with open(self.spam_data) as f: + with open(self.spam_data, **self.spam_data_kwargs) as f: data2 = StringIO(f.read()) df1 = self.read_html(data1, '.*Water.*') @@ -258,7 +261,7 @@ def test_string_io(self): assert_framelist_equal(df1, df2) def test_string(self): - with open(self.spam_data) as f: + with open(self.spam_data, **self.spam_data_kwargs) as f: data = f.read() df1 = self.read_html(data, '.*Water.*') @@ -267,10 +270,10 @@ def test_string(self): assert_framelist_equal(df1, df2) def test_file_like(self): - with open(self.spam_data) as f: + with open(self.spam_data, **self.spam_data_kwargs) as f: df1 = self.read_html(f, '.*Water.*') - with open(self.spam_data) as f: + with open(self.spam_data, **self.spam_data_kwargs) as f: df2 = self.read_html(f, 'Unit') assert_framelist_equal(df1, df2)
- [x] closes #16525 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16526
2017-05-28T18:59:57Z
2017-05-29T16:00:42Z
2017-05-29T16:00:42Z
2019-01-30T22:16:42Z
BUG: read_msgpack raise an error when passed an non existent path in Python 2
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index e85ba505887b4..4b2999416ffbe 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -86,6 +86,8 @@ Documentation Changes Bug Fixes ~~~~~~~~~ +- Bug in ``pd.read_msgpack()`` with a non existent file is passed in Python 2 (:issue:`15296`) + Conversion ^^^^^^^^^^ diff --git a/pandas/io/packers.py b/pandas/io/packers.py index abd258034af99..ef65a3275060b 100644 --- a/pandas/io/packers.py +++ b/pandas/io/packers.py @@ -192,7 +192,6 @@ def read(fh): # see if we have an actual file if isinstance(path_or_buf, compat.string_types): - try: exists = os.path.exists(path_or_buf) except (TypeError, ValueError): @@ -202,18 +201,21 @@ def read(fh): with open(path_or_buf, 'rb') as fh: return read(fh) - # treat as a binary-like if isinstance(path_or_buf, compat.binary_type): + # treat as a binary-like fh = None try: - fh = compat.BytesIO(path_or_buf) - return read(fh) + # We can't distinguish between a path and a buffer of bytes in + # Python 2 so instead assume the first byte of a valid path is + # less than 0x80. + if compat.PY3 or ord(path_or_buf[0]) >= 0x80: + fh = compat.BytesIO(path_or_buf) + return read(fh) finally: if fh is not None: fh.close() - - # a buffer like - if hasattr(path_or_buf, 'read') and compat.callable(path_or_buf.read): + elif hasattr(path_or_buf, 'read') and compat.callable(path_or_buf.read): + # treat as a buffer like return read(path_or_buf) raise ValueError('path_or_buf needs to be a string file path or file-like') diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index 30904593fedc4..707580bfe9601 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -10,7 +10,7 @@ import pandas.util.testing as tm from pandas.io import common -from pandas.compat import is_platform_windows, StringIO +from pandas.compat import is_platform_windows, StringIO, FileNotFoundError from pandas import read_csv, concat @@ -125,6 +125,26 @@ def test_iterator(self): tm.assert_frame_equal(first, expected.iloc[[0]]) tm.assert_frame_equal(concat(it), expected.iloc[1:]) + @pytest.mark.parametrize('reader, module, error_class, fn_ext', [ + (pd.read_csv, 'os', FileNotFoundError, 'csv'), + (pd.read_table, 'os', FileNotFoundError, 'csv'), + (pd.read_fwf, 'os', FileNotFoundError, 'txt'), + (pd.read_excel, 'xlrd', FileNotFoundError, 'xlsx'), + (pd.read_feather, 'feather', Exception, 'feather'), + (pd.read_hdf, 'tables', FileNotFoundError, 'h5'), + (pd.read_stata, 'os', FileNotFoundError, 'dta'), + (pd.read_sas, 'os', FileNotFoundError, 'sas7bdat'), + (pd.read_json, 'os', ValueError, 'json'), + (pd.read_msgpack, 'os', ValueError, 'mp'), + (pd.read_pickle, 'os', FileNotFoundError, 'pickle'), + ]) + def test_read_non_existant(self, reader, module, error_class, fn_ext): + pytest.importorskip(module) + + path = os.path.join(HERE, 'data', 'does_not_exist.' + fn_ext) + with pytest.raises(error_class): + reader(path) + @pytest.mark.parametrize('reader, module, path', [ (pd.read_csv, 'os', os.path.join(HERE, 'data', 'iris.csv')), (pd.read_table, 'os', os.path.join(HERE, 'data', 'iris.csv')),
- [ ] closes #15296 - [x] 11 tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry This PR adds tests to check that a suitable error is raised when a non existent path is passed to `pd.read_xxxxx()`. A fix is also included for `read_msgpack` with python 2 which works by checking that the first byte of the passed string is `>= 0x80`. So far as I can tell these are [reserved and unused by pandas](https://github.com/msgpack/msgpack/blob/master/spec.md#types-extension-type) so I think this shouldn't break any existing functionality.
https://api.github.com/repos/pandas-dev/pandas/pulls/16523
2017-05-28T10:20:00Z
2017-10-30T12:53:40Z
2017-10-30T12:53:40Z
2017-10-30T13:02:31Z
MAINT: Drop has_index_names input from read_excel
diff --git a/doc/source/io.rst b/doc/source/io.rst index bca23dd18a0e3..af337d770c7f7 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -2739,11 +2739,6 @@ should be passed to ``index_col`` and ``header`` import os os.remove('path_to_file.xlsx') -.. warning:: - - Excel files saved in version 0.16.2 or prior that had index names will still able to be read in, - but the ``has_index_names`` argument must specified to ``True``. - Parsing Specific Columns ++++++++++++++++++++++++ diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index a6b6d704737bd..4b6abca50cd20 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -70,6 +70,7 @@ Deprecations Removal of prior version deprecations/changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +- ``pd.read_excel()`` has dropped the ``has_index_names`` parameter (:issue:`10967`) .. _whatsnew_0210.performance: diff --git a/pandas/io/excel.py b/pandas/io/excel.py index aa08e5fd378f0..a4d2fabf76a41 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -141,10 +141,6 @@ convert integral floats to int (i.e., 1.0 --> 1). If False, all numeric data will be read in as floats: Excel stores all numbers as floats internally -has_index_names : boolean, default None - DEPRECATED: for version 0.17+ index names will be automatically - inferred based on index_col. To read Excel output from 0.16.2 and - prior that had saved index names, use True. Returns ------- @@ -198,8 +194,8 @@ def get_writer(engine_name): def read_excel(io, sheet_name=0, header=0, skiprows=None, skip_footer=0, index_col=None, names=None, parse_cols=None, parse_dates=False, date_parser=None, na_values=None, thousands=None, - convert_float=True, has_index_names=None, converters=None, - dtype=None, true_values=None, false_values=None, engine=None, + convert_float=True, converters=None, dtype=None, + true_values=None, false_values=None, engine=None, squeeze=False, **kwds): # Can't use _deprecate_kwarg since sheetname=None has a special meaning @@ -218,10 +214,9 @@ def read_excel(io, sheet_name=0, header=0, skiprows=None, skip_footer=0, sheetname=sheet_name, header=header, skiprows=skiprows, names=names, index_col=index_col, parse_cols=parse_cols, parse_dates=parse_dates, date_parser=date_parser, na_values=na_values, thousands=thousands, - convert_float=convert_float, has_index_names=has_index_names, - skip_footer=skip_footer, converters=converters, dtype=dtype, - true_values=true_values, false_values=false_values, squeeze=squeeze, - **kwds) + convert_float=convert_float, skip_footer=skip_footer, + converters=converters, dtype=dtype, true_values=true_values, + false_values=false_values, squeeze=squeeze, **kwds) class ExcelFile(object): @@ -283,9 +278,8 @@ def __fspath__(self): def parse(self, sheet_name=0, header=0, skiprows=None, skip_footer=0, names=None, index_col=None, parse_cols=None, parse_dates=False, date_parser=None, na_values=None, thousands=None, - convert_float=True, has_index_names=None, - converters=None, true_values=None, false_values=None, - squeeze=False, **kwds): + convert_float=True, converters=None, true_values=None, + false_values=None, squeeze=False, **kwds): """ Parse specified sheet(s) into a DataFrame @@ -296,7 +290,6 @@ def parse(self, sheet_name=0, header=0, skiprows=None, skip_footer=0, return self._parse_excel(sheetname=sheet_name, header=header, skiprows=skiprows, names=names, index_col=index_col, - has_index_names=has_index_names, parse_cols=parse_cols, parse_dates=parse_dates, date_parser=date_parser, na_values=na_values, @@ -343,23 +336,17 @@ def _excel2num(x): return i in parse_cols def _parse_excel(self, sheetname=0, header=0, skiprows=None, names=None, - skip_footer=0, index_col=None, has_index_names=None, - parse_cols=None, parse_dates=False, date_parser=None, - na_values=None, thousands=None, convert_float=True, - true_values=None, false_values=None, verbose=False, - dtype=None, squeeze=False, **kwds): + skip_footer=0, index_col=None, parse_cols=None, + parse_dates=False, date_parser=None, na_values=None, + thousands=None, convert_float=True, true_values=None, + false_values=None, verbose=False, dtype=None, + squeeze=False, **kwds): skipfooter = kwds.pop('skipfooter', None) if skipfooter is not None: skip_footer = skipfooter _validate_header_arg(header) - if has_index_names is not None: - warn("\nThe has_index_names argument is deprecated; index names " - "will be automatically inferred based on index_col.\n" - "This argmument is still necessary if reading Excel output " - "from 0.16.2 or prior with index names.", FutureWarning, - stacklevel=3) if 'chunksize' in kwds: raise NotImplementedError("chunksize keyword of read_excel " @@ -511,8 +498,7 @@ def _parse_cell(cell_contents, cell_typ): else: last = data[row][col] - if is_list_like(header) and len(header) > 1: - has_index_names = True + has_index_names = is_list_like(header) and len(header) > 1 # GH 12292 : error when read one empty column from excel file try: diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index 4441ed815370b..abe3757ec64f3 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -881,8 +881,42 @@ def test_excel_multindex_roundtrip(self): tm.assert_frame_equal( df, act, check_names=check_names) - def test_excel_oldindex_format(self): - # GH 4679 + def test_excel_old_index_format(self): + # see gh-4679 + filename = 'test_index_name_pre17' + self.ext + in_file = os.path.join(self.dirpath, filename) + + # We detect headers to determine if index names exist, so + # that "index" name in the "names" version of the data will + # now be interpreted as rows that include null data. + data = np.array([[None, None, None, None, None], + ['R0C0', 'R0C1', 'R0C2', 'R0C3', 'R0C4'], + ['R1C0', 'R1C1', 'R1C2', 'R1C3', 'R1C4'], + ['R2C0', 'R2C1', 'R2C2', 'R2C3', 'R2C4'], + ['R3C0', 'R3C1', 'R3C2', 'R3C3', 'R3C4'], + ['R4C0', 'R4C1', 'R4C2', 'R4C3', 'R4C4']]) + columns = ['C_l0_g0', 'C_l0_g1', 'C_l0_g2', 'C_l0_g3', 'C_l0_g4'] + mi = MultiIndex(levels=[['R0', 'R_l0_g0', 'R_l0_g1', + 'R_l0_g2', 'R_l0_g3', 'R_l0_g4'], + ['R1', 'R_l1_g0', 'R_l1_g1', + 'R_l1_g2', 'R_l1_g3', 'R_l1_g4']], + labels=[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]], + names=[None, None]) + si = Index(['R0', 'R_l0_g0', 'R_l0_g1', 'R_l0_g2', + 'R_l0_g3', 'R_l0_g4'], name=None) + + expected = pd.DataFrame(data, index=si, columns=columns) + + actual = pd.read_excel(in_file, 'single_names') + tm.assert_frame_equal(actual, expected) + + expected.index = mi + + actual = pd.read_excel(in_file, 'multi_names') + tm.assert_frame_equal(actual, expected) + + # The analogous versions of the "names" version data + # where there are explicitly no names for the indices. data = np.array([['R0C0', 'R0C1', 'R0C2', 'R0C3', 'R0C4'], ['R1C0', 'R1C1', 'R1C2', 'R1C3', 'R1C4'], ['R2C0', 'R2C1', 'R2C2', 'R2C3', 'R2C4'], @@ -894,40 +928,19 @@ def test_excel_oldindex_format(self): ['R_l1_g0', 'R_l1_g1', 'R_l1_g2', 'R_l1_g3', 'R_l1_g4']], labels=[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], - names=['R0', 'R1']) + names=[None, None]) si = Index(['R_l0_g0', 'R_l0_g1', 'R_l0_g2', - 'R_l0_g3', 'R_l0_g4'], name='R0') - - in_file = os.path.join( - self.dirpath, 'test_index_name_pre17' + self.ext) + 'R_l0_g3', 'R_l0_g4'], name=None) expected = pd.DataFrame(data, index=si, columns=columns) - with tm.assert_produces_warning(FutureWarning): - actual = pd.read_excel( - in_file, 'single_names', has_index_names=True) - tm.assert_frame_equal(actual, expected) - expected.index.name = None actual = pd.read_excel(in_file, 'single_no_names') tm.assert_frame_equal(actual, expected) - with tm.assert_produces_warning(FutureWarning): - actual = pd.read_excel( - in_file, 'single_no_names', has_index_names=False) - tm.assert_frame_equal(actual, expected) expected.index = mi - with tm.assert_produces_warning(FutureWarning): - actual = pd.read_excel( - in_file, 'multi_names', has_index_names=True) - tm.assert_frame_equal(actual, expected) - expected.index.names = [None, None] actual = pd.read_excel(in_file, 'multi_no_names', index_col=[0, 1]) tm.assert_frame_equal(actual, expected, check_names=False) - with tm.assert_produces_warning(FutureWarning): - actual = pd.read_excel(in_file, 'multi_no_names', index_col=[0, 1], - has_index_names=False) - tm.assert_frame_equal(actual, expected, check_names=False) def test_read_excel_bool_header_arg(self): # GH 6114
Deprecated since 0.17.0 xref #10967
https://api.github.com/repos/pandas-dev/pandas/pulls/16522
2017-05-28T09:56:03Z
2017-06-01T22:24:20Z
2017-06-01T22:24:19Z
2017-06-03T08:40:45Z
DOC: Improving docstring of pop method (#16416)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 5722539b87aec..a4bb746722c1e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -547,6 +547,43 @@ def swapaxes(self, axis1, axis2, copy=True): def pop(self, item): """ Return item and drop from frame. Raise KeyError if not found. + + Parameters + ---------- + item : str + Column label to be popped + + Returns + ------- + popped : Series + + Examples + -------- + >>> df = pd.DataFrame([('falcon', 'bird', 389.0), + ... ('parrot', 'bird', 24.0), + ... ('lion', 'mammal', 80.5), + ... ('monkey', 'mammal', np.nan)], + ... columns=('name', 'class', 'max_speed')) + >>> df + name class max_speed + 0 falcon bird 389.0 + 1 parrot bird 24.0 + 2 lion mammal 80.5 + 3 monkey mammal NaN + + >>> df.pop('class') + 0 bird + 1 bird + 2 mammal + 3 mammal + Name: class, dtype: object + + >>> df + name max_speed + 0 falcon 389.0 + 1 parrot 24.0 + 2 lion 80.5 + 3 monkey NaN """ result = self[item] del self[item]
- [ ] closes #xxxx - [ ] tests added / passed - [X] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry As discussed in gitter, it'd be nice to have more and better examples in the API documentation. I think it'd be nice to have as many examples as possible with the same DataFrame, so the users who check the documentation know it without needing to read it again. In this PR I propose a standard DataFrame that: - Is simple to understand - Contains all the main dtypes - Contains NaNs - It can be groupped Please feel free to propose a another one if you have a better idea, and reject this PR. Let me know if the format of this docstring, as well as the DataFrame can be used for the rest of the method docstrings, and I'll work with them. You can see how the html documentation looks like in the next screenshot: ![pandas_pop_doc](https://cloud.githubusercontent.com/assets/10058240/26524333/883d96e6-4327-11e7-856c-31cc3446b268.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/16520
2017-05-27T21:03:38Z
2017-07-15T15:38:23Z
2017-07-15T15:38:23Z
2017-07-15T15:38:26Z
DOC: Remove preference for pytest paradigm in assert_raises_regex
diff --git a/pandas/util/testing.py b/pandas/util/testing.py index f987045c27d5f..17e09b38b20e0 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -2424,15 +2424,8 @@ def assert_raises_regex(_exception, _regexp, _callable=None, Check that the specified Exception is raised and that the error message matches a given regular expression pattern. This may be a regular expression object or a string containing a regular expression suitable - for use by `re.search()`. - - This is a port of the `assertRaisesRegexp` function from unittest in - Python 2.7. However, with our migration to `pytest`, please refrain - from using this. Instead, use the following paradigm: - - with pytest.raises(_exception) as exc_info: - func(*args, **kwargs) - exc_info.matches(reg_exp) + for use by `re.search()`. This is a port of the `assertRaisesRegexp` + function from unittest in Python 2.7. Examples --------
`tm.assert_raises_regex` is a more compact version of the following: ~~~python with pytest.raises(<exc_type>) as exc_info: f(...) exc_info.match(<regex>) ~~~ No reason for the docs to say that we prefer the `pytest` paradigm over our own. xref <a href="https://github.com/pandas-dev/pandas/pull/16511#discussion_r118771331">#16511 (comment)</a>
https://api.github.com/repos/pandas-dev/pandas/pulls/16518
2017-05-27T00:57:28Z
2017-05-27T01:35:12Z
2017-05-27T01:35:12Z
2017-05-27T16:39:26Z
DOC: Update Sphinx Deprecated Directive
diff --git a/doc/source/io.rst b/doc/source/io.rst index e7c1cc13d103d..74a604339cddb 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -137,8 +137,10 @@ usecols : array-like or callable, default ``None`` Using this parameter results in much faster parsing time and lower memory usage. as_recarray : boolean, default ``False`` - DEPRECATED: this argument will be removed in a future version. Please call - ``pd.read_csv(...).to_records()`` instead. + + .. deprecated:: 0.18.2 + + Please call ``pd.read_csv(...).to_records()`` instead. Return a NumPy recarray instead of a DataFrame after parsing the data. If set to ``True``, this option takes precedence over the ``squeeze`` parameter. @@ -191,7 +193,11 @@ skiprows : list-like or integer, default ``None`` skipfooter : int, default ``0`` Number of lines at bottom of file to skip (unsupported with engine='c'). skip_footer : int, default ``0`` - DEPRECATED: use the ``skipfooter`` parameter instead, as they are identical + + .. deprecated:: 0.19.0 + + Use the ``skipfooter`` parameter instead, as they are identical + nrows : int, default ``None`` Number of rows of file to read. Useful for reading pieces of large files. low_memory : boolean, default ``True`` @@ -202,16 +208,25 @@ low_memory : boolean, default ``True`` use the ``chunksize`` or ``iterator`` parameter to return the data in chunks. (Only valid with C parser) buffer_lines : int, default None - DEPRECATED: this argument will be removed in a future version because its - value is not respected by the parser + + .. deprecated:: 0.19.0 + + Argument removed because its value is not respected by the parser + compact_ints : boolean, default False - DEPRECATED: this argument will be removed in a future version + + .. deprecated:: 0.19.0 + + Argument moved to ``pd.to_numeric`` If ``compact_ints`` is ``True``, then for any column that is of integer dtype, the parser will attempt to cast it as the smallest integer ``dtype`` possible, either signed or unsigned depending on the specification from the ``use_unsigned`` parameter. use_unsigned : boolean, default False - DEPRECATED: this argument will be removed in a future version + + .. deprecated:: 0.18.2 + + Argument moved to ``pd.to_numeric`` If integer columns are being compacted (i.e. ``compact_ints=True``), specify whether the column should be compacted to the smallest signed or unsigned integer dtype. diff --git a/doc/sphinxext/numpydoc/README.rst b/doc/sphinxext/numpydoc/README.rst index 89b9f2fd23e9b..f91811ef9add6 100755 --- a/doc/sphinxext/numpydoc/README.rst +++ b/doc/sphinxext/numpydoc/README.rst @@ -46,6 +46,6 @@ The following options can be set in conf.py: methods and attributes. If a table of contents is made, Sphinx expects each entry to have a separate page. -- numpydoc_edit_link: bool (DEPRECATED -- edit your HTML template instead) +- numpydoc_edit_link: bool (DEPRECATED -- edit your HTML template instead) Whether to insert an edit link after docstrings. diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index ce70fb94b6cd4..796b2696af9ce 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -398,8 +398,8 @@ def itemsize(self): def reshape(self, new_shape, *args, **kwargs): """ - DEPRECATED: calling this method will raise an error in a - future release. + .. deprecated:: 0.19.0 + Calling this method will raise an error in a future release. An ndarray-compatible method that returns `self` because `Categorical` instances cannot actually be reshaped. @@ -430,7 +430,8 @@ def base(self): @classmethod def from_array(cls, data, **kwargs): """ - DEPRECATED: Use ``Categorical`` instead. + .. deprecated:: 0.19.0 + Use ``Categorical`` instead. Make a Categorical type from a single array-like object. diff --git a/pandas/core/common.py b/pandas/core/common.py index ed768a5743666..3b09e68c6433a 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -555,7 +555,8 @@ def in_qtconsole(): """ check if we're inside an IPython qtconsole - DEPRECATED: This is no longer needed, or working, in IPython 3 and above. + .. deprecated:: 0.14.1 + This is no longer needed, or working, in IPython 3 and above. """ try: ip = get_ipython() # noqa @@ -573,8 +574,8 @@ def in_ipnb(): """ check if we're inside an IPython Notebook - DEPRECATED: This is no longer used in pandas, and won't work in IPython 3 - and above. + .. deprecated:: 0.14.1 + This is no longer needed, or working, in IPython 3 and above. """ try: ip = get_ipython() # noqa diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7b56c30fcc9f6..6069757efc429 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1338,9 +1338,9 @@ def to_sql(self, name, con, flavor=None, schema=None, if_exists='fail', Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. flavor : 'sqlite', default None - DEPRECATED: this parameter will be removed in a future version, - as 'sqlite' is the only supported option if SQLAlchemy is not - installed. + .. deprecated:: 0.19.0 + 'sqlite' is the only supported option if SQLAlchemy is not + used. schema : string, default None Specify the schema (if database flavor supports this). If None, use default schema. @@ -3498,7 +3498,9 @@ def astype(self, dtype, copy=True, errors='raise', **kwargs): .. versionadded:: 0.20.0 - raise_on_error : DEPRECATED use ``errors`` instead + raise_on_error : raise on invalid input + .. deprecated:: 0.20.0 + Use ``errors`` instead kwargs : keyword arguments to pass on to the constructor Returns @@ -3602,7 +3604,6 @@ def convert_objects(self, convert_dates=True, convert_numeric=False, convert_timedeltas=True, copy=True): """ Deprecated. - Attempt to infer better dtype for object columns Parameters @@ -5809,8 +5810,9 @@ def tz_localize(self, tz, axis=0, level=None, copy=True, - 'NaT' will return NaT where there are ambiguous times - 'raise' will raise an AmbiguousTimeError if there are ambiguous times - infer_dst : boolean, default False (DEPRECATED) - Attempt to infer fall dst-transition hours based on order + infer_dst : boolean, default False + .. deprecated:: 0.15.0 + Attempt to infer fall dst-transition hours based on order Returns ------- diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 239894cff3874..d8aae2367976b 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -197,8 +197,9 @@ class DatetimeIndex(DatelikeOps, TimelikeOps, DatetimeIndexOpsMixin, times) - 'NaT' will return NaT where there are ambiguous times - 'raise' will raise an AmbiguousTimeError if there are ambiguous times - infer_dst : boolean, default False (DEPRECATED) - Attempt to infer fall dst-transition hours based on order + infer_dst : boolean, default False + .. deprecated:: 0.15.0 + Attempt to infer fall dst-transition hours based on order name : object Name to be stored in the index @@ -1818,8 +1819,9 @@ def tz_localize(self, tz, ambiguous='raise', errors='raise'): .. versionadded:: 0.19.0 - infer_dst : boolean, default False (DEPRECATED) - Attempt to infer fall dst-transition hours based on order + infer_dst : boolean, default False + .. deprecated:: 0.15.0 + Attempt to infer fall dst-transition hours based on order Returns ------- diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index f8af6c8303d99..9d1a49e13c804 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -558,7 +558,8 @@ def asfreq(self, freq=None, how='E'): def to_datetime(self, dayfirst=False): """ - DEPRECATED: use :meth:`to_timestamp` instead. + .. deprecated:: 0.19.0 + Use :meth:`to_timestamp` instead. Cast to DatetimeIndex. """ diff --git a/pandas/core/panel4d.py b/pandas/core/panel4d.py index f32de29c5c167..16e7d0dfcc336 100644 --- a/pandas/core/panel4d.py +++ b/pandas/core/panel4d.py @@ -19,10 +19,10 @@ having 4 named dimensions. It is intended as a test bed for more N-Dimensional named containers. - DEPRECATED. Panel4D is deprecated and will be removed in a future version. - The recommended way to represent these types of n-dimensional data are with - the `xarray package <http://xarray.pydata.org/en/stable/>`__. - Pandas provides a `.to_xarray()` method to automate this conversion. + .. deprecated:: 0.19.0 + The recommended way to represent these types of n-dimensional data + are with the `xarray package <http://xarray.pydata.org/en/stable/>`__. + Pandas provides a `.to_xarray()` method to automate this conversion. Parameters ---------- diff --git a/pandas/core/panelnd.py b/pandas/core/panelnd.py index 26ceeea654e4e..7a5cb63cd4f07 100644 --- a/pandas/core/panelnd.py +++ b/pandas/core/panelnd.py @@ -9,10 +9,10 @@ def create_nd_panel_factory(klass_name, orders, slices, slicer, aliases=None, stat_axis=2, info_axis=0, ns=None): """ manufacture a n-d class: - DEPRECATED. Panelnd is deprecated and will be removed in a future version. - The recommended way to represent these types of n-dimensional data are with - the `xarray package <http://xarray.pydata.org/en/stable/>`__. - Pandas provides a `.to_xarray()` method to automate this conversion. + .. deprecated:: 0.19.0 + The recommended way to represent these types of n-dimensional data + are with the `xarray package <http://xarray.pydata.org/en/stable/>`__. + Pandas provides a `.to_xarray()` method to automate this conversion. Parameters ---------- diff --git a/pandas/core/series.py b/pandas/core/series.py index 74d4f3f955f26..e1f668dd3afda 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -850,8 +850,9 @@ def repeat(self, repeats, *args, **kwargs): def reshape(self, *args, **kwargs): """ - DEPRECATED: calling this method will raise an error in a - future release. Please call ``.values.reshape(...)`` instead. + .. deprecated:: 0.19.0 + Calling this method will raise an error. Please call + ``.values.reshape(...)`` instead. return an ndarray with the values shape if the specified shape matches exactly the current shape, then diff --git a/pandas/core/sparse/array.py b/pandas/core/sparse/array.py index c75de01b98e4e..5c1cf8c773501 100644 --- a/pandas/core/sparse/array.py +++ b/pandas/core/sparse/array.py @@ -391,8 +391,8 @@ def to_dense(self, fill=None): Parameters ---------- fill: float, default None - DEPRECATED: this argument will be removed in a future version - because it is not respected by this function. + .. deprecated:: 0.20.0 + This argument is not respected by this function. Returns ------- diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 4814e78ee6546..cd7e313b13f1e 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -478,7 +478,7 @@ def str_match(arr, pat, case=True, flags=0, na=np.nan, as_indexer=None): flags : int, default 0 (no flags) re module flags, e.g. re.IGNORECASE na : default NaN, fill value for missing values. - as_indexer : DEPRECATED + as_indexer : DEPRECATED - Keyword is ignored. Returns ------- diff --git a/pandas/core/window.py b/pandas/core/window.py index ba7e79944ab0e..01b1bdc3e5054 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -342,21 +342,23 @@ def aggregate(self, arg, *args, **kwargs): Parameters ---------- - how : string, default None (DEPRECATED) - Method for down- or re-sampling""") + how : string, default None + .. deprecated:: 0.18.0 + Method for down- or re-sampling""") _shared_docs['mean'] = dedent(""" %(name)s mean Parameters ---------- - how : string, default None (DEPRECATED) - Method for down- or re-sampling""") + how : string, default None + .. deprecated:: 0.18.0 + Method for down- or re-sampling""") class Window(_Window): """ - Provides rolling window calculcations. + Provides rolling window calculations. .. versionadded:: 0.18.0 @@ -374,9 +376,10 @@ class Window(_Window): Minimum number of observations in window required to have a value (otherwise result is NA). For a window that is specified by an offset, this will default to 1. - freq : string or DateOffset object, optional (default None) (DEPRECATED) - Frequency to conform the data to before computing the statistic. - Specified as a frequency string or DateOffset object. + freq : string or DateOffset object, optional (default None) + .. deprecated:: 0.18.0 + Frequency to conform the data to before computing the statistic. + Specified as a frequency string or DateOffset object. center : boolean, default False Set the labels at the center of the window. win_type : string, default None @@ -571,8 +574,9 @@ def _apply_window(self, mean=True, how=None, **kwargs): ---------- mean : boolean, default True If True computes weighted mean, else weighted sum - how : string, default to None (DEPRECATED) - how to resample + how : string, default to None + .. deprecated:: 0.18.0 + how to resample Returns ------- @@ -736,8 +740,9 @@ def _apply(self, func, name=None, window=None, center=None, window : int/array, default to _get_window() center : boolean, default to self.center check_minp : function, default to _use_window - how : string, default to None (DEPRECATED) - how to resample + how : string, default to None + .. deprecated:: 0.18.0 + how to resample Returns ------- @@ -864,8 +869,9 @@ def sum(self, *args, **kwargs): Parameters ---------- - how : string, default 'max' (DEPRECATED) - Method for down- or re-sampling""") + how : string, default 'max' + .. deprecated:: 0.18.0 + Method for down- or re-sampling""") def max(self, how=None, *args, **kwargs): nv.validate_window_func('max', args, kwargs) @@ -878,8 +884,9 @@ def max(self, how=None, *args, **kwargs): Parameters ---------- - how : string, default 'min' (DEPRECATED) - Method for down- or re-sampling""") + how : string, default 'min' + .. deprecated:: 0.18.0 + Method for down- or re-sampling""") def min(self, how=None, *args, **kwargs): nv.validate_window_func('min', args, kwargs) @@ -896,8 +903,9 @@ def mean(self, *args, **kwargs): Parameters ---------- - how : string, default 'median' (DEPRECATED) - Method for down- or re-sampling""") + how : string, default 'median' + .. deprecated:: 0.18.0 + Method for down- or re-sampling""") def median(self, how=None, **kwargs): if self.freq is not None and how is None: @@ -1329,9 +1337,10 @@ class Expanding(_Rolling_and_Expanding): min_periods : int, default None Minimum number of observations in window required to have a value (otherwise result is NA). - freq : string or DateOffset object, optional (default None) (DEPRECATED) - Frequency to conform the data to before computing the statistic. - Specified as a frequency string or DateOffset object. + freq : string or DateOffset object, optional (default None) + .. deprecated:: 0.18.0 + Frequency to conform the data to before computing the statistic. + Specified as a frequency string or DateOffset object. center : boolean, default False Set the labels at the center of the window. axis : int or string, default 0 @@ -1593,8 +1602,9 @@ class EWM(_Rolling): min_periods : int, default 0 Minimum number of observations in window required to have a value (otherwise result is NA). - freq : None or string alias / date offset object, default=None (DEPRECATED) - Frequency to conform to before computing statistic + freq : None or string alias / date offset object, default=None + .. deprecated:: 0.18.0 + Frequency to conform to before computing statistic adjust : boolean, default True Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings (viewing EWMA as a moving average) @@ -1727,8 +1737,9 @@ def _apply(self, func, how=None, **kwargs): Parameters ---------- func : string/callable to apply - how : string, default to None (DEPRECATED) - how to resample + how : string, default to None + .. deprecated:: 0.18.0 + how to resample Returns ------- diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 0350849037391..343bc7a74fde8 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -105,8 +105,8 @@ ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster parsing time and lower memory usage. as_recarray : boolean, default False - DEPRECATED: this argument will be removed in a future version. Please call - `pd.read_csv(...).to_records()` instead. + .. deprecated:: 0.19.0 + Please call `pd.read_csv(...).to_records()` instead. Return a NumPy recarray instead of a DataFrame after parsing the data. If set to True, this option takes precedence over the `squeeze` parameter. @@ -145,7 +145,8 @@ skipfooter : int, default 0 Number of lines at bottom of file to skip (Unsupported with engine='c') skip_footer : int, default 0 - DEPRECATED: use the `skipfooter` parameter instead, as they are identical + .. deprecated:: 0.19.0 + Use the `skipfooter` parameter instead, as they are identical nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files na_values : scalar, str, list-like, or dict, default None @@ -277,17 +278,19 @@ use the `chunksize` or `iterator` parameter to return the data in chunks. (Only valid with C parser) buffer_lines : int, default None - DEPRECATED: this argument will be removed in a future version because its - value is not respected by the parser + .. deprecated:: 0.19.0 + This argument is not respected by the parser compact_ints : boolean, default False - DEPRECATED: this argument will be removed in a future version + .. deprecated:: 0.19.0 + Argument moved to ``pd.to_numeric`` If compact_ints is True, then for any column that is of integer dtype, the parser will attempt to cast it as the smallest integer dtype possible, either signed or unsigned depending on the specification from the `use_unsigned` parameter. use_unsigned : boolean, default False - DEPRECATED: this argument will be removed in a future version + .. deprecated:: 0.19.0 + Argument moved to ``pd.to_numeric`` If integer columns are being compacted (i.e. `compact_ints=True`), specify whether the column should be compacted to the smallest signed or unsigned diff --git a/pandas/io/sql.py b/pandas/io/sql.py index ee992c6dd3439..0dbef66616e43 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -432,7 +432,9 @@ def to_sql(frame, name, con, flavor=None, schema=None, if_exists='fail', library. If a DBAPI2 object, only sqlite3 is supported. flavor : 'sqlite', default None - DEPRECATED: this parameter will be removed in a future version + .. deprecated:: 0.19.0 + 'sqlite' is the only supported option if SQLAlchemy is not + used. schema : string, default None Name of SQL schema in database to write to (if database flavor supports this). If None, use default schema (default). @@ -484,7 +486,9 @@ def has_table(table_name, con, flavor=None, schema=None): library. If a DBAPI2 object, only sqlite3 is supported. flavor : 'sqlite', default None - DEPRECATED: this parameter will be removed in a future version + .. deprecated:: 0.19.0 + 'sqlite' is the only supported option if SQLAlchemy is not + installed. schema : string, default None Name of SQL schema in database to write to (if database flavor supports this). If None, use default schema (default). @@ -1545,7 +1549,9 @@ def get_schema(frame, name, flavor=None, keys=None, con=None, dtype=None): library, default: None If a DBAPI2 object, only sqlite3 is supported. flavor : 'sqlite', default None - DEPRECATED: this parameter will be removed in a future version + .. deprecated:: 0.19.0 + 'sqlite' is the only supported option if SQLAlchemy is not + installed. dtype : dict of column name to SQL type, default None Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type, or a string for sqlite3 fallback connection. diff --git a/pandas/io/stata.py b/pandas/io/stata.py index e03e87f09173e..107dccfc8175c 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -110,9 +110,11 @@ _statafile_processing_params2, _chunksize_params, _iterator_params) -_data_method_doc = """Reads observations from Stata file, converting them into a dataframe +_data_method_doc = """\ +Reads observations from Stata file, converting them into a dataframe -This is a legacy method. Use `read` in new code. + .. deprecated:: + This is a legacy method. Use `read` in new code. Parameters ---------- @@ -1407,7 +1409,7 @@ def _read_strls(self): self.GSO[str(v_o)] = va # legacy - @Appender('DEPRECATED: ' + _data_method_doc) + @Appender(_data_method_doc) def data(self, **kwargs): import warnings
- [x] closes #16507 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry XR #6581 for version numbers. Hopefully whitespace is okay.
https://api.github.com/repos/pandas-dev/pandas/pulls/16512
2017-05-26T07:07:31Z
2017-06-27T07:23:40Z
2017-06-27T07:23:40Z
2017-09-11T07:39:30Z
Fix unbound local with bad engine
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 13365401f1d1c..48c2d772ab35f 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -39,6 +39,9 @@ Bug Fixes - Bug in using ``pathlib.Path`` or ``py.path.local`` objects with io functions (:issue:`16291`) - Bug in ``DataFrame.update()`` with ``overwrite=False`` and ``NaN values`` (:issue:`15593`) +- Passing an invalid engine to :func:`read_csv` now raises an informative + ``ValueError`` rather than ``UnboundLocalError``. (:issue:`16511`) + diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index e287d92f67ef6..12b606d969c7d 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -969,6 +969,10 @@ def _make_engine(self, engine='c'): klass = PythonParser elif engine == 'python-fwf': klass = FixedWidthFieldParser + else: + raise ValueError('Unknown engine: {engine} (valid options are' + ' "c", "python", or' ' "python-fwf")'.format( + engine=engine)) self._engine = klass(self.f, **self.options) def _failover_to_python(self): diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index b7d158dd75960..289f86eb2dc53 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -223,3 +223,10 @@ def test_next(self): assert next_line.strip() == line.strip() pytest.raises(StopIteration, next, wrapper) + + def test_unknown_engine(self): + with tm.ensure_clean() as path: + df = tm.makeDataFrame() + df.to_csv(path) + with tm.assert_raises_regex(ValueError, 'Unknown engine'): + read_csv(path, engine='pyt')
This was so small I figured simpler to put up a PR rather than issue then PR. :) Previously, passing a bad engine to read_csv gave an less-than-informative UnboundLocalError: ``` Traceback (most recent call last): File "example_test.py", line 9, in <module> pd.read_csv(tfp.name, engine='pyt') File "/Users/jtratner/pandas/pandas/io/parsers.py", line 655, in parser_f return _read(filepath_or_buffer, kwds) File "/Users/jtratner/pandas/pandas/io/parsers.py", line 405, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "/Users/jtratner/pandas/pandas/io/parsers.py", line 762, in __init__ self._make_engine(self.engine) File "/Users/jtratner/pandas/pandas/io/parsers.py", line 972, in _make_engine self._engine = klass(self.f, **self.options) UnboundLocalError: local variable 'klass' referenced before assignment ``` Now it gives a much nicer ValueError: ``` Traceback (most recent call last): File "example_test.py", line 9, in <module> pd.read_csv(fp, engine='pyt') File "/Users/jtratner/pandas/pandas/io/parsers.py", line 655, in parser_f return _read(filepath_or_buffer, kwds) File "/Users/jtratner/pandas/pandas/io/parsers.py", line 405, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "/Users/jtratner/pandas/pandas/io/parsers.py", line 762, in __init__ self._make_engine(self.engine) File "/Users/jtratner/pandas/pandas/io/parsers.py", line 974, in _make_engine ' or "python-fwf")' % engine) ValueError: Unknown engine: 'pyt' (valid are "c", "python", or "python-fwf") ``` - [x] tests added / passed - added test that correct ValueError is generated - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry I was not sure where to stick the test or the whatsnew entry (or if a whatsnew entry is really necessary), so please tell me if I should move it elsewhere. Cheers!
https://api.github.com/repos/pandas-dev/pandas/pulls/16511
2017-05-26T04:53:34Z
2017-05-31T10:39:46Z
2017-05-31T10:39:46Z
2017-06-04T17:02:56Z
PERF: optimized median func when bottleneck not present
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index fe5342c520196..5fa0c1ff9253f 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -379,6 +379,8 @@ Performance Improvements - Improved performance of :func:`IntervalIndex.symmetric_difference()` (:issue:`18475`) - Improved performance of ``DatetimeIndex`` and ``Series`` arithmetic operations with Business-Month and Business-Quarter frequencies (:issue:`18489`) - :func:`Series` / :func:`DataFrame` tab completion limits to 100 values, for better performance. (:issue:`18587`) +- Improved performance of :func:`DataFrame.median` with ``axis=1`` when bottleneck is not installed (:issue:`16468`) + .. _whatsnew_0230.docs: diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index 7b61cd22f45d1..9a7af71e74574 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -196,24 +196,6 @@ cpdef numeric kth_smallest(numeric[:] a, Py_ssize_t k) nogil: return a[k] -cpdef numeric median(numeric[:] arr): - """ - A faster median - """ - cdef Py_ssize_t n = arr.size - - if n == 0: - return np.NaN - - arr = arr.copy() - - if n % 2: - return kth_smallest(arr, n // 2) - else: - return (kth_smallest(arr, n // 2) + - kth_smallest(arr, n // 2 - 1)) / 2 - - # ---------------------------------------------------------------------- # Pairwise correlation/covariance diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 9d9ac2ef2f5b1..9cc15fb6692d9 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -118,7 +118,7 @@ def group_last_object(ndarray[object, ndim=2] out, out[i, j] = resx[i, j] -cdef inline float64_t _median_linear(float64_t* a, int n) nogil: +cdef inline float64_t median_linear(float64_t* a, int n) nogil: cdef int i, j, na_count = 0 cdef float64_t result cdef float64_t* tmp diff --git a/pandas/_libs/groupby_helper.pxi.in b/pandas/_libs/groupby_helper.pxi.in index 14d47398ac1df..a751fadaf48cf 100644 --- a/pandas/_libs/groupby_helper.pxi.in +++ b/pandas/_libs/groupby_helper.pxi.in @@ -740,7 +740,7 @@ def group_median_float64(ndarray[float64_t, ndim=2] out, ptr += _counts[0] for j in range(ngroups): size = _counts[j + 1] - out[j, i] = _median_linear(ptr, size) + out[j, i] = median_linear(ptr, size) ptr += size diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 63989304bb5f9..eda86f12d501d 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -6,7 +6,7 @@ import numpy as np from pandas import compat -from pandas._libs import tslib, algos, lib +from pandas._libs import tslib, lib from pandas.core.dtypes.common import ( _get_dtype, is_float, is_scalar, @@ -370,14 +370,13 @@ def nanmean(values, axis=None, skipna=True): @bottleneck_switch() def nanmedian(values, axis=None, skipna=True): - values, mask, dtype, dtype_max = _get_values(values, skipna) - def get_median(x): mask = notna(x) if not skipna and not mask.all(): return np.nan - return algos.median(com._values_from_object(x[mask])) + return np.nanmedian(x[mask]) + values, mask, dtype, dtype_max = _get_values(values, skipna) if not is_float_dtype(values): values = values.astype('f8') values[mask] = np.nan @@ -389,10 +388,15 @@ def get_median(x): # an array from a frame if values.ndim > 1: + # there's a non-empty array to apply over otherwise numpy raises if notempty: - return _wrap_results( - np.apply_along_axis(get_median, axis, values), dtype) + if not skipna: + return _wrap_results( + np.apply_along_axis(get_median, axis, values), dtype) + + # fastpath for the skipna case + return _wrap_results(np.nanmedian(values, axis), dtype) # must return the correct shape, but median is not defined for the # empty set so return nans of shape "everything but the passed axis"
closes #16468 Uses np.nanmedian to compute median instead of internal algos.median when bottleneck is not present/turned off. Has order of magnitude performance benefits `df = pd.DataFrame(np.random.randn(10000, 2), columns=list('AB'))` Before ``` >>> pd.set_option('use_bottleneck', False) >>> %timeit df.median(1) 318 ms ± 8.56 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) >>> %timeit pd.Series(np.nanmedian(df.values, axis=1), index=df.index) 1.83 ms ± 123 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) >>> pd.set_option('use_bottleneck', True) >>> %timeit df.median(1) 239 µs ± 2.23 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` After ``` >>> pd.set_option('use_bottleneck', False) >>> %timeit df.median(1) 1.89 ms ± 53.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) >>> pd.set_option('use_bottleneck', True) >>> %timeit df.median(1) 227 µs ± 11 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/16509
2017-05-25T22:10:38Z
2018-01-22T11:11:55Z
2018-01-22T11:11:55Z
2018-01-22T11:11:55Z
Add inplace support for rename_axis
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 36ca79e8b8714..48d835272537f 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -33,6 +33,7 @@ Other Enhancements - The ``validate`` argument for :func:`merge` function now checks whether a merge is one-to-one, one-to-many, many-to-one, or many-to-many. If a merge is found to not be an example of specified merge type, an exception of type ``MergeError`` will be raised. For more, see :ref:`here <merging.validation>` (:issue:`16270`) - ``Series.to_dict()`` and ``DataFrame.to_dict()`` now support an ``into`` keyword which allows you to specify the ``collections.Mapping`` subclass that you would like returned. The default is ``dict``, which is backwards compatible. (:issue:`16122`) - ``RangeIndex.append`` now returns a ``RangeIndex`` object when possible (:issue:`16212`) +- ``Series.rename_axis()`` and ``DataFrame.rename_axis()`` with ``inplace=True`` now return None while renaming the axis inplace. (:issue:`15704`) - :func:`to_pickle` has gained a protocol parameter (:issue:`16252`). By default, this parameter is set to `HIGHEST_PROTOCOL <https://docs.python.org/3/library/pickle.html#data-stream-format>`__ - :func:`api.types.infer_dtype` now infers decimals. (:issue: `15690`) - :func:`read_feather` has gained the ``nthreads`` parameter for multi-threaded operations (:issue:`16359`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 8b186bab29d5e..54ad86b07d4d4 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -753,7 +753,7 @@ def rename_axis(self, mapper, axis=0, copy=True, inplace=False): Returns ------- - renamed : type of caller + renamed : type of caller or None if inplace=True See Also -------- @@ -784,16 +784,16 @@ def rename_axis(self, mapper, axis=0, copy=True, inplace=False): non_mapper = is_scalar(mapper) or (is_list_like(mapper) and not is_dict_like(mapper)) if non_mapper: - return self._set_axis_name(mapper, axis=axis) + return self._set_axis_name(mapper, axis=axis, inplace=inplace) else: axis = self._get_axis_name(axis) d = {'copy': copy, 'inplace': inplace} d[axis] = mapper return self.rename(**d) - def _set_axis_name(self, name, axis=0): + def _set_axis_name(self, name, axis=0, inplace=False): """ - Alter the name or names of the axis, returning self. + Alter the name or names of the axis. Parameters ---------- @@ -801,10 +801,14 @@ def _set_axis_name(self, name, axis=0): Name for the Index, or list of names for the MultiIndex axis : int or str 0 or 'index' for the index; 1 or 'columns' for the columns + inplace : bool + whether to modify `self` directly or return a copy + + .. versionadded: 0.21.0 Returns ------- - renamed : type of caller + renamed : type of caller or None if inplace=True See Also -------- @@ -831,9 +835,11 @@ def _set_axis_name(self, name, axis=0): axis = self._get_axis_number(axis) idx = self._get_axis(axis).set_names(name) - renamed = self.copy(deep=True) + inplace = validate_bool_kwarg(inplace, 'inplace') + renamed = self if inplace else self.copy() renamed.set_axis(axis, idx) - return renamed + if not inplace: + return renamed # ---------------------------------------------------------------------- # Comparisons diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index fbfbcc14e9150..434c02b8eba2f 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -418,6 +418,23 @@ def test_rename(self): pd.Index(['bar', 'foo'], name='name')) assert renamed.index.name == renamer.index.name + def test_rename_axis_inplace(self): + # GH 15704 + frame = self.frame.copy() + expected = frame.rename_axis('foo') + result = frame.copy() + no_return = result.rename_axis('foo', inplace=True) + + assert no_return is None + assert_frame_equal(result, expected) + + expected = frame.rename_axis('bar', axis=1) + result = frame.copy() + no_return = result.rename_axis('bar', axis=1, inplace=True) + + assert no_return is None + assert_frame_equal(result, expected) + def test_rename_multiindex(self): tuples_index = [('foo1', 'bar1'), ('foo2', 'bar2')] diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index 98ae749aaa10e..d93f0326fd3b1 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -224,3 +224,13 @@ def test_reorder_levels(self): result = s.reorder_levels(['L0', 'L0', 'L0']) assert_series_equal(result, expected) + + def test_rename_axis_inplace(self): + # GH 15704 + series = self.ts.copy() + expected = series.rename_axis('foo') + result = series.copy() + no_return = result.rename_axis('foo', inplace=True) + + assert no_return is None + assert_series_equal(result, expected)
- [x] closes #15704 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff``
https://api.github.com/repos/pandas-dev/pandas/pulls/16505
2017-05-25T21:14:54Z
2017-06-13T23:07:52Z
2017-06-13T23:07:52Z
2017-06-13T23:07:59Z
BUG: clip dataframe column-wise #15390
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 5515d093f39e4..ce0d40d327c15 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -135,6 +135,7 @@ Reshaping Numeric ^^^^^^^ +- Bug in ``.clip()`` with ``axis=1`` and a list-like for ``threshold`` is passed; previously this raised ``ValueError`` (:issue:`15390`) Categorical diff --git a/pandas/core/generic.py b/pandas/core/generic.py index db19d9354ec4d..7d1a8adf381fe 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -52,6 +52,7 @@ from pandas.compat.numpy import function as nv from pandas.compat import (map, zip, lzip, lrange, string_types, isidentifier, set_function_name, cPickle as pkl) +from pandas.core.ops import _align_method_FRAME import pandas.core.nanops as nanops from pandas.util._decorators import Appender, Substitution, deprecate_kwarg from pandas.util._validators import validate_bool_kwarg @@ -4413,6 +4414,34 @@ def _clip_with_scalar(self, lower, upper, inplace=False): else: return result + def _clip_with_one_bound(self, threshold, method, axis, inplace): + + inplace = validate_bool_kwarg(inplace, 'inplace') + if axis is not None: + axis = self._get_axis_number(axis) + + if np.any(isnull(threshold)): + raise ValueError("Cannot use an NA value as a clip threshold") + + # method is self.le for upper bound and self.ge for lower bound + if is_scalar(threshold) and is_number(threshold): + if method.__name__ == 'le': + return self._clip_with_scalar(None, threshold, inplace=inplace) + return self._clip_with_scalar(threshold, None, inplace=inplace) + + subset = method(threshold, axis=axis) | isnull(self) + + # GH #15390 + # In order for where method to work, the threshold must + # be transformed to NDFrame from other array like structure. + if (not isinstance(threshold, ABCSeries)) and is_list_like(threshold): + if isinstance(self, ABCSeries): + threshold = pd.Series(threshold, index=self.index) + else: + threshold = _align_method_FRAME(self, np.asarray(threshold), + axis) + return self.where(subset, threshold, axis=axis, inplace=inplace) + def clip(self, lower=None, upper=None, axis=None, inplace=False, *args, **kwargs): """ @@ -4515,16 +4544,8 @@ def clip_upper(self, threshold, axis=None, inplace=False): ------- clipped : same type as input """ - if np.any(isnull(threshold)): - raise ValueError("Cannot use an NA value as a clip threshold") - - if is_scalar(threshold) and is_number(threshold): - return self._clip_with_scalar(None, threshold, inplace=inplace) - - inplace = validate_bool_kwarg(inplace, 'inplace') - - subset = self.le(threshold, axis=axis) | isnull(self) - return self.where(subset, threshold, axis=axis, inplace=inplace) + return self._clip_with_one_bound(threshold, method=self.le, + axis=axis, inplace=inplace) def clip_lower(self, threshold, axis=None, inplace=False): """ @@ -4547,16 +4568,8 @@ def clip_lower(self, threshold, axis=None, inplace=False): ------- clipped : same type as input """ - if np.any(isnull(threshold)): - raise ValueError("Cannot use an NA value as a clip threshold") - - if is_scalar(threshold) and is_number(threshold): - return self._clip_with_scalar(threshold, None, inplace=inplace) - - inplace = validate_bool_kwarg(inplace, 'inplace') - - subset = self.ge(threshold, axis=axis) | isnull(self) - return self.where(subset, threshold, axis=axis, inplace=inplace) + return self._clip_with_one_bound(threshold, method=self.ge, + axis=axis, inplace=inplace) def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs): diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 943a93b27a78a..b09325bfa2ddc 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1892,12 +1892,33 @@ def test_clip_against_series(self, inplace): tm.assert_series_equal(clipped_df.loc[mask, i], df.loc[mask, i]) - def test_clip_against_frame(self): + @pytest.mark.parametrize("inplace", [True, False]) + @pytest.mark.parametrize("lower", [[2, 3, 4], np.asarray([2, 3, 4])]) + @pytest.mark.parametrize("axis,res", [ + (0, [[2., 2., 3.], [4., 5., 6.], [7., 7., 7.]]), + (1, [[2., 3., 4.], [4., 5., 6.], [5., 6., 7.]]) + ]) + def test_clip_against_list_like(self, inplace, lower, axis, res): + # GH #15390 + original = self.simple.copy(deep=True) + + result = original.clip(lower=lower, upper=[5, 6, 7], + axis=axis, inplace=inplace) + + expected = pd.DataFrame(res, + columns=original.columns, + index=original.index) + if inplace: + result = original + tm.assert_frame_equal(result, expected, check_exact=True) + + @pytest.mark.parametrize("axis", [0, 1, None]) + def test_clip_against_frame(self, axis): df = DataFrame(np.random.randn(1000, 2)) lb = DataFrame(np.random.randn(1000, 2)) ub = lb + 1 - clipped_df = df.clip(lb, ub) + clipped_df = df.clip(lb, ub, axis=axis) lb_mask = df <= lb ub_mask = df >= ub diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 18c6c9a6dd021..749af1c56a7f0 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -1015,6 +1015,18 @@ def test_clip_against_series(self): assert_series_equal(s.clip(lower, upper), Series([1.0, 2.0, 3.5])) assert_series_equal(s.clip(1.5, upper), Series([1.5, 1.5, 3.5])) + @pytest.mark.parametrize("inplace", [True, False]) + @pytest.mark.parametrize("upper", [[1, 2, 3], np.asarray([1, 2, 3])]) + def test_clip_against_list_like(self, inplace, upper): + # GH #15390 + original = pd.Series([5, 6, 7]) + result = original.clip(upper=upper, inplace=inplace) + expected = pd.Series([1, 2, 3]) + + if inplace: + result = original + tm.assert_series_equal(result, expected, check_exact=True) + def test_clip_with_datetimes(self): # GH 11838
The bug is due to that `where` doesn't take array-like as argument other, as documented. I just casted array like stuff to Series with appropriate index. - [X] closes #15390 - [X] test_clip_against_list in frame/test_analytics and series/test_analytics - [X] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16504
2017-05-25T20:53:50Z
2017-07-01T08:41:37Z
2017-07-01T08:41:37Z
2017-07-01T08:41:42Z
TST: ujson tests are not being run (#16499)
diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 662f06dbb725e..76fb6d442a25a 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -27,7 +27,7 @@ else partial(json.dumps, encoding="utf-8")) -class UltraJSONTests(object): +class TestUltraJSONTests(object): @pytest.mark.skipif(compat.is_platform_32bit(), reason="not compliant on 32-bit, xref #15865") @@ -944,19 +944,19 @@ def my_obj_handler(obj): ujson.decode(ujson.encode(l, default_handler=str))) -class NumpyJSONTests(object): +class TestNumpyJSONTests(object): - def testBool(self): + def test_Bool(self): b = np.bool(True) assert ujson.decode(ujson.encode(b)) == b - def testBoolArray(self): + def test_BoolArray(self): inpt = np.array([True, False, True, True, False, True, False, False], dtype=np.bool) outp = np.array(ujson.decode(ujson.encode(inpt)), dtype=np.bool) tm.assert_numpy_array_equal(inpt, outp) - def testInt(self): + def test_Int(self): num = np.int(2562010) assert np.int(ujson.decode(ujson.encode(num))) == num @@ -984,7 +984,7 @@ def testInt(self): num = np.uint64(2562010) assert np.uint64(ujson.decode(ujson.encode(num))) == num - def testIntArray(self): + def test_IntArray(self): arr = np.arange(100, dtype=np.int) dtypes = (np.int, np.int8, np.int16, np.int32, np.int64, np.uint, np.uint8, np.uint16, np.uint32, np.uint64) @@ -993,7 +993,7 @@ def testIntArray(self): outp = np.array(ujson.decode(ujson.encode(inpt)), dtype=dtype) tm.assert_numpy_array_equal(inpt, outp) - def testIntMax(self): + def test_IntMax(self): num = np.int(np.iinfo(np.int).max) assert np.int(ujson.decode(ujson.encode(num))) == num @@ -1023,7 +1023,7 @@ def testIntMax(self): num = np.uint64(np.iinfo(np.int64).max) assert np.uint64(ujson.decode(ujson.encode(num))) == num - def testFloat(self): + def test_Float(self): num = np.float(256.2013) assert np.float(ujson.decode(ujson.encode(num))) == num @@ -1033,7 +1033,7 @@ def testFloat(self): num = np.float64(256.2013) assert np.float64(ujson.decode(ujson.encode(num))) == num - def testFloatArray(self): + def test_FloatArray(self): arr = np.arange(12.5, 185.72, 1.7322, dtype=np.float) dtypes = (np.float, np.float32, np.float64) @@ -1043,7 +1043,7 @@ def testFloatArray(self): inpt, double_precision=15)), dtype=dtype) tm.assert_almost_equal(inpt, outp) - def testFloatMax(self): + def test_FloatMax(self): num = np.float(np.finfo(np.float).max / 10) tm.assert_almost_equal(np.float(ujson.decode( ujson.encode(num, double_precision=15))), num, 15) @@ -1056,7 +1056,7 @@ def testFloatMax(self): tm.assert_almost_equal(np.float64(ujson.decode( ujson.encode(num, double_precision=15))), num, 15) - def testArrays(self): + def test_Arrays(self): arr = np.arange(100) arr = arr.reshape((10, 10)) @@ -1097,13 +1097,13 @@ def testArrays(self): outp = ujson.decode(ujson.encode(arr), numpy=True, dtype=np.float32) tm.assert_almost_equal(arr, outp) - def testOdArray(self): + def test_OdArray(self): def will_raise(): ujson.encode(np.array(1)) pytest.raises(TypeError, will_raise) - def testArrayNumpyExcept(self): + def test_ArrayNumpyExcept(self): input = ujson.dumps([42, {}, 'a']) try: @@ -1186,7 +1186,7 @@ def testArrayNumpyExcept(self): except: assert False, "Wrong exception" - def testArrayNumpyLabelled(self): + def test_ArrayNumpyLabelled(self): input = {'a': []} output = ujson.loads(ujson.dumps(input), numpy=True, labelled=True) assert (np.empty((1, 0)) == output[0]).all() @@ -1220,9 +1220,9 @@ def testArrayNumpyLabelled(self): assert (np.array(['a', 'b']) == output[2]).all() -class PandasJSONTests(object): +class TestPandasJSONTests(object): - def testDataFrame(self): + def test_DataFrame(self): df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[ 'a', 'b'], columns=['x', 'y', 'z']) @@ -1252,7 +1252,7 @@ def testDataFrame(self): tm.assert_index_equal(df.transpose().columns, outp.columns) tm.assert_index_equal(df.transpose().index, outp.index) - def testDataFrameNumpy(self): + def test_DataFrameNumpy(self): df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[ 'a', 'b'], columns=['x', 'y', 'z']) @@ -1275,7 +1275,7 @@ def testDataFrameNumpy(self): tm.assert_index_equal(df.transpose().columns, outp.columns) tm.assert_index_equal(df.transpose().index, outp.index) - def testDataFrameNested(self): + def test_DataFrameNested(self): df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[ 'a', 'b'], columns=['x', 'y', 'z']) @@ -1301,7 +1301,7 @@ def testDataFrameNested(self): 'df2': ujson.decode(ujson.encode(df, orient="split"))} assert ujson.decode(ujson.encode(nested, orient="split")) == exp - def testDataFrameNumpyLabelled(self): + def test_DataFrameNumpyLabelled(self): df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[ 'a', 'b'], columns=['x', 'y', 'z']) @@ -1324,7 +1324,7 @@ def testDataFrameNumpyLabelled(self): tm.assert_index_equal(df.columns, outp.columns) tm.assert_index_equal(df.index, outp.index) - def testSeries(self): + def test_Series(self): s = Series([10, 20, 30, 40, 50, 60], name="series", index=[6, 7, 8, 9, 10, 15]).sort_values() @@ -1372,7 +1372,7 @@ def testSeries(self): s, orient="index"), numpy=True)).sort_values() tm.assert_series_equal(outp, exp) - def testSeriesNested(self): + def test_SeriesNested(self): s = Series([10, 20, 30, 40, 50, 60], name="series", index=[6, 7, 8, 9, 10, 15]).sort_values() @@ -1398,7 +1398,7 @@ def testSeriesNested(self): 's2': ujson.decode(ujson.encode(s, orient="index"))} assert ujson.decode(ujson.encode(nested, orient="index")) == exp - def testIndex(self): + def test_Index(self): i = Index([23, 45, 18, 98, 43, 11], name="index") # column indexed
add Test prefix on classes to enable PyTest picking them up. add underscore in test method where applicable. E.G. testBool() to test_Bool(). - [X] closes #16499 - [X] tests added / passed - [X] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16500
2017-05-25T18:33:05Z
2017-05-26T19:11:56Z
2017-05-26T19:11:56Z
2017-05-30T12:20:23Z
DOC: added string processing comparison with SAS
diff --git a/doc/source/comparison_with_sas.rst b/doc/source/comparison_with_sas.rst index 875358521173a..02e0f46d36c84 100644 --- a/doc/source/comparison_with_sas.rst +++ b/doc/source/comparison_with_sas.rst @@ -357,6 +357,146 @@ takes a list of columns to sort by. tips = tips.sort_values(['sex', 'total_bill']) tips.head() + +String Processing +----------------- + +Length +~~~~~~ + +SAS determines the length of a character string with the +`LENGTHN <http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a002284668.htm>`__ +and `LENGTHC <http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a002283942.htm>`__ +functions. ``LENGTHN`` excludes trailing blanks and ``LENGTHC`` includes trailing blanks. + +.. code-block:: none + + data _null_; + set tips; + put(LENGTHN(time)); + put(LENGTHC(time)); + run; + +Python determines the length of a character string with the ``len`` function. +``len`` includes trailing blanks. Use ``len`` and ``rstrip`` to exclude +trailing blanks. + +.. ipython:: python + + tips['time'].str.len().head() + tips['time'].str.rstrip().str.len().head() + + +Find +~~~~ + +SAS determines the position of a character in a string with the +`FINDW <http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a002978282.htm>`__ function. +``FINDW`` takes the string defined by the first argument and searches for the first position of the substring +you supply as the second argument. + +.. code-block:: none + + data _null_; + set tips; + put(FINDW(sex,'ale')); + run; + +Python determines the position of a character in a string with the +``find`` function. ``find`` searches for the first position of the +substring. If the substring is found, the function returns its +position. Keep in mind that Python indexes are zero-based and +the function will return -1 if it fails to find the substring. + +.. ipython:: python + + tips['sex'].str.find("ale").head() + + +Substring +~~~~~~~~~ + +SAS extracts a substring from a string based on its position with the +`SUBSTR <http://www2.sas.com/proceedings/sugi25/25/cc/25p088.pdf>`__ function. + +.. code-block:: none + + data _null_; + set tips; + put(substr(sex,1,1)); + run; + +With pandas you can use ``[]`` notation to extract a substring +from a string by position locations. Keep in mind that Python +indexes are zero-based. + +.. ipython:: python + + tips['sex'].str[0:1].head() + + +Scan +~~~~ + +The SAS `SCAN <http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000214639.htm>`__ +function returns the nth word from a string. The first argument is the string you want to parse and the +second argument specifies which word you want to extract. + +.. code-block:: none + + data firstlast; + input String $60.; + First_Name = scan(string, 1); + Last_Name = scan(string, -1); + datalines2; + John Smith; + Jane Cook; + ;;; + run; + +Python extracts a substring from a string based on its text +by using regular expressions. There are much more powerful +approaches, but this just shows a simple approach. + +.. ipython:: python + + firstlast = pd.DataFrame({'String': ['John Smith', 'Jane Cook']}) + firstlast['First_Name'] = firstlast['String'].str.split(" ", expand=True)[0] + firstlast['Last_Name'] = firstlast['String'].str.rsplit(" ", expand=True)[0] + firstlast + + +Upcase, Lowcase, and Propcase +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The SAS `UPCASE <http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000245965.htm>`__ +`LOWCASE <http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000245912.htm>`__ and +`PROPCASE <http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/a002598106.htm>`__ +functions change the case of the argument. + +.. code-block:: none + + data firstlast; + input String $60.; + string_up = UPCASE(string); + string_low = LOWCASE(string); + string_prop = PROPCASE(string); + datalines2; + John Smith; + Jane Cook; + ;;; + run; + +The equivalent Python functions are ``upper``, ``lower``, and ``title``. + +.. ipython:: python + + firstlast = pd.DataFrame({'String': ['John Smith', 'Jane Cook']}) + firstlast['string_up'] = firstlast['String'].str.upper() + firstlast['string_low'] = firstlast['String'].str.lower() + firstlast['string_prop'] = firstlast['String'].str.title() + firstlast + Merging -------
#13229 Added string processing section to comparison_with_sas DOC. Used info from http://blog.dominodatalab.com/using-r-and-python-for-common-sas-functions. This completes half of the issue. Working on R next.
https://api.github.com/repos/pandas-dev/pandas/pulls/16497
2017-05-25T17:12:21Z
2017-08-07T12:56:54Z
2017-08-07T12:56:54Z
2017-08-07T12:58:36Z
BUG: Fixed tput output on windows
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 86e7812765b40..ea02ed78ea413 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -36,6 +36,8 @@ Performance Improvements Bug Fixes ~~~~~~~~~ +- Silenced a warning on some Windows environments about "tput: terminal attributes: No such device or address" when + detecting the terminal size. This fix only applies to python 3 (:issue:`16496`) - Bug in using ``pathlib.Path`` or ``py.path.local`` objects with io functions (:issue:`16291`) - Bug in ``DataFrame.update()`` with ``overwrite=False`` and ``NaN values`` (:issue:`15593`) diff --git a/pandas/io/formats/terminal.py b/pandas/io/formats/terminal.py index dadd09ae74ea4..30bd1d16b538a 100644 --- a/pandas/io/formats/terminal.py +++ b/pandas/io/formats/terminal.py @@ -14,6 +14,8 @@ from __future__ import print_function import os +import sys +import shutil __all__ = ['get_terminal_size'] @@ -26,6 +28,10 @@ def get_terminal_size(): IPython zmq frontends, or IDLE do not run in a terminal, """ import platform + + if sys.version_info[0] >= 3: + return shutil.get_terminal_size() + current_os = platform.system() tuple_xy = None if current_os == 'Windows':
This came up in [dask]( https://ci.appveyor.com/project/daskdev/dask/build/1.0.1397#L477). For reasons I don't understand, you can end up with a bunch of warnings like `tput: terminal attributes: No such device or address` when pandas calls `get_terminal_size` I was able to monkey patch those calls with `shutil.get_terminal_size` and verify that the warnings were fixed. However that's python3 only. This change uses `shutil.get_terminal_size` when possible, and falls back to our prior implementation otherwise. Not sure about unit tests, but manually, the output matches on my mac.
https://api.github.com/repos/pandas-dev/pandas/pulls/16496
2017-05-25T16:17:09Z
2017-05-30T22:52:56Z
2017-05-30T22:52:56Z
2017-06-04T20:29:32Z
CLN: Small linting failures
diff --git a/pandas/tests/frame/test_combine_concat.py b/pandas/tests/frame/test_combine_concat.py index f32efccf85fc6..e82faaeef2986 100644 --- a/pandas/tests/frame/test_combine_concat.py +++ b/pandas/tests/frame/test_combine_concat.py @@ -778,10 +778,11 @@ def test_update_nan(self): tm.assert_frame_equal(df1, expected) # test 2 - df1 = DataFrame({'A': [1.0, None, 3], 'B': date_range('2000', periods=3)}) + df1 = DataFrame({'A': [1.0, None, 3], + 'B': date_range('2000', periods=3)}) df2 = DataFrame({'A': [None, 2, 3]}) - expected = DataFrame({'A': [1.0, 2, 3], 'B': date_range('2000', periods=3)}) + expected = DataFrame({'A': [1.0, 2, 3], + 'B': date_range('2000', periods=3)}) df1.update(df2, overwrite=False) tm.assert_frame_equal(df1, expected) -
Some slipped in.
https://api.github.com/repos/pandas-dev/pandas/pulls/16491
2017-05-25T02:13:30Z
2017-05-25T03:24:05Z
2017-05-25T03:24:05Z
2017-05-30T12:20:23Z
ENH #15972 added margins_name parameter for crosstab
diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt index a0bf2f9b3758a..9d475390175b2 100644 --- a/doc/source/whatsnew/v0.20.0.txt +++ b/doc/source/whatsnew/v0.20.0.txt @@ -515,7 +515,6 @@ Other Enhancements - Options added to allow one to turn on/off using ``bottleneck`` and ``numexpr``, see :ref:`here <basics.accelerate>` (:issue:`16157`) - ``DataFrame.style.bar()`` now accepts two more options to further customize the bar chart. Bar alignment is set with ``align='left'|'mid'|'zero'``, the default is "left", which is backward compatible; You can now pass a list of ``color=[color_negative, color_positive]``. (:issue:`14757`) - .. _ISO 8601 duration: https://en.wikipedia.org/wiki/ISO_8601#Durations diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index b4ca3f011a81d..a6b6d704737bd 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -37,6 +37,7 @@ Other Enhancements - :func:`api.types.infer_dtype` now infers decimals. (:issue: `15690`) - :func:`read_feather` has gained the ``nthreads`` parameter for multi-threaded operations (:issue:`16359`) - :func:`DataFrame.clip()` and :func: `Series.cip()` have gained an inplace argument. (:issue: `15388`) +- :func:`crosstab` has gained a ``margins_name`` parameter to define the name of the row / column that will contain the totals when margins=True. (:issue:`15972`) .. _whatsnew_0210.api_breaking: diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 74dbbfc00cb11..b562f8a32f5c9 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -388,7 +388,8 @@ def _convert_by(by): def crosstab(index, columns, values=None, rownames=None, colnames=None, - aggfunc=None, margins=False, dropna=True, normalize=False): + aggfunc=None, margins=False, margins_name='All', dropna=True, + normalize=False): """ Compute a simple cross-tabulation of two (or more) factors. By default computes a frequency table of the factors unless an array of values and an @@ -411,6 +412,12 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None, If passed, must match number of column arrays passed margins : boolean, default False Add row/column margins (subtotals) + margins_name : string, default 'All' + Name of the row / column that will contain the totals + when margins is True. + + .. versionadded:: 0.21.0 + dropna : boolean, default True Do not include columns whose entries are all NaN normalize : boolean, {'all', 'index', 'columns'}, or {0,1}, default False @@ -490,23 +497,26 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None, df = DataFrame(data) df['__dummy__'] = 0 table = df.pivot_table('__dummy__', index=rownames, columns=colnames, - aggfunc=len, margins=margins, dropna=dropna) + aggfunc=len, margins=margins, + margins_name=margins_name, dropna=dropna) table = table.fillna(0).astype(np.int64) else: data['__dummy__'] = values df = DataFrame(data) table = df.pivot_table('__dummy__', index=rownames, columns=colnames, - aggfunc=aggfunc, margins=margins, dropna=dropna) + aggfunc=aggfunc, margins=margins, + margins_name=margins_name, dropna=dropna) # Post-process if normalize is not False: - table = _normalize(table, normalize=normalize, margins=margins) + table = _normalize(table, normalize=normalize, margins=margins, + margins_name=margins_name) return table -def _normalize(table, normalize, margins): +def _normalize(table, normalize, margins, margins_name='All'): if not isinstance(normalize, bool) and not isinstance(normalize, compat.string_types): @@ -537,9 +547,9 @@ def _normalize(table, normalize, margins): elif margins is True: - column_margin = table.loc[:, 'All'].drop('All') - index_margin = table.loc['All', :].drop('All') - table = table.drop('All', axis=1).drop('All') + column_margin = table.loc[:, margins_name].drop(margins_name) + index_margin = table.loc[margins_name, :].drop(margins_name) + table = table.drop(margins_name, axis=1).drop(margins_name) # to keep index and columns names table_index_names = table.index.names table_columns_names = table.columns.names @@ -561,7 +571,7 @@ def _normalize(table, normalize, margins): elif normalize == "all" or normalize is True: column_margin = column_margin / column_margin.sum() index_margin = index_margin / index_margin.sum() - index_margin.loc['All'] = 1 + index_margin.loc[margins_name] = 1 table = concat([table, column_margin], axis=1) table = table.append(index_margin) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 270a93e4ae382..fc5a2eb468d4f 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -1071,6 +1071,43 @@ def test_crosstab_margins(self): exp_rows = exp_rows.fillna(0).astype(np.int64) tm.assert_series_equal(all_rows, exp_rows) + def test_crosstab_margins_set_margin_name(self): + # GH 15972 + a = np.random.randint(0, 7, size=100) + b = np.random.randint(0, 3, size=100) + c = np.random.randint(0, 5, size=100) + + df = DataFrame({'a': a, 'b': b, 'c': c}) + + result = crosstab(a, [b, c], rownames=['a'], colnames=('b', 'c'), + margins=True, margins_name='TOTAL') + + assert result.index.names == ('a',) + assert result.columns.names == ['b', 'c'] + + all_cols = result['TOTAL', ''] + exp_cols = df.groupby(['a']).size().astype('i8') + # to keep index.name + exp_margin = Series([len(df)], index=Index(['TOTAL'], name='a')) + exp_cols = exp_cols.append(exp_margin) + exp_cols.name = ('TOTAL', '') + + tm.assert_series_equal(all_cols, exp_cols) + + all_rows = result.loc['TOTAL'] + exp_rows = df.groupby(['b', 'c']).size().astype('i8') + exp_rows = exp_rows.append(Series([len(df)], index=[('TOTAL', '')])) + exp_rows.name = 'TOTAL' + + exp_rows = exp_rows.reindex(all_rows.index) + exp_rows = exp_rows.fillna(0).astype(np.int64) + tm.assert_series_equal(all_rows, exp_rows) + + for margins_name in [666, None, ['a', 'b']]: + with pytest.raises(ValueError): + crosstab(a, [b, c], rownames=['a'], colnames=('b', 'c'), + margins=True, margins_name=margins_name) + def test_crosstab_pass_values(self): a = np.random.randint(0, 7, size=100) b = np.random.randint(0, 3, size=100)
- closes #15972 - 1 tests added / passed - passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16489
2017-05-24T22:55:01Z
2017-05-26T14:43:13Z
2017-05-26T14:43:13Z
2017-05-26T14:43:20Z
DOC: Update to docstring of DataFrame(dtype) (#14764)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 743d623ee5e44..907959c42323e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -241,17 +241,47 @@ class DataFrame(NDFrame): Column labels to use for resulting frame. Will default to np.arange(n) if no column labels are provided dtype : dtype, default None - Data type to force, otherwise infer + Data type to force. Only a single dtype is allowed. If None, infer copy : boolean, default False Copy data from inputs. Only affects DataFrame / 2d ndarray input Examples -------- - >>> d = {'col1': ts1, 'col2': ts2} - >>> df = DataFrame(data=d, index=index) - >>> df2 = DataFrame(np.random.randn(10, 5)) - >>> df3 = DataFrame(np.random.randn(10, 5), - ... columns=['a', 'b', 'c', 'd', 'e']) + Constructing DataFrame from a dictionary. + + >>> d = {'col1': [1, 2], 'col2': [3, 4]} + >>> df = pd.DataFrame(data=d) + >>> df + col1 col2 + 0 1 3 + 1 2 4 + + Notice that the inferred dtype is int64. + + >>> df.dtypes + col1 int64 + col2 int64 + dtype: object + + To enforce a single dtype: + + >>> df = pd.DataFrame(data=d, dtype=np.int8) + >>> df.dtypes + col1 int8 + col2 int8 + dtype: object + + Constructing DataFrame from numpy ndarray: + + >>> df2 = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)), + ... columns=['a', 'b', 'c', 'd', 'e']) + >>> df2 + a b c d e + 0 2 8 8 3 4 + 1 4 2 9 0 9 + 2 1 0 7 8 0 + 3 5 1 7 1 3 + 4 6 0 2 4 2 See also --------
- [ ] closes #14764 - [ ] tests added / passed - [ ] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16487
2017-05-24T21:21:15Z
2017-05-31T08:54:26Z
2017-05-31T08:54:26Z
2017-05-31T15:34:09Z
return empty MultiIndex for symmetrical difference on equal MultiIndexes
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 90146aa176b31..692e0c02606ad 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -40,6 +40,7 @@ Bug Fixes - Silenced a warning on some Windows environments about "tput: terminal attributes: No such device or address" when detecting the terminal size. This fix only applies to python 3 (:issue:`16496`) - Bug in using ``pathlib.Path`` or ``py.path.local`` objects with io functions (:issue:`16291`) +- Bug in ``Index.symmetric_difference()`` on two equal MultiIndex's, results in a TypeError (:issue `13490`) - Bug in ``DataFrame.update()`` with ``overwrite=False`` and ``NaN values`` (:issue:`15593`) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 569e16f2141ae..981a6a696a618 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -414,6 +414,12 @@ def view(self, cls=None): return result def _shallow_copy_with_infer(self, values=None, **kwargs): + # On equal MultiIndexes the difference is empty. + # Therefore, an empty MultiIndex is returned GH13490 + if len(values) == 0: + return MultiIndex(levels=[[] for _ in range(self.nlevels)], + labels=[[] for _ in range(self.nlevels)], + **kwargs) return self._shallow_copy(values, **kwargs) @Appender(_index_shared_docs['_shallow_copy']) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 6a2087b37631e..02561cba784b8 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -188,7 +188,6 @@ def test_constructor_ndarray_like(self): # it should be possible to convert any object that satisfies the numpy # ndarray interface directly into an Index class ArrayLike(object): - def __init__(self, array): self.array = array @@ -246,7 +245,6 @@ def test_index_ctor_infer_nan_nat(self): [np.timedelta64('nat'), np.nan], [pd.NaT, np.timedelta64('nat')], [np.timedelta64('nat'), pd.NaT]]: - tm.assert_index_equal(Index(data), exp) tm.assert_index_equal(Index(np.array(data, dtype=object)), exp) diff --git a/pandas/tests/indexing/test_multiindex.py b/pandas/tests/indexing/test_multiindex.py index 483c39ed8694e..fc6c627075c96 100644 --- a/pandas/tests/indexing/test_multiindex.py +++ b/pandas/tests/indexing/test_multiindex.py @@ -697,6 +697,17 @@ def test_multiindex_slice_first_level(self): index=range(30, 71)) tm.assert_frame_equal(result, expected) + def test_multiindex_symmetric_difference(self): + # GH 13490 + idx = MultiIndex.from_product([['a', 'b'], ['A', 'B']], + names=['a', 'b']) + result = idx ^ idx + assert result.names == idx.names + + idx2 = idx.copy().rename(['A', 'B']) + result = idx ^ idx2 + assert result.names == [None, None] + class TestMultiIndexSlicers(object):
- [X] closes #13490 - [X] tests added / passed - [X] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff``
https://api.github.com/repos/pandas-dev/pandas/pulls/16486
2017-05-24T20:40:41Z
2017-05-31T11:56:52Z
2017-05-31T11:56:52Z
2017-06-04T17:02:56Z
[Issue: #16483] Adding GroupBy Filter to API docs.
diff --git a/doc/source/api.rst b/doc/source/api.rst index cb5136df1ff8b..83abd84d36eb4 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -1738,6 +1738,7 @@ application to columns of a specific data type. DataFrameGroupBy.diff DataFrameGroupBy.ffill DataFrameGroupBy.fillna + DataFrameGroupBy.filter DataFrameGroupBy.hist DataFrameGroupBy.idxmax DataFrameGroupBy.idxmin
- [ ] closes #16483 - [ ] tests added / passed - [ ] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16484
2017-05-24T19:05:07Z
2017-05-24T23:03:46Z
2017-05-24T23:03:46Z
2017-05-24T23:04:11Z
TST: Fix excel test discovery
diff --git a/pandas/io/excel.py b/pandas/io/excel.py index 81a36b21b3617..aa08e5fd378f0 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -8,6 +8,7 @@ import os import abc +import warnings import numpy as np from pandas.core.dtypes.common import ( @@ -30,7 +31,7 @@ import pandas.compat.openpyxl_compat as openpyxl_compat from warnings import warn from distutils.version import LooseVersion -from pandas.util._decorators import Appender, deprecate_kwarg +from pandas.util._decorators import Appender from textwrap import fill __all__ = ["read_excel", "ExcelWriter", "ExcelFile"] @@ -193,7 +194,6 @@ def get_writer(engine_name): raise ValueError("No Excel writer '%s'" % engine_name) -@deprecate_kwarg('sheetname', 'sheet_name') @Appender(_read_excel_doc) def read_excel(io, sheet_name=0, header=0, skiprows=None, skip_footer=0, index_col=None, names=None, parse_cols=None, parse_dates=False, @@ -202,6 +202,15 @@ def read_excel(io, sheet_name=0, header=0, skiprows=None, skip_footer=0, dtype=None, true_values=None, false_values=None, engine=None, squeeze=False, **kwds): + # Can't use _deprecate_kwarg since sheetname=None has a special meaning + if is_integer(sheet_name) and sheet_name == 0 and 'sheetname' in kwds: + warnings.warn("The `sheetname` keyword is deprecated, use " + "`sheet_name` instead", FutureWarning, stacklevel=2) + sheet_name = kwds.pop("sheetname") + elif 'sheetname' in kwds: + raise TypeError("Cannot specify both `sheet_name` and `sheetname`. " + "Use just `sheet_name`") + if not isinstance(io, ExcelFile): io = ExcelFile(io, engine=engine) diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index 0a79d4e8fd81b..4441ed815370b 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -5,6 +5,7 @@ import sys import os from distutils.version import LooseVersion +from functools import partial import warnings from warnings import catch_warnings @@ -407,7 +408,7 @@ def test_reading_all_sheets(self): # Ensure a dict is returned. # See PR #9450 basename = 'test_multisheet' - dfs = self.get_exceldf(basename, sheetname=None) + dfs = self.get_exceldf(basename, sheet_name=None) # ensure this is not alphabetical to test order preservation expected_keys = ['Charlie', 'Alpha', 'Beta'] tm.assert_contains_all(expected_keys, dfs.keys()) @@ -424,7 +425,7 @@ def test_reading_multiple_specific_sheets(self): basename = 'test_multisheet' # Explicitly request duplicates. Only the set should be returned. expected_keys = [2, 'Charlie', 'Charlie'] - dfs = self.get_exceldf(basename, sheetname=expected_keys) + dfs = self.get_exceldf(basename, sheet_name=expected_keys) expected_keys = list(set(expected_keys)) tm.assert_contains_all(expected_keys, dfs.keys()) assert len(expected_keys) == len(dfs.keys()) @@ -434,7 +435,7 @@ def test_reading_all_sheets_with_blank(self): # In the case where some sheets are blank. # Issue #11711 basename = 'blank_with_header' - dfs = self.get_exceldf(basename, sheetname=None) + dfs = self.get_exceldf(basename, sheet_name=None) expected_keys = ['Sheet1', 'Sheet2', 'Sheet3'] tm.assert_contains_all(expected_keys, dfs.keys()) @@ -551,11 +552,15 @@ def test_sheet_name_and_sheetname(self): dfref = self.get_csv_refdf('test1') df1 = self.get_exceldf('test1', sheet_name='Sheet1') # doc with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - df2 = self.get_exceldf('test1', sheetname='Sheet2') # bkwrd compat + df2 = self.get_exceldf('test1', sheetname='Sheet1') # bkwrd compat tm.assert_frame_equal(df1, dfref, check_names=False) tm.assert_frame_equal(df2, dfref, check_names=False) + def test_sheet_name_both_raises(self): + with tm.assert_raises_regex(TypeError, "Cannot specify both"): + self.get_exceldf('test1', sheetname='Sheet1', sheet_name='Sheet1') + class XlrdTests(ReadingTestsBase): """ @@ -589,7 +594,7 @@ def test_read_xlrd_Book(self): result = read_excel(xl, "SheetA") tm.assert_frame_equal(df, result) - result = read_excel(book, sheetname="SheetA", engine="xlrd") + result = read_excel(book, sheet_name="SheetA", engine="xlrd") tm.assert_frame_equal(df, result) @tm.network @@ -691,7 +696,7 @@ def tdf(sheetname): with ExcelWriter(pth) as ew: for sheetname, df in iteritems(dfs): df.to_excel(ew, sheetname) - dfs_returned = read_excel(pth, sheetname=sheets) + dfs_returned = read_excel(pth, sheet_name=sheets) for s in sheets: tm.assert_frame_equal(dfs[s], dfs_returned[s]) @@ -1001,19 +1006,19 @@ def test_read_excel_squeeze(self): tm.assert_series_equal(actual, expected) -class XlsReaderTests(XlrdTests): +class TestXlsReaderTests(XlrdTests): ext = '.xls' engine_name = 'xlrd' check_skip = staticmethod(_skip_if_no_xlrd) -class XlsxReaderTests(XlrdTests): +class TestXlsxReaderTests(XlrdTests): ext = '.xlsx' engine_name = 'xlrd' check_skip = staticmethod(_skip_if_no_xlrd) -class XlsmReaderTests(XlrdTests): +class TestXlsmReaderTests(XlrdTests): ext = '.xlsm' engine_name = 'xlrd' check_skip = staticmethod(_skip_if_no_xlrd) @@ -1872,12 +1877,18 @@ def test_freeze_panes(self): def test_path_pathlib(self): df = tm.makeDataFrame() - result = tm.round_trip_pathlib(df.to_excel, pd.read_excel) + writer = partial(df.to_excel, engine=self.engine_name) + reader = partial(pd.read_excel) + result = tm.round_trip_pathlib(writer, reader, + path="foo.{}".format(self.ext)) tm.assert_frame_equal(df, result) def test_path_localpath(self): df = tm.makeDataFrame() - result = tm.round_trip_localpath(df.to_excel, pd.read_excel) + writer = partial(df.to_excel, engine=self.engine_name) + reader = partial(pd.read_excel) + result = tm.round_trip_pathlib(writer, reader, + path="foo.{}".format(self.ext)) tm.assert_frame_equal(df, result) @@ -1909,7 +1920,7 @@ def versioned_raise_on_incompat_version(cls): @raise_on_incompat_version(1) -class OpenpyxlTests(ExcelWriterBase): +class TestOpenpyxlTests(ExcelWriterBase): ext = '.xlsx' engine_name = 'openpyxl1' check_skip = staticmethod(lambda *args, **kwargs: None) @@ -1962,7 +1973,7 @@ def setup_class(cls): @raise_on_incompat_version(2) @skip_openpyxl_gt21 -class Openpyxl20Tests(ExcelWriterBase): +class TestOpenpyxl20Tests(ExcelWriterBase): ext = '.xlsx' engine_name = 'openpyxl20' check_skip = staticmethod(lambda *args, **kwargs: None) @@ -2078,7 +2089,7 @@ def setup_class(cls): @raise_on_incompat_version(2) @skip_openpyxl_lt22 -class Openpyxl22Tests(ExcelWriterBase): +class TestOpenpyxl22Tests(ExcelWriterBase): ext = '.xlsx' engine_name = 'openpyxl22' check_skip = staticmethod(lambda *args, **kwargs: None) @@ -2173,7 +2184,7 @@ def test_write_cells_merge_styled(self): assert xcell_a2.font == openpyxl_sty_merged -class XlwtTests(ExcelWriterBase): +class TestXlwtTests(ExcelWriterBase): ext = '.xls' engine_name = 'xlwt' check_skip = staticmethod(_skip_if_no_xlwt) @@ -2230,7 +2241,7 @@ def test_to_excel_styleconverter(self): assert xlwt.Alignment.VERT_TOP == xls_style.alignment.vert -class XlsxWriterTests(ExcelWriterBase): +class TestXlsxWriterTests(ExcelWriterBase): ext = '.xlsx' engine_name = 'xlsxwriter' check_skip = staticmethod(_skip_if_no_xlsxwriter) @@ -2283,7 +2294,7 @@ def test_column_format(self): assert read_num_format == num_format -class OpenpyxlTests_NoMerge(ExcelWriterBase): +class TestOpenpyxlTests_NoMerge(ExcelWriterBase): ext = '.xlsx' engine_name = 'openpyxl' check_skip = staticmethod(_skip_if_no_openpyxl) @@ -2292,7 +2303,7 @@ class OpenpyxlTests_NoMerge(ExcelWriterBase): merge_cells = False -class XlwtTests_NoMerge(ExcelWriterBase): +class TestXlwtTests_NoMerge(ExcelWriterBase): ext = '.xls' engine_name = 'xlwt' check_skip = staticmethod(_skip_if_no_xlwt) @@ -2301,7 +2312,7 @@ class XlwtTests_NoMerge(ExcelWriterBase): merge_cells = False -class XlsxWriterTests_NoMerge(ExcelWriterBase): +class TestXlsxWriterTests_NoMerge(ExcelWriterBase): ext = '.xlsx' engine_name = 'xlsxwriter' check_skip = staticmethod(_skip_if_no_xlsxwriter) @@ -2310,7 +2321,7 @@ class XlsxWriterTests_NoMerge(ExcelWriterBase): merge_cells = False -class ExcelWriterEngineTests(object): +class TestExcelWriterEngineTests(object): def test_ExcelWriter_dispatch(self): with tm.assert_raises_regex(ValueError, 'No engine'):
closes #16477 Locally: ``` ======================================== 26 failed, 358 passed, 48 skipped, 1 xfailed, 61 warnings in 20.85 seconds ======================================== ```
https://api.github.com/repos/pandas-dev/pandas/pulls/16478
2017-05-24T12:04:01Z
2017-05-26T12:48:06Z
2017-05-26T12:48:06Z
2017-05-29T20:43:32Z
ENH: add nthreads option to feather-format IO
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 4cb55ec6b117b..13e0d677b79e8 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -35,6 +35,7 @@ Other Enhancements - ``RangeIndex.append`` now returns a ``RangeIndex`` object when possible (:issue:`16212`) - :func:`to_pickle` has gained a protocol parameter (:issue:`16252`). By default, this parameter is set to `HIGHEST_PROTOCOL <https://docs.python.org/3/library/pickle.html#data-stream-format>`__ - :func:`api.types.infer_dtype` now infers decimals. (:issue: `15690`) +- :func:`read_feather` has gained the ``nthreads`` parameter for multi-threaded operations (:issue:`16359`) .. _whatsnew_0210.api_breaking: diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index 8bdb23fc1ae6a..86d58caa5e816 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -43,6 +43,7 @@ def to_feather(df, path): df : DataFrame path : string File path + """ path = _stringify_path(path) if not isinstance(df, DataFrame): @@ -83,7 +84,7 @@ def to_feather(df, path): feather.write_dataframe(df, path) -def read_feather(path): +def read_feather(path, nthreads=1): """ Load a feather-format object from the file path @@ -93,6 +94,10 @@ def read_feather(path): ---------- path : string File path + nthreads : int, default 1 + Number of CPU threads to use when reading to pandas.DataFrame + + .. versionadded 0.21.0 Returns ------- @@ -102,4 +107,8 @@ def read_feather(path): feather = _try_import() path = _stringify_path(path) - return feather.read_dataframe(path) + + if feather.__version__ < LooseVersion('0.4.0'): + return feather.read_dataframe(path) + + return feather.read_dataframe(path, nthreads=nthreads) diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 42ad9d3e0d8fe..dadfe7ca87e48 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -27,11 +27,11 @@ def check_error_on_write(self, df, exc): with ensure_clean() as path: to_feather(df, path) - def check_round_trip(self, df): + def check_round_trip(self, df, **kwargs): with ensure_clean() as path: to_feather(df, path) - result = read_feather(path) + result = read_feather(path, **kwargs) assert_frame_equal(result, df) def test_error(self): @@ -98,6 +98,12 @@ def test_unsupported_other(self): df = pd.DataFrame({'a': pd.period_range('2013', freq='M', periods=3)}) self.check_error_on_write(df, ValueError) + @pytest.mark.skipif(fv < '0.4.0', reason='new in 0.4.0') + def test_rw_nthreads(self): + + df = pd.DataFrame({'A': np.arange(100000)}) + self.check_round_trip(df, nthreads=2) + def test_write_with_index(self): df = pd.DataFrame({'A': [1, 2, 3]})
closes #16359
https://api.github.com/repos/pandas-dev/pandas/pulls/16476
2017-05-24T10:37:02Z
2017-05-24T22:48:12Z
2017-05-24T22:48:11Z
2017-05-24T22:49:36Z
COMPAT: feather-format 0.4.0 compat
diff --git a/ci/requirements-3.5_OSX.sh b/ci/requirements-3.5_OSX.sh index cfbd2882a8a2d..39ea1a0cf67bf 100644 --- a/ci/requirements-3.5_OSX.sh +++ b/ci/requirements-3.5_OSX.sh @@ -4,4 +4,4 @@ source activate pandas echo "install 35_OSX" -conda install -n pandas -c conda-forge feather-format +conda install -n pandas -c conda-forge feather-format==0.3.1 diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 948ab736af6c6..42ad9d3e0d8fe 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -10,6 +10,10 @@ from feather import FeatherError from pandas.util.testing import assert_frame_equal, ensure_clean import pandas.util.testing as tm +from distutils.version import LooseVersion + + +fv = LooseVersion(feather.__version__) @pytest.mark.single @@ -57,6 +61,7 @@ def test_basic(self): assert df.dttz.dtype.tz.zone == 'US/Eastern' self.check_round_trip(df) + @pytest.mark.skipif(fv >= '0.4.0', reason='fixed in 0.4.0') def test_strided_data_issues(self): # strided data issuehttps://github.com/wesm/feather/issues/97 @@ -76,12 +81,10 @@ def test_stringify_columns(self): df = pd.DataFrame(np.arange(12).reshape(4, 3)).copy() self.check_error_on_write(df, ValueError) + @pytest.mark.skipif(fv >= '0.4.0', reason='fixed in 0.4.0') def test_unsupported(self): - # period - df = pd.DataFrame({'a': pd.period_range('2013', freq='M', periods=3)}) - self.check_error_on_write(df, ValueError) - + # timedelta df = pd.DataFrame({'a': pd.timedelta_range('1 day', periods=3)}) self.check_error_on_write(df, FeatherError) @@ -89,6 +92,12 @@ def test_unsupported(self): df = pd.DataFrame({'a': ['a', 1, 2.0]}) self.check_error_on_write(df, ValueError) + def test_unsupported_other(self): + + # period + df = pd.DataFrame({'a': pd.period_range('2013', freq='M', periods=3)}) + self.check_error_on_write(df, ValueError) + def test_write_with_index(self): df = pd.DataFrame({'A': [1, 2, 3]})
https://api.github.com/repos/pandas-dev/pandas/pulls/16475
2017-05-24T10:14:29Z
2017-05-24T10:35:21Z
2017-05-24T10:35:21Z
2017-05-30T12:22:44Z
TST: Fix test assertions
diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py index 7912b4bf3bdf6..47e6e7839422a 100644 --- a/pandas/tests/groupby/test_nth.py +++ b/pandas/tests/groupby/test_nth.py @@ -153,8 +153,8 @@ def test_nth(self): expected = s.groupby(g).first() expected2 = s.groupby(g).apply(lambda x: x.iloc[0]) assert_series_equal(expected2, expected, check_names=False) - assert expected.name, 0 assert expected.name == 1 + assert expected2.name == 1 # validate first v = s[g == 1].iloc[0] diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index 61f7ac8abaf09..a47db755b44af 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -625,7 +625,7 @@ def test_to_datetime_iso8601(self): def test_to_datetime_default(self): rs = to_datetime('2001') xp = datetime(2001, 1, 1) - assert rs, xp + assert rs == xp # dayfirst is essentially broken diff --git a/pandas/tests/indexes/period/test_construction.py b/pandas/tests/indexes/period/test_construction.py index 6a188c0987f91..e5b889e100307 100644 --- a/pandas/tests/indexes/period/test_construction.py +++ b/pandas/tests/indexes/period/test_construction.py @@ -135,15 +135,15 @@ def test_constructor_fromarraylike(self): result = PeriodIndex(idx, freq=offsets.MonthEnd()) tm.assert_index_equal(result, idx) - assert result.freq, 'M' + assert result.freq == 'M' result = PeriodIndex(idx, freq='2M') tm.assert_index_equal(result, idx.asfreq('2M')) - assert result.freq, '2M' + assert result.freq == '2M' result = PeriodIndex(idx, freq=offsets.MonthEnd(2)) tm.assert_index_equal(result, idx.asfreq('2M')) - assert result.freq, '2M' + assert result.freq == '2M' result = PeriodIndex(idx, freq='D') exp = idx.asfreq('D', 'e') diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py index d140a2503984e..c7af0954cf483 100644 --- a/pandas/tests/indexes/test_range.py +++ b/pandas/tests/indexes/test_range.py @@ -172,16 +172,16 @@ def test_constructor_name(self): copy = RangeIndex(orig) copy.name = 'copy' - assert orig.name, 'original' - assert copy.name, 'copy' + assert orig.name == 'original' + assert copy.name == 'copy' new = Index(copy) - assert new.name, 'copy' + assert new.name == 'copy' new.name = 'new' - assert orig.name, 'original' - assert new.name, 'copy' - assert new.name, 'new' + assert orig.name == 'original' + assert copy.name == 'copy' + assert new.name == 'new' def test_numeric_compat2(self): # validate that we are handling the RangeIndex overrides to numeric ops @@ -273,7 +273,7 @@ def test_repr(self): expected = "RangeIndex(start=0, stop=5, step=1, name='Foo')" else: expected = "RangeIndex(start=0, stop=5, step=1, name=u'Foo')" - assert result, expected + assert result == expected result = eval(result) tm.assert_index_equal(result, i, exact=True) diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 92537059218d6..cff83c2ff0a3a 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -843,7 +843,7 @@ def test_to_weekly_resampling(self): tsplot(high, plt.Axes.plot) lines = tsplot(low, plt.Axes.plot) for l in lines: - assert PeriodIndex(data=l.get_xdata()).freq, idxh.freq + assert PeriodIndex(data=l.get_xdata()).freq == idxh.freq @slow def test_from_weekly_resampling(self): @@ -858,7 +858,7 @@ def test_from_weekly_resampling(self): expected_l = np.array([1514, 1519, 1523, 1527, 1531, 1536, 1540, 1544, 1549, 1553, 1558, 1562], dtype=np.float64) for l in ax.get_lines(): - assert PeriodIndex(data=l.get_xdata()).freq, idxh.freq + assert PeriodIndex(data=l.get_xdata()).freq == idxh.freq xdata = l.get_xdata(orig=False) if len(xdata) == 12: # idxl lines tm.assert_numpy_array_equal(xdata, expected_l) @@ -873,7 +873,7 @@ def test_from_weekly_resampling(self): tsplot(low, plt.Axes.plot) lines = tsplot(high, plt.Axes.plot) for l in lines: - assert PeriodIndex(data=l.get_xdata()).freq, idxh.freq + assert PeriodIndex(data=l.get_xdata()).freq == idxh.freq xdata = l.get_xdata(orig=False) if len(xdata) == 12: # idxl lines tm.assert_numpy_array_equal(xdata, expected_l) diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index d5517bdcceac7..6018260708335 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -916,7 +916,7 @@ def test_from_M8_structured(self): assert df['Forecasting'][0] == dates[0][1] s = Series(arr['Date']) - assert s[0], Timestamp + assert isinstance(s[0], Timestamp) assert s[0] == dates[0][0] s = Series.from_array(arr['Date'], Index([0])) diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py index df97095035952..6be687e26e985 100644 --- a/pandas/tests/test_lib.py +++ b/pandas/tests/test_lib.py @@ -13,15 +13,15 @@ class TestMisc(object): def test_max_len_string_array(self): arr = a = np.array(['foo', 'b', np.nan], dtype='object') - assert lib.max_len_string_array(arr), 3 + assert lib.max_len_string_array(arr) == 3 # unicode arr = a.astype('U').astype(object) - assert lib.max_len_string_array(arr), 3 + assert lib.max_len_string_array(arr) == 3 # bytes for python3 arr = a.astype('S').astype(object) - assert lib.max_len_string_array(arr), 3 + assert lib.max_len_string_array(arr) == 3 # raises pytest.raises(TypeError, diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index f28a5926087ac..bb31fb9260160 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -2102,12 +2102,12 @@ def test_split_with_name(self): idx = Index(['a,b', 'c,d'], name='xxx') res = idx.str.split(',') exp = Index([['a', 'b'], ['c', 'd']], name='xxx') - assert res.nlevels, 1 + assert res.nlevels == 1 tm.assert_index_equal(res, exp) res = idx.str.split(',', expand=True) exp = MultiIndex.from_tuples([('a', 'b'), ('c', 'd')]) - assert res.nlevels, 2 + assert res.nlevels == 2 tm.assert_index_equal(res, exp) def test_partition_series(self): @@ -2247,13 +2247,13 @@ def test_partition_with_name(self): idx = Index(['a,b', 'c,d'], name='xxx') res = idx.str.partition(',') exp = MultiIndex.from_tuples([('a', ',', 'b'), ('c', ',', 'd')]) - assert res.nlevels, 3 + assert res.nlevels == 3 tm.assert_index_equal(res, exp) # should preserve name res = idx.str.partition(',', expand=False) exp = Index(np.array([('a', ',', 'b'), ('c', ',', 'd')]), name='xxx') - assert res.nlevels, 1 + assert res.nlevels == 1 tm.assert_index_equal(res, exp) def test_pipe_failures(self):
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry This fixes some test assertions that were only checking the truthiness of a value when they should have been comparing two values. Initially, through typos, tests were written using assertTrue when they should have been using assertEqual. The second argument to assertTrue was being treated as a message instead of as the expected value. More recently, these assertions with typos were transformed to use `assert`, with the same problems persisting. I have fixed each of the problems I found on a case-by-case basis. Some lines required more complicated fixes, like adding instanceof() or fixing an expected value. I believe I have found all such instances of this error, because I reviewed all the locations where assertTrue was called with two arguments.
https://api.github.com/repos/pandas-dev/pandas/pulls/16470
2017-05-24T03:23:29Z
2017-05-24T10:38:03Z
2017-05-24T10:38:03Z
2017-05-24T10:38:07Z
DOC: add examples to set_index method
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 78a369761afc1..574db33d93b36 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2947,9 +2947,44 @@ def set_index(self, keys, drop=True, append=False, inplace=False, Examples -------- - >>> indexed_df = df.set_index(['A', 'B']) - >>> indexed_df2 = df.set_index(['A', [0, 1, 2, 0, 1, 2]]) - >>> indexed_df3 = df.set_index([[0, 1, 2, 0, 1, 2]]) + >>> df = pd.DataFrame({'month': [1, 4, 7, 10], + ... 'year': [2012, 2014, 2013, 2014], + ... 'sale':[55, 40, 84, 31]}) + month sale year + 0 1 55 2012 + 1 4 40 2014 + 2 7 84 2013 + 3 10 31 2014 + + Set the index to become the 'month' column: + + >>> df.set_index('month') + sale year + month + 1 55 2012 + 4 40 2014 + 7 84 2013 + 10 31 2014 + + Create a multi-index using columns 'year' and 'month': + + >>> df.set_index(['year', 'month']) + sale + year month + 2012 1 55 + 2014 4 40 + 2013 7 84 + 2014 10 31 + + Create a multi-index using a set of values and a column: + + >>> df.set_index([[1, 2, 3, 4], 'year']) + month sale + year + 1 2012 1 55 + 2 2014 4 40 + 3 2013 7 84 + 4 2014 10 31 Returns -------
- [x] related to #16416 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry Added better examples in the doc for the dataframe set_index() method.
https://api.github.com/repos/pandas-dev/pandas/pulls/16467
2017-05-23T23:04:04Z
2017-05-25T02:19:33Z
2017-05-25T02:19:33Z
2017-05-26T17:28:26Z
ENH: Add to_latex() method to Series (#16180)
diff --git a/doc/source/api.rst b/doc/source/api.rst index cb5136df1ff8b..e7d12df56d260 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -724,6 +724,7 @@ Serialization / IO / Conversion Series.to_dense Series.to_string Series.to_clipboard + Series.to_latex Sparse ~~~~~~ diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index e24b0c229c46c..8c58a9e590f23 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -20,6 +20,7 @@ Enhancements ~~~~~~~~~~~~ - Unblocked access to additional compression types supported in pytables: 'blosc:blosclz, 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy', 'blosc:zlib', 'blosc:zstd' (:issue:`14478`) +- ``Series`` provides a ``to_latex`` method (:issue:`16180`) .. _whatsnew_0202.performance: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 78a369761afc1..c1f13f8883bd5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -634,16 +634,6 @@ def _repr_html_(self): else: return None - def _repr_latex_(self): - """ - Returns a LaTeX representation for a particular Dataframe. - Mainly for use with nbconvert (jupyter notebook conversion to pdf). - """ - if get_option('display.latex.repr'): - return self.to_latex() - else: - return None - @property def style(self): """ @@ -1663,94 +1653,6 @@ def to_html(self, buf=None, columns=None, col_space=None, header=True, if buf is None: return formatter.buf.getvalue() - @Substitution(header='Write out column names. If a list of string is given, \ -it is assumed to be aliases for the column names.') - @Appender(fmt.common_docstring + fmt.return_docstring, indents=1) - def to_latex(self, buf=None, columns=None, col_space=None, header=True, - index=True, na_rep='NaN', formatters=None, float_format=None, - sparsify=None, index_names=True, bold_rows=True, - column_format=None, longtable=None, escape=None, - encoding=None, decimal='.', multicolumn=None, - multicolumn_format=None, multirow=None): - r""" - Render a DataFrame to a tabular environment table. You can splice - this into a LaTeX document. Requires \usepackage{booktabs}. - - `to_latex`-specific options: - - bold_rows : boolean, default True - Make the row labels bold in the output - column_format : str, default None - The columns format as specified in `LaTeX table format - <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g 'rcl' for 3 - columns - longtable : boolean, default will be read from the pandas config module - Default: False. - Use a longtable environment instead of tabular. Requires adding - a \usepackage{longtable} to your LaTeX preamble. - escape : boolean, default will be read from the pandas config module - Default: True. - When set to False prevents from escaping latex special - characters in column names. - encoding : str, default None - A string representing the encoding to use in the output file, - defaults to 'ascii' on Python 2 and 'utf-8' on Python 3. - decimal : string, default '.' - Character recognized as decimal separator, e.g. ',' in Europe. - - .. versionadded:: 0.18.0 - - multicolumn : boolean, default True - Use \multicolumn to enhance MultiIndex columns. - The default will be read from the config module. - - .. versionadded:: 0.20.0 - - multicolumn_format : str, default 'l' - The alignment for multicolumns, similar to `column_format` - The default will be read from the config module. - - .. versionadded:: 0.20.0 - - multirow : boolean, default False - Use \multirow to enhance MultiIndex rows. - Requires adding a \usepackage{multirow} to your LaTeX preamble. - Will print centered labels (instead of top-aligned) - across the contained rows, separating groups via clines. - The default will be read from the pandas config module. - - .. versionadded:: 0.20.0 - - """ - # Get defaults from the pandas config - if longtable is None: - longtable = get_option("display.latex.longtable") - if escape is None: - escape = get_option("display.latex.escape") - if multicolumn is None: - multicolumn = get_option("display.latex.multicolumn") - if multicolumn_format is None: - multicolumn_format = get_option("display.latex.multicolumn_format") - if multirow is None: - multirow = get_option("display.latex.multirow") - - formatter = fmt.DataFrameFormatter(self, buf=buf, columns=columns, - col_space=col_space, na_rep=na_rep, - header=header, index=index, - formatters=formatters, - float_format=float_format, - bold_rows=bold_rows, - sparsify=sparsify, - index_names=index_names, - escape=escape, decimal=decimal) - formatter.to_latex(column_format=column_format, longtable=longtable, - encoding=encoding, multicolumn=multicolumn, - multicolumn_format=multicolumn_format, - multirow=multirow) - - if buf is None: - return formatter.buf.getvalue() - def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None): """ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2e7d8693d48dd..594b637c7e5fa 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -45,7 +45,7 @@ import pandas.core.common as com import pandas.core.missing as missing from pandas.io.formats.printing import pprint_thing -from pandas.io.formats.format import format_percentiles +from pandas.io.formats.format import format_percentiles, DataFrameFormatter from pandas.tseries.frequencies import to_offset from pandas import compat from pandas.compat.numpy import function as nv @@ -1050,6 +1050,16 @@ def __setstate__(self, state): # ---------------------------------------------------------------------- # IO + def _repr_latex_(self): + """ + Returns a LaTeX representation for a particular object. + Mainly for use with nbconvert (jupyter notebook conversion to pdf). + """ + if config.get_option('display.latex.repr'): + return self.to_latex() + else: + return None + # ---------------------------------------------------------------------- # I/O Methods @@ -1502,6 +1512,100 @@ def to_xarray(self): coords=coords, ) + _shared_docs['to_latex'] = """ + Render an object to a tabular environment table. You can splice + this into a LaTeX document. Requires \\usepackage{booktabs}. + + .. versionchanged:: 0.20.2 + Added to Series + + `to_latex`-specific options: + + bold_rows : boolean, default True + Make the row labels bold in the output + column_format : str, default None + The columns format as specified in `LaTeX table format + <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g 'rcl' for 3 + columns + longtable : boolean, default will be read from the pandas config module + Default: False. + Use a longtable environment instead of tabular. Requires adding + a \\usepackage{longtable} to your LaTeX preamble. + escape : boolean, default will be read from the pandas config module + Default: True. + When set to False prevents from escaping latex special + characters in column names. + encoding : str, default None + A string representing the encoding to use in the output file, + defaults to 'ascii' on Python 2 and 'utf-8' on Python 3. + decimal : string, default '.' + Character recognized as decimal separator, e.g. ',' in Europe. + + .. versionadded:: 0.18.0 + + multicolumn : boolean, default True + Use \multicolumn to enhance MultiIndex columns. + The default will be read from the config module. + + .. versionadded:: 0.20.0 + + multicolumn_format : str, default 'l' + The alignment for multicolumns, similar to `column_format` + The default will be read from the config module. + + .. versionadded:: 0.20.0 + + multirow : boolean, default False + Use \multirow to enhance MultiIndex rows. + Requires adding a \\usepackage{multirow} to your LaTeX preamble. + Will print centered labels (instead of top-aligned) + across the contained rows, separating groups via clines. + The default will be read from the pandas config module. + + .. versionadded:: 0.20.0 + """ + + @Substitution(header='Write out column names. If a list of string is given, \ +it is assumed to be aliases for the column names.') + @Appender(_shared_docs['to_latex'] % _shared_doc_kwargs) + def to_latex(self, buf=None, columns=None, col_space=None, header=True, + index=True, na_rep='NaN', formatters=None, float_format=None, + sparsify=None, index_names=True, bold_rows=True, + column_format=None, longtable=None, escape=None, + encoding=None, decimal='.', multicolumn=None, + multicolumn_format=None, multirow=None): + # Get defaults from the pandas config + if self.ndim == 1: + self = self.to_frame() + if longtable is None: + longtable = config.get_option("display.latex.longtable") + if escape is None: + escape = config.get_option("display.latex.escape") + if multicolumn is None: + multicolumn = config.get_option("display.latex.multicolumn") + if multicolumn_format is None: + multicolumn_format = config.get_option( + "display.latex.multicolumn_format") + if multirow is None: + multirow = config.get_option("display.latex.multirow") + + formatter = DataFrameFormatter(self, buf=buf, columns=columns, + col_space=col_space, na_rep=na_rep, + header=header, index=index, + formatters=formatters, + float_format=float_format, + bold_rows=bold_rows, + sparsify=sparsify, + index_names=index_names, + escape=escape, decimal=decimal) + formatter.to_latex(column_format=column_format, longtable=longtable, + encoding=encoding, multicolumn=multicolumn, + multicolumn_format=multicolumn_format, + multirow=multirow) + + if buf is None: + return formatter.buf.getvalue() + # ---------------------------------------------------------------------- # Fancy Indexing diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index 2542deb0cedf1..4ee77abb32c26 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -3,7 +3,7 @@ import pytest import pandas as pd -from pandas import DataFrame, compat +from pandas import DataFrame, compat, Series from pandas.util import testing as tm from pandas.compat import u import codecs @@ -491,3 +491,18 @@ def test_to_latex_decimal(self, frame): """ assert withindex_result == withindex_expected + + def test_to_latex_series(self): + s = Series(['a', 'b', 'c']) + withindex_result = s.to_latex() + withindex_expected = r"""\begin{tabular}{ll} +\toprule +{} & 0 \\ +\midrule +0 & a \\ +1 & b \\ +2 & c \\ +\bottomrule +\end{tabular} +""" + assert withindex_result == withindex_expected diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py index 3af61b0a902d3..c22e2ca8e0dc8 100644 --- a/pandas/tests/series/test_repr.py +++ b/pandas/tests/series/test_repr.py @@ -8,7 +8,7 @@ import numpy as np import pandas as pd -from pandas import (Index, Series, DataFrame, date_range) +from pandas import (Index, Series, DataFrame, date_range, option_context) from pandas.core.index import MultiIndex from pandas.compat import lrange, range, u @@ -180,3 +180,21 @@ def test_timeseries_repr_object_dtype(self): ts2 = ts.iloc[np.random.randint(0, len(ts) - 1, 400)] repr(ts2).splitlines()[-1] + + def test_latex_repr(self): + result = r"""\begin{tabular}{ll} +\toprule +{} & 0 \\ +\midrule +0 & $\alpha$ \\ +1 & b \\ +2 & c \\ +\bottomrule +\end{tabular} +""" + with option_context('display.latex.escape', False, + 'display.latex.repr', True): + s = Series([r'$\alpha$', 'b', 'c']) + assert result == s._repr_latex_() + + assert s._repr_latex_() is None
This changeset adds _repr_latex_ to the Series class and moves the to_latex() method from the DataFrame class to the NDFrame class. - [ ] closes #16180 - [ ] tests added / passed - [ ] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16465
2017-05-23T22:41:59Z
2017-05-26T11:47:45Z
2017-05-26T11:47:44Z
2017-05-30T12:20:22Z
BUG: writing invalid table names to sqlite
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 7b3717281bf89..a6ad44ba31422 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -816,6 +816,16 @@ def test_unicode_column_name(self): df = DataFrame([[1, 2], [3, 4]], columns=[u'\xe9', u'b']) df.to_sql('test_unicode', self.conn, index=False) + def test_escaped_table_name(self): + # GH 13206 + df = DataFrame({'A': [0, 1, 2], 'B': [0.2, np.nan, 5.6]}) + df.to_sql('d1187b08-4943-4c8d-a7f6', self.conn, index=False) + + res = sql.read_sql_query('SELECT * FROM `d1187b08-4943-4c8d-a7f6`', + self.conn) + + tm.assert_frame_equal(res, df) + @pytest.mark.single class TestSQLApi(SQLAlchemyMixIn, _TestSQLApi):
I verified that the test exposes the bug prior to the fix for bug #13206. Pandas from master ``` >>> import sqlite3 >>> import pandas as pd >>> import numpy as np >>> conn = sqlite3.connect(':memory:') >>> df = pd.DataFrame({'A': [0, 1, 2], 'B': [0.2, np.nan, 5.6]}) >>> df.to_sql('d1187b08-4943-4c8d-a7f6-6c06b7cb9509', conn, index=False) >>> ``` Pandas 0.13.1 ``` >>> import sqlite3 >>> import pandas as pd >>> import numpy as np >>> conn = sqlite3.connect(':memory:') >>> df = pd.DataFrame({'A': [0, 1, 2], 'B': [0.2, np.nan, 5.6]}) >>> df.to_sql('d1187b08-4943-4c8d-a7f6-6c06b7cb9509', conn, index=False) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Projects\Sprints\PandasVirtualEnvLatest\PandasVirtualEnvLatest\oldpy27\lib\site-packages\pandas\core\frame.py", line 1261, in to_sql self, name, con, flavor=flavor, if_exists=if_exists, **kwargs) File "C:\Projects\Sprints\PandasVirtualEnvLatest\PandasVirtualEnvLatest\oldpy27\lib\site-packages\pandas\io\sql.py", line 226, in write_frame cur.execute(create) OperationalError: near "-": syntax error >>> ```
https://api.github.com/repos/pandas-dev/pandas/pulls/16464
2017-05-23T22:03:08Z
2017-06-01T19:31:53Z
2017-06-01T19:31:53Z
2017-06-01T19:32:11Z
ENH: Support inplace clip (#15388)
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index f1289c490e4fb..b4ca3f011a81d 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -36,6 +36,7 @@ Other Enhancements - :func:`to_pickle` has gained a protocol parameter (:issue:`16252`). By default, this parameter is set to `HIGHEST_PROTOCOL <https://docs.python.org/3/library/pickle.html#data-stream-format>`__ - :func:`api.types.infer_dtype` now infers decimals. (:issue: `15690`) - :func:`read_feather` has gained the ``nthreads`` parameter for multi-threaded operations (:issue:`16359`) +- :func:`DataFrame.clip()` and :func: `Series.cip()` have gained an inplace argument. (:issue: `15388`) .. _whatsnew_0210.api_breaking: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index b19a0751ea2e4..f8da6851d18bc 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4120,8 +4120,7 @@ def isnull(self): def notnull(self): return notnull(self).__finalize__(self) - def _clip_with_scalar(self, lower, upper): - + def _clip_with_scalar(self, lower, upper, inplace=False): if ((lower is not None and np.any(isnull(lower))) or (upper is not None and np.any(isnull(upper)))): raise ValueError("Cannot use an NA value as a clip threshold") @@ -4137,10 +4136,16 @@ def _clip_with_scalar(self, lower, upper): if np.any(mask): result[mask] = np.nan - return self._constructor( - result, **self._construct_axes_dict()).__finalize__(self) + axes_dict = self._construct_axes_dict() + result = self._constructor(result, **axes_dict).__finalize__(self) + + if inplace: + self._update_inplace(result) + else: + return result - def clip(self, lower=None, upper=None, axis=None, *args, **kwargs): + def clip(self, lower=None, upper=None, axis=None, inplace=False, + *args, **kwargs): """ Trim values at input threshold(s). @@ -4150,6 +4155,9 @@ def clip(self, lower=None, upper=None, axis=None, *args, **kwargs): upper : float or array_like, default None axis : int or string axis name, optional Align object with lower and upper along the given axis. + inplace : boolean, default False + Whether to perform the operation in place on the data + .. versionadded:: 0.21.0 Returns ------- @@ -4192,6 +4200,8 @@ def clip(self, lower=None, upper=None, axis=None, *args, **kwargs): if isinstance(self, ABCPanel): raise NotImplementedError("clip is not supported yet for panels") + inplace = validate_bool_kwarg(inplace, 'inplace') + axis = nv.validate_clip_with_axis(axis, args, kwargs) # GH 2747 (arguments were reversed) @@ -4202,17 +4212,20 @@ def clip(self, lower=None, upper=None, axis=None, *args, **kwargs): # fast-path for scalars if ((lower is None or (is_scalar(lower) and is_number(lower))) and (upper is None or (is_scalar(upper) and is_number(upper)))): - return self._clip_with_scalar(lower, upper) + return self._clip_with_scalar(lower, upper, inplace=inplace) result = self if lower is not None: - result = result.clip_lower(lower, axis) + result = result.clip_lower(lower, axis, inplace=inplace) if upper is not None: - result = result.clip_upper(upper, axis) + if inplace: + result = self + + result = result.clip_upper(upper, axis, inplace=inplace) return result - def clip_upper(self, threshold, axis=None): + def clip_upper(self, threshold, axis=None, inplace=False): """ Return copy of input with values above given value(s) truncated. @@ -4221,6 +4234,9 @@ def clip_upper(self, threshold, axis=None): threshold : float or array_like axis : int or string axis name, optional Align object with threshold along the given axis. + inplace : boolean, default False + Whether to perform the operation in place on the data + .. versionadded:: 0.21.0 See Also -------- @@ -4234,12 +4250,14 @@ def clip_upper(self, threshold, axis=None): raise ValueError("Cannot use an NA value as a clip threshold") if is_scalar(threshold) and is_number(threshold): - return self._clip_with_scalar(None, threshold) + return self._clip_with_scalar(None, threshold, inplace=inplace) + + inplace = validate_bool_kwarg(inplace, 'inplace') subset = self.le(threshold, axis=axis) | isnull(self) - return self.where(subset, threshold, axis=axis) + return self.where(subset, threshold, axis=axis, inplace=inplace) - def clip_lower(self, threshold, axis=None): + def clip_lower(self, threshold, axis=None, inplace=False): """ Return copy of the input with values below given value(s) truncated. @@ -4248,6 +4266,9 @@ def clip_lower(self, threshold, axis=None): threshold : float or array_like axis : int or string axis name, optional Align object with threshold along the given axis. + inplace : boolean, default False + Whether to perform the operation in place on the data + .. versionadded:: 0.21.0 See Also -------- @@ -4261,10 +4282,12 @@ def clip_lower(self, threshold, axis=None): raise ValueError("Cannot use an NA value as a clip threshold") if is_scalar(threshold) and is_number(threshold): - return self._clip_with_scalar(threshold, None) + return self._clip_with_scalar(threshold, None, inplace=inplace) + + inplace = validate_bool_kwarg(inplace, 'inplace') subset = self.ge(threshold, axis=axis) | isnull(self) - return self.where(subset, threshold, axis=axis) + return self.where(subset, threshold, axis=axis, inplace=inplace) def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs): diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 73c6c0e7279a6..943a93b27a78a 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1807,6 +1807,7 @@ def test_built_in_round(self): def test_clip(self): median = self.frame.median().median() + original = self.frame.copy() capped = self.frame.clip_upper(median) assert not (capped.values > median).any() @@ -1817,6 +1818,25 @@ def test_clip(self): double = self.frame.clip(upper=median, lower=median) assert not (double.values != median).any() + # Verify that self.frame was not changed inplace + assert (self.frame.values == original.values).all() + + def test_inplace_clip(self): + # GH #15388 + median = self.frame.median().median() + frame_copy = self.frame.copy() + + frame_copy.clip_upper(median, inplace=True) + assert not (frame_copy.values > median).any() + frame_copy = self.frame.copy() + + frame_copy.clip_lower(median, inplace=True) + assert not (frame_copy.values < median).any() + frame_copy = self.frame.copy() + + frame_copy.clip(upper=median, lower=median, inplace=True) + assert not (frame_copy.values != median).any() + def test_dataframe_clip(self): # GH #2747 df = DataFrame(np.random.randn(1000, 2)) @@ -1843,18 +1863,23 @@ def test_clip_mixed_numeric(self): 'B': [1., np.nan, 2.]}) tm.assert_frame_equal(result, expected, check_like=True) - def test_clip_against_series(self): + @pytest.mark.parametrize("inplace", [True, False]) + def test_clip_against_series(self, inplace): # GH #6966 df = DataFrame(np.random.randn(1000, 2)) lb = Series(np.random.randn(1000)) ub = lb + 1 - clipped_df = df.clip(lb, ub, axis=0) + original = df.copy() + clipped_df = df.clip(lb, ub, axis=0, inplace=inplace) + + if inplace: + clipped_df = df for i in range(2): - lb_mask = df.iloc[:, i] <= lb - ub_mask = df.iloc[:, i] >= ub + lb_mask = original.iloc[:, i] <= lb + ub_mask = original.iloc[:, i] >= ub mask = ~lb_mask & ~ub_mask result = clipped_df.loc[lb_mask, i]
- [V] closes #15388 - [V] tests added / passed - [V] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16462
2017-05-23T20:06:46Z
2017-05-25T10:21:48Z
2017-05-25T10:21:48Z
2017-05-25T10:21:52Z
BUG: strange timeseries plot behavior
diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 92537059218d6..d9bdafb37a321 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -1349,6 +1349,22 @@ def test_hist(self): w2 = np.arange(0, 1, .1)[::-1] self.plt.hist([x, x], weights=[w1, w2]) + @slow + def test_overlapping_datetime(self): + # GB 6608 + s1 = Series([1, 2, 3], index=[datetime(1995, 12, 31), + datetime(2000, 12, 31), + datetime(2005, 12, 31)]) + s2 = Series([1, 2, 3], index=[datetime(1997, 12, 31), + datetime(2003, 12, 31), + datetime(2008, 12, 31)]) + + # plot first series, then add the second series to those axes, + # then try adding the first series again + ax = s1.plot() + s2.plot(ax=ax) + s1.plot(ax=ax) + def _check_plot_works(f, freq=None, series=None, *args, **kwargs): import matplotlib.pyplot as plt
I added a test with the simple repro at the top of bug #6608, which appears to be the missing piece for the bug to be closed. I went back in time to a previous version of pandas, and I confirmed the issue. ``` Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import pandas as pd >>> import datetime >>> >>> s1 = pd.Series([1, 2, 3], index=[datetime.datetime(1995, 12, 31), datetime.datetime(2000, 12, 31), datetime.datetime(2005, 12, 31)]) >>> s2 = pd.Series([1, 2, 3], index=[datetime.datetime(1997, 12, 31), datetime.datetime(2003, 12, 31), datetime.datetime(2008, 12, 31)]) >>> >>> ax = s1.plot() >>> s2.plot(ax=ax) <matplotlib.axes._subplots.AxesSubplot object at 0x04ECED10> >>> s1.plot(ax=ax) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Projects\Sprints\PandasVirtualEnvLatest\PandasVirtualEnvLatest\oldpy27\lib\site-packages\pandas\tools\plotting.py", line 1829, in plot_series plot_obj.generate() File "C:\Projects\Sprints\PandasVirtualEnvLatest\PandasVirtualEnvLatest\oldpy27\lib\site-packages\pandas\tools\plotting.py", line 905, in generate self._make_plot() File "C:\Projects\Sprints\PandasVirtualEnvLatest\PandasVirtualEnvLatest\oldpy27\lib\site-packages\pandas\tools\plotting.py", line 1317, in _make_plot self._make_ts_plot(data, **self.kwds) File "C:\Projects\Sprints\PandasVirtualEnvLatest\PandasVirtualEnvLatest\oldpy27\lib\site-packages\pandas\tools\plotting.py", line 1388, in _make_ts_plot _plot(data, 0, ax, label, self.style, **kwds) File "C:\Projects\Sprints\PandasVirtualEnvLatest\PandasVirtualEnvLatest\oldpy27\lib\site-packages\pandas\tools\plotting.py", line 1372, in _plot style=style, **kwds) File "C:\Projects\Sprints\PandasVirtualEnvLatest\PandasVirtualEnvLatest\oldpy27\lib\site-packages\pandas\tseries\plotting.py", line 82, in tsplot left, right = _get_xlim(ax.get_lines()) File "C:\Projects\Sprints\PandasVirtualEnvLatest\PandasVirtualEnvLatest\oldpy27\lib\site-packages\pandas\tseries\plotting.py", line 226, in _get_xlim left = min(x[0].ordinal, left) AttributeError: 'datetime.datetime' object has no attribute 'ordinal' >>> print(pd.__version__) 0.13.1 >>> ```
https://api.github.com/repos/pandas-dev/pandas/pulls/16461
2017-05-23T19:33:46Z
2017-05-24T12:11:58Z
2017-05-24T12:11:58Z
2017-05-24T20:50:08Z
Raise error in usecols when column doesn't exist but length matches
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index c9486954258c8..ea92c45b7e35b 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -72,6 +72,7 @@ I/O ^^^ - Bug in :func:`read_csv` when ``comment`` is passed in a space delimited text file (:issue:`16472`) +- Bug in :func:`read_csv` not raising an exception with nonexistent columns in ``usecols`` when it had the correct length (:issue:`14671`) - Bug that would force importing of the clipboard routines unnecessarily, potentially causing an import error on startup (:issue:`16288`) - Bug that raised ``IndexError`` when HTML-rendering an empty ``DataFrame`` (:issue:`15953`) - Bug in :func:`read_csv` in which tarfile object inputs were raising an error in Python 2.x for the C engine (:issue:`16530`) diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index aab70c8ce2cd4..055d6d045d2f2 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1649,6 +1649,12 @@ def __init__(self, src, **kwds): if self.usecols: usecols = _evaluate_usecols(self.usecols, self.orig_names) + + # GH 14671 + if (self.usecols_dtype == 'string' and + not set(usecols).issubset(self.orig_names)): + raise ValueError("Usecols do not match names.") + if len(self.names) > len(usecols): self.names = [n for i, n in enumerate(self.names) if (i in usecols or n in usecols)] diff --git a/pandas/tests/io/parser/usecols.py b/pandas/tests/io/parser/usecols.py index 8761d1ccd3da4..f582e5037ca07 100644 --- a/pandas/tests/io/parser/usecols.py +++ b/pandas/tests/io/parser/usecols.py @@ -475,3 +475,54 @@ def test_uneven_length_cols(self): 'C': [3, 5, 4, 3, 3, 7]}) df = self.read_csv(StringIO(data), usecols=usecols) tm.assert_frame_equal(df, expected) + + def test_raise_on_usecols_names_mismatch(self): + # GH 14671 + data = 'a,b,c,d\n1,2,3,4\n5,6,7,8' + + if self.engine == 'c': + msg = 'Usecols do not match names' + else: + msg = 'is not in list' + + usecols = ['a', 'b', 'c', 'd'] + df = self.read_csv(StringIO(data), usecols=usecols) + expected = DataFrame({'a': [1, 5], 'b': [2, 6], 'c': [3, 7], + 'd': [4, 8]}) + tm.assert_frame_equal(df, expected) + + usecols = ['a', 'b', 'c', 'f'] + with tm.assert_raises_regex(ValueError, msg): + self.read_csv(StringIO(data), usecols=usecols) + + usecols = ['a', 'b', 'f'] + with tm.assert_raises_regex(ValueError, msg): + self.read_csv(StringIO(data), usecols=usecols) + + names = ['A', 'B', 'C', 'D'] + + df = self.read_csv(StringIO(data), header=0, names=names) + expected = DataFrame({'A': [1, 5], 'B': [2, 6], 'C': [3, 7], + 'D': [4, 8]}) + tm.assert_frame_equal(df, expected) + + # TODO: https://github.com/pandas-dev/pandas/issues/16469 + # usecols = ['A','C'] + # df = self.read_csv(StringIO(data), header=0, names=names, + # usecols=usecols) + # expected = DataFrame({'A': [1,5], 'C': [3,7]}) + # tm.assert_frame_equal(df, expected) + # + # usecols = [0,2] + # df = self.read_csv(StringIO(data), header=0, names=names, + # usecols=usecols) + # expected = DataFrame({'A': [1,5], 'C': [3,7]}) + # tm.assert_frame_equal(df, expected) + + usecols = ['A', 'B', 'C', 'f'] + with tm.assert_raises_regex(ValueError, msg): + self.read_csv(StringIO(data), header=0, names=names, + usecols=usecols) + usecols = ['A', 'B', 'f'] + with tm.assert_raises_regex(ValueError, msg): + self.read_csv(StringIO(data), names=names, usecols=usecols)
- [ ] closes #14671 - [ ] tests added / passed - [ ] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] Bug fix: In parser.py added check that usecols option in read_csv raises an error if it contains strings not in the names option. 'test_raise_on_usecols_names_mismatch' added to tests/io/parser/usecols.py
https://api.github.com/repos/pandas-dev/pandas/pulls/16460
2017-05-23T18:09:11Z
2017-06-04T10:47:15Z
2017-06-04T10:47:15Z
2017-06-04T17:51:23Z
BUG: Allow non-callable attributes in aggregate function. Fixes GH16405
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 1f71710d19e44..ecbfee862353a 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -89,6 +89,7 @@ Reshaping - Bug in ``pd.wide_to_long()`` where no error was raised when ``i`` was not a unique identifier (:issue:`16382`) - Bug in ``Series.isin(..)`` with a list of tuples (:issue:`16394`) - Bug in construction of a ``DataFrame`` with mixed dtypes including an all-NaT column. (:issue:`16395`) +- Bug in ``DataFrame.agg()`` and ``Series.agg()`` with aggregating on non-callable attributes (:issue:`16405`) Numeric diff --git a/pandas/core/base.py b/pandas/core/base.py index a3ef24c80f883..97c4c8626dcbb 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -378,7 +378,7 @@ def aggregate(self, func, *args, **kwargs): def _try_aggregate_string_function(self, arg, *args, **kwargs): """ if arg is a string, then try to operate on it: - - try to find a function on ourselves + - try to find a function (or attribute) on ourselves - try to find a numpy function - raise @@ -387,7 +387,15 @@ def _try_aggregate_string_function(self, arg, *args, **kwargs): f = getattr(self, arg, None) if f is not None: - return f(*args, **kwargs) + if callable(f): + return f(*args, **kwargs) + + # people may try to aggregate on a non-callable attribute + # but don't let them think they can pass args to it + assert len(args) == 0 + assert len([kwarg for kwarg in kwargs + if kwarg not in ['axis', '_level']]) == 0 + return f f = getattr(np, arg, None) if f is not None: diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index aa7c7a7120c1b..a6f39cabb60ed 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -635,3 +635,48 @@ def test_nuiscance_columns(self): expected = DataFrame([[6, 6., 'foobarbaz']], index=['sum'], columns=['A', 'B', 'C']) assert_frame_equal(result, expected) + + def test_non_callable_aggregates(self): + + # GH 16405 + # 'size' is a property of frame/series + # validate that this is working + df = DataFrame({'A': [None, 2, 3], + 'B': [1.0, np.nan, 3.0], + 'C': ['foo', None, 'bar']}) + + # Function aggregate + result = df.agg({'A': 'count'}) + expected = pd.Series({'A': 2}) + + assert_series_equal(result, expected) + + # Non-function aggregate + result = df.agg({'A': 'size'}) + expected = pd.Series({'A': 3}) + + assert_series_equal(result, expected) + + # Mix function and non-function aggs + result1 = df.agg(['count', 'size']) + result2 = df.agg({'A': ['count', 'size'], + 'B': ['count', 'size'], + 'C': ['count', 'size']}) + expected = pd.DataFrame({'A': {'count': 2, 'size': 3}, + 'B': {'count': 2, 'size': 3}, + 'C': {'count': 2, 'size': 3}}) + + assert_frame_equal(result1, result2, check_like=True) + assert_frame_equal(result2, expected, check_like=True) + + # Just functional string arg is same as calling df.arg() + result = df.agg('count') + expected = df.count() + + assert_series_equal(result, expected) + + # Just a string attribute arg same as calling df.arg + result = df.agg('size') + expected = df.size + + assert result == expected diff --git a/pandas/tests/series/test_apply.py b/pandas/tests/series/test_apply.py index c273d3161fff5..2c5f0d7772cc2 100644 --- a/pandas/tests/series/test_apply.py +++ b/pandas/tests/series/test_apply.py @@ -306,6 +306,22 @@ def test_reduce(self): name=self.series.name) assert_series_equal(result, expected) + def test_non_callable_aggregates(self): + # test agg using non-callable series attributes + s = Series([1, 2, None]) + + # Calling agg w/ just a string arg same as calling s.arg + result = s.agg('size') + expected = s.size + assert result == expected + + # test when mixed w/ callable reducers + result = s.agg(['size', 'count', 'mean']) + expected = Series(OrderedDict({'size': 3.0, + 'count': 2.0, + 'mean': 1.5})) + assert_series_equal(result[expected.index], expected) + class TestSeriesMap(TestData):
- [x] closes #16405 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16458
2017-05-23T16:07:13Z
2017-06-01T10:35:19Z
2017-06-01T10:35:19Z
2017-06-04T17:02:55Z
DOC: update make.py script
diff --git a/doc/make.py b/doc/make.py index 316ce58812f82..acef563f301e4 100755 --- a/doc/make.py +++ b/doc/make.py @@ -34,39 +34,52 @@ SPHINX_BUILD = 'sphinxbuild' -def upload_dev(user='pandas'): +def _process_user(user): + if user is None or user is False: + user = '' + else: + user = user + '@' + return user + + +def upload_dev(user=None): 'push a copy to the pydata dev directory' - if os.system('cd build/html; rsync -avz . {0}@pandas.pydata.org' + user = _process_user(user) + if os.system('cd build/html; rsync -avz . {0}pandas.pydata.org' ':/usr/share/nginx/pandas/pandas-docs/dev/ -essh'.format(user)): raise SystemExit('Upload to Pydata Dev failed') -def upload_dev_pdf(user='pandas'): +def upload_dev_pdf(user=None): 'push a copy to the pydata dev directory' - if os.system('cd build/latex; scp pandas.pdf {0}@pandas.pydata.org' + user = _process_user(user) + if os.system('cd build/latex; scp pandas.pdf {0}pandas.pydata.org' ':/usr/share/nginx/pandas/pandas-docs/dev/'.format(user)): raise SystemExit('PDF upload to Pydata Dev failed') -def upload_stable(user='pandas'): +def upload_stable(user=None): 'push a copy to the pydata stable directory' - if os.system('cd build/html; rsync -avz . {0}@pandas.pydata.org' + user = _process_user(user) + if os.system('cd build/html; rsync -avz . {0}pandas.pydata.org' ':/usr/share/nginx/pandas/pandas-docs/stable/ -essh'.format(user)): raise SystemExit('Upload to stable failed') -def upload_stable_pdf(user='pandas'): +def upload_stable_pdf(user=None): 'push a copy to the pydata dev directory' - if os.system('cd build/latex; scp pandas.pdf {0}@pandas.pydata.org' + user = _process_user(user) + if os.system('cd build/latex; scp pandas.pdf {0}pandas.pydata.org' ':/usr/share/nginx/pandas/pandas-docs/stable/'.format(user)): raise SystemExit('PDF upload to stable failed') -def upload_prev(ver, doc_root='./', user='pandas'): +def upload_prev(ver, doc_root='./', user=None): 'push a copy of older release to appropriate version directory' + user = _process_user(user) local_dir = doc_root + 'build/html' remote_dir = '/usr/share/nginx/pandas/pandas-docs/version/%s/' % ver - cmd = 'cd %s; rsync -avz . %s@pandas.pydata.org:%s -essh' + cmd = 'cd %s; rsync -avz . %spandas.pydata.org:%s -essh' cmd = cmd % (local_dir, user, remote_dir) print(cmd) if os.system(cmd): @@ -74,7 +87,7 @@ def upload_prev(ver, doc_root='./', user='pandas'): 'Upload to %s from %s failed' % (remote_dir, local_dir)) local_dir = doc_root + 'build/latex' - pdf_cmd = 'cd %s; scp pandas.pdf %s@pandas.pydata.org:%s' + pdf_cmd = 'cd %s; scp pandas.pdf %spandas.pydata.org:%s' pdf_cmd = pdf_cmd % (local_dir, user, remote_dir) if os.system(pdf_cmd): raise SystemExit('Upload PDF to %s from %s failed' % (ver, doc_root))
@TomAugspurger I updated the docs yesterday with this. Not sure if it is needed to keep the possibility to pass a user (if you specify this in `.ssh/config` you don't need this, but the current code allows you to not have the user specified there) But I could also simplify and just remove the whole user thing. (depending on that will also update the other one, upload_stable_pdf)
https://api.github.com/repos/pandas-dev/pandas/pulls/16456
2017-05-23T15:15:15Z
2017-05-23T17:33:19Z
2017-05-23T17:33:19Z
2017-05-30T12:20:22Z
Fix correct warning with c engine when skipping lines
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 6d6a148ed025f..6c9728191f5b6 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -53,6 +53,7 @@ Indexing I/O ^^^ +- Bug in pd.read_csv() when comment is passed in space deliminted text files (:issue:`16472`) - Bug that would force importing of the clipboard routines unnecessarily, potentially causing an import error on startup (:issue:`16288`) - Bug that raised IndexError HTML-rendering an empty DataFrame (:issue:`15953`) diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c index 6b0775e54da0c..be23ebb023383 100644 --- a/pandas/_libs/src/parser/tokenizer.c +++ b/pandas/_libs/src/parser/tokenizer.c @@ -832,6 +832,9 @@ int tokenize_bytes(parser_t *self, size_t line_limit, int start_lines) { } else if (IS_CARRIAGE(c)) { self->state = EAT_CRNL; break; + } else if (IS_COMMENT_CHAR(c)) { + self->state = EAT_COMMENT; + break; } else if (!IS_WHITESPACE(c)) { self->state = START_FIELD; // fall through to subsequent state diff --git a/pandas/tests/io/parser/c_parser_only.py b/pandas/tests/io/parser/c_parser_only.py index 3e7a648474bc3..56ac10404b7b2 100644 --- a/pandas/tests/io/parser/c_parser_only.py +++ b/pandas/tests/io/parser/c_parser_only.py @@ -7,6 +7,8 @@ further arguments when parsing. """ +import sys + import pytest import numpy as np @@ -417,3 +419,30 @@ def test_data_after_quote(self): expected = DataFrame({'a': ['1', 'ba']}) tm.assert_frame_equal(result, expected) + + @tm.capture_stderr + def test_comment_whitespace_delimited(self): + test_input = """\ +1 2 +2 2 3 +3 2 3 # 3 fields +4 2 3# 3 fields +5 2 # 2 fields +6 2# 2 fields +7 # 1 field, NaN +8# 1 field, NaN +9 2 3 # skipped line +# comment""" + df = self.read_csv(StringIO(test_input), comment='#', header=None, + delimiter='\\s+', skiprows=0, + error_bad_lines=False) + error = sys.stderr.getvalue() + # skipped lines 2, 3, 4, 9 + for line_num in (2, 3, 4, 9): + assert 'Skipping line {}'.format(line_num) in error, error + expected = DataFrame([[1, 2], + [5, 2], + [6, 2], + [7, np.nan], + [8, np.nan]]) + tm.assert_frame_equal(df, expected)
Fixed bug where c engine would not print warnings for lines it skipped in case the skipped line had an inline comment. Also, its accounting of number of fields in such lines would be off by one. - [x] closes #16472 - [x] tests added - [x] tests passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16455
2017-05-23T14:40:51Z
2017-05-24T17:36:06Z
2017-05-24T17:36:05Z
2017-05-30T12:20:22Z
DOC: remove prominence of installing from source instructions in README
diff --git a/README.md b/README.md index 01182d7b7b4b5..dc74828ba9863 100644 --- a/README.md +++ b/README.md @@ -197,14 +197,7 @@ mode](https://pip.pypa.io/en/latest/reference/pip_install.html#editable-installs pip install -e . ``` -On Windows, you will need to install MinGW and execute: - -```sh -python setup.py build --compiler=mingw32 -python setup.py install -``` - -See **[the docs](http://pandas.pydata.org/pandas-docs/stable/install.html#installing-from-source)** for more information. +See the full instructions for [installing from source](http://pandas.pydata.org/pandas-docs/stable/install.html#installing-from-source). ## License BSD
these are wrong for windows anyhow
https://api.github.com/repos/pandas-dev/pandas/pulls/16451
2017-05-23T11:07:01Z
2017-05-23T11:07:19Z
2017-05-23T11:07:19Z
2017-05-23T11:07:19Z
BUG: Series.argmax() fails with np.inf
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 8b2c4d16f4e1a..03508b02625c8 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -265,7 +265,7 @@ Other API Changes - Removed the ``@slow`` decorator from ``pandas.util.testing``, which caused issues for some downstream packages' test suites. Use ``@pytest.mark.slow`` instead, which achieves the same thing (:issue:`16850`) - Moved definition of ``MergeError`` to the ``pandas.errors`` module. - The signature of :func:`Series.set_axis` and :func:`DataFrame.set_axis` has been changed from ``set_axis(axis, labels)`` to ``set_axis(labels, axis=0)``, for consistency with the rest of the API. The old signature is deprecated and will show a ``FutureWarning`` (:issue:`14636`) - +- :func:`Series.argmin` and :func:`Series.argmax` will now raise a ``TypeError`` when used with ``object`` dtypes, instead of a ``ValueError`` (:issue:`13595`) .. _whatsnew_0210.deprecations: @@ -369,6 +369,7 @@ Reshaping - Fixes regression from 0.20, :func:`Series.aggregate` and :func:`DataFrame.aggregate` allow dictionaries as return values again (:issue:`16741`) - Fixes dtype of result with integer dtype input, from :func:`pivot_table` when called with ``margins=True`` (:issue:`17013`) - Bug in :func:`crosstab` where passing two ``Series`` with the same name raised a ``KeyError`` (:issue:`13279`) +- :func:`Series.argmin`, :func:`Series.argmax`, and their counterparts on ``DataFrame`` and groupby objects work correctly with floating point data that contains infinite values (:issue:`13595`). Numeric ^^^^^^^ diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 2f4e437c0ae61..b2bbf1c75b7ea 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -486,23 +486,23 @@ def reduction(values, axis=None, skipna=True): nanmax = _nanminmax('max', fill_value_typ='-inf') +@disallow('O') def nanargmax(values, axis=None, skipna=True): """ Returns -1 in the NA case """ - values, mask, dtype, _ = _get_values(values, skipna, fill_value_typ='-inf', - isfinite=True) + values, mask, dtype, _ = _get_values(values, skipna, fill_value_typ='-inf') result = values.argmax(axis) result = _maybe_arg_null_out(result, axis, mask, skipna) return result +@disallow('O') def nanargmin(values, axis=None, skipna=True): """ Returns -1 in the NA case """ - values, mask, dtype, _ = _get_values(values, skipna, fill_value_typ='+inf', - isfinite=True) + values, mask, dtype, _ = _get_values(values, skipna, fill_value_typ='+inf') result = values.argmin(axis) result = _maybe_arg_null_out(result, axis, mask, skipna) return result diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 0dea1e8447b2b..f9e1a0d2e744a 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -2339,7 +2339,7 @@ def test_non_cython_api(self): assert_frame_equal(result, expected) # idxmax - expected = DataFrame([[0], [nan]], columns=['B'], index=[1, 3]) + expected = DataFrame([[0.0], [nan]], columns=['B'], index=[1, 3]) expected.index.name = 'A' result = g.idxmax() assert_frame_equal(result, expected) diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index 991c5ff625554..4888f8fe996b6 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -1857,3 +1857,50 @@ def test_op_duplicate_index(self): result = s1 + s2 expected = pd.Series([11, 12, np.nan], index=[1, 1, 2]) assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "test_input,error_type", + [ + (pd.Series([]), ValueError), + + # For strings, or any Series with dtype 'O' + (pd.Series(['foo', 'bar', 'baz']), TypeError), + (pd.Series([(1,), (2,)]), TypeError), + + # For mixed data types + ( + pd.Series(['foo', 'foo', 'bar', 'bar', None, np.nan, 'baz']), + TypeError + ), + ] + ) + def test_assert_argminmax_raises(self, test_input, error_type): + """ + Cases where ``Series.argmax`` and related should raise an exception + """ + with pytest.raises(error_type): + test_input.argmin() + with pytest.raises(error_type): + test_input.argmin(skipna=False) + with pytest.raises(error_type): + test_input.argmax() + with pytest.raises(error_type): + test_input.argmax(skipna=False) + + def test_argminmax_with_inf(self): + # For numeric data with NA and Inf (GH #13595) + s = pd.Series([0, -np.inf, np.inf, np.nan]) + + assert s.argmin() == 1 + assert np.isnan(s.argmin(skipna=False)) + + assert s.argmax() == 2 + assert np.isnan(s.argmax(skipna=False)) + + # Using old-style behavior that treats floating point nan, -inf, and + # +inf as missing + with pd.option_context('mode.use_inf_as_na', True): + assert s.argmin() == 0 + assert np.isnan(s.argmin(skipna=False)) + assert s.argmax() == 0 + np.isnan(s.argmax(skipna=False))
closes #13595 This PR changes the behavior of two functions in the `nanops` module to address #13595, `nanargmax` and `nanargmin`. Previously, these two functions used a flag on the `_get_values` helper that caused it to 1) always mask out and ignore infinite values in the input, and 2) attempt to coerce the input to float. It's worth noting that because of 2), this changes the way `nanargmax` and `nanargmin`, and consequently `Series.idxmax` etc, behave with string data. Previously, ```python data = ['foo', 'bar', 'baz'] pd.Series(data).idxmax() # --> ValueError pd.DataFrame({'A': data}).idxmax() # --> ValueError pd.DataFrame({'grp': [1, 1, 2], 'A': data}).groupby('grp').idxmax() # --> an empty data frame ``` After the PR, ```python In [1]: import pandas as pd In [2]: data = ['foo', 'bar', 'baz'] In [3]: pd.Series(data).idxmax() Out[3]: 0 In [4]: pd.DataFrame({'A': data}).idxmax() Out[4]: A 0 dtype: int64 In [5]: pd.DataFrame({'grp': [1, 1, 2], 'A': data}).groupby('grp').idxmax() Out[5]: A grp 1 0 2 2 ``` This is consistent with the behavior of `numpy.argmax` etc with string data, and might be more consistent with user expectations. It did mean that I needed to update one of the `DataFrame.groupby` test cases, but otherwise appears to cause no breakage. Since this might be a bigger change that was expected for fixing the issue, I'm posting it as WIP. - [x] closes #13595 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16449
2017-05-23T03:46:29Z
2017-08-15T22:44:55Z
2017-08-15T22:44:54Z
2017-08-16T01:42:01Z
Don't ignore figsize in df.boxplot
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index d5fd879d3f9bf..c199564a4dab6 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -61,6 +61,7 @@ Plotting - Bug in ``DataFrame.plot`` with a single column and a list-like ``color`` (:issue:`3486`) - Bug in ``plot`` where ``NaT`` in ``DatetimeIndex`` results in ``Timestamp.min`` (:issue: `12405`) +- Bug in ``DataFrame.boxplot`` where ``figsize`` keyword was not respected for non-grouped boxplots (:issue:`11959`) diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 49076ffb469cb..9169eb86895fb 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -49,9 +49,10 @@ def _get_standard_kind(kind): return {'density': 'kde'}.get(kind, kind) -def _gca(): +def _gca(rc=None): import matplotlib.pyplot as plt - return plt.gca() + with plt.rc_context(rc): + return plt.gca() def _gcf(): @@ -1871,12 +1872,6 @@ def plot_series(data, kind='line', ax=None, # Series unique **kwds): import matplotlib.pyplot as plt - """ - If no axes is specified, check whether there are existing figures - If there is no existing figures, _gca() will - create a figure with the default figsize, causing the figsize=parameter to - be ignored. - """ if ax is None and len(plt.get_fignums()) > 0: ax = _gca() ax = MPLPlot._get_ax_layer(ax) @@ -2006,7 +2001,8 @@ def plot_group(keys, values, ax): "'by' is None") if ax is None: - ax = _gca() + rc = {'figure.figsize': figsize} if figsize is not None else {} + ax = _gca(rc) data = data._get_numeric_data() if columns is None: columns = data.columns diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index a4c70f7945347..ce8fb7a57c912 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -160,6 +160,14 @@ def test_boxplot_empty_column(self): df.loc[:, 0] = np.nan _check_plot_works(df.boxplot, return_type='axes') + @slow + def test_figsize(self): + df = DataFrame(np.random.rand(10, 5), + columns=['A', 'B', 'C', 'D', 'E']) + result = df.boxplot(return_type='axes', figsize=(12, 8)) + assert result.figure.bbox_inches.width == 12 + assert result.figure.bbox_inches.height == 8 + def test_fontsize(self): df = DataFrame({"a": [1, 2, 3, 4, 5, 6]}) self._check_ticks_props(df.boxplot("a", fontsize=16),
Work in progress from PyCon sprints Fix for https://github.com/pandas-dev/pandas/issues/11959 It really doesn't feel like a proper fix, but I'm not sure what a proper fix would be (without changing matplotlib). The matplotlib `gca()` ends up calling `figure()`, but doesn't let us pass in a `figsize` to `gca()`. Any advice? FYI this works, ie it fixes the behavior for the code snippet in the bug report. It would obviously break in multithreaded scenarios, but I'm not sure if that's a consideration or not.
https://api.github.com/repos/pandas-dev/pandas/pulls/16445
2017-05-23T00:26:20Z
2017-05-24T01:24:42Z
2017-05-24T01:24:42Z
2017-05-30T12:20:22Z
BUG: Handle numpy strings in index names in HDF #13492
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 379249b6e55d6..7bca4174da297 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -70,6 +70,7 @@ I/O - Bug that raised IndexError HTML-rendering an empty DataFrame (:issue:`15953`) - Bug in ``pd.read_csv()`` in which tarfile object inputs were raising an error in Python 2.x for the C engine (:issue:`16530`) - Bug where ``DataFrame.to_html()`` ignored the ``index_names`` parameter (:issue:`16493`) +- Bug where ``pd.read_hdf()`` returns numpy strings for index names (:issue:`13492`) - Bug in ``HDFStore.select_as_multiple()`` where start/stop arguments were not respected (:issue:`16209`) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index b838260d1f73c..4a1b12414bcc5 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -73,6 +73,18 @@ def _ensure_encoding(encoding): return encoding +def _ensure_str(name): + """Ensure that an index / column name is a str (python 3) or + unicode (python 2); otherwise they may be np.string dtype. + Non-string dtypes are passed through unchanged. + + https://github.com/pandas-dev/pandas/issues/13492 + """ + if isinstance(name, compat.string_types): + name = compat.text_type(name) + return name + + Term = Expr @@ -2567,7 +2579,7 @@ def read_index_node(self, node, start=None, stop=None): name = None if 'name' in node._v_attrs: - name = node._v_attrs.name + name = _ensure_str(node._v_attrs.name) index_class = self._alias_to_class(getattr(node._v_attrs, 'index_class', '')) diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index ae14f74ece31c..040345db83c2b 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -16,7 +16,7 @@ date_range, timedelta_range, Index, DatetimeIndex, isnull) -from pandas.compat import is_platform_windows, PY3, PY35, BytesIO +from pandas.compat import is_platform_windows, PY3, PY35, BytesIO, text_type from pandas.io.formats.printing import pprint_thing tables = pytest.importorskip('tables') @@ -2920,6 +2920,27 @@ def test_store_index_name_with_tz(self): recons = store['frame'] tm.assert_frame_equal(recons, df) + @pytest.mark.parametrize('table_format', ['table', 'fixed']) + def test_store_index_name_numpy_str(self, table_format): + # GH #13492 + idx = pd.Index(pd.to_datetime([datetime.date(2000, 1, 1), + datetime.date(2000, 1, 2)]), + name=u('cols\u05d2')) + idx1 = pd.Index(pd.to_datetime([datetime.date(2010, 1, 1), + datetime.date(2010, 1, 2)]), + name=u('rows\u05d0')) + df = pd.DataFrame(np.arange(4).reshape(2, 2), columns=idx, index=idx1) + + # This used to fail, returning numpy strings instead of python strings. + with ensure_clean_path(self.path) as path: + df.to_hdf(path, 'df', format=table_format) + df2 = read_hdf(path, 'df') + + assert_frame_equal(df, df2, check_names=True) + + assert type(df2.index.name) == text_type + assert type(df2.columns.name) == text_type + def test_store_series_name(self): df = tm.makeDataFrame() series = df['A']
Work in progress! - [ ] closes #13492 - [ ] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16444
2017-05-23T00:11:36Z
2017-06-04T10:44:26Z
2017-06-04T10:44:26Z
2017-06-04T17:02:55Z
BUG: .iloc[:] and .loc[:] return a copy of the original object #13873
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 79f2816f43a6f..d6b699abdba2d 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -97,6 +97,7 @@ Conversion Indexing ^^^^^^^^ +- When called with a null slice (e.g. ``df.iloc[:]``), the``iloc`` and ``loc`` indexers return a shallow copy of the original object. Previously they returned the original object. (:issue:`13873`). I/O diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 50f2f9b52e111..ae0aaf98fdf02 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -988,6 +988,10 @@ def _getitem_lowerdim(self, tup): if len(new_key) == 1: new_key, = new_key + # Slices should return views, but calling iloc/loc with a null + # slice returns a new object. + if is_null_slice(new_key): + return section # This is an elided recursive call to iloc/loc/etc' return getattr(section, self.name)[new_key] @@ -1250,7 +1254,7 @@ def _get_slice_axis(self, slice_obj, axis=0): obj = self.obj if not need_slice(slice_obj): - return obj + return obj.copy(deep=False) indexer = self._convert_slice_indexer(slice_obj, axis) if isinstance(indexer, slice): @@ -1349,7 +1353,7 @@ def _get_slice_axis(self, slice_obj, axis=0): """ this is pretty simple as we just have to deal with labels """ obj = self.obj if not need_slice(slice_obj): - return obj + return obj.copy(deep=False) labels = obj._get_axis(axis) indexer = labels.slice_indexer(slice_obj.start, slice_obj.stop, @@ -1690,7 +1694,7 @@ def _get_slice_axis(self, slice_obj, axis=0): obj = self.obj if not need_slice(slice_obj): - return obj + return obj.copy(deep=False) slice_obj = self._convert_slice_indexer(slice_obj, axis) if isinstance(slice_obj, slice): diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index af4b9e1f0cc25..769cf8ec395dd 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -591,3 +591,21 @@ def test_iloc_empty_list_indexer_is_ok(self): tm.assert_frame_equal(df.iloc[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True) + + def test_identity_slice_returns_new_object(self): + # GH13873 + original_df = DataFrame({'a': [1, 2, 3]}) + sliced_df = original_df.iloc[:] + assert sliced_df is not original_df + + # should be a shallow copy + original_df['a'] = [4, 4, 4] + assert (sliced_df['a'] == 4).all() + + original_series = Series([1, 2, 3, 4, 5, 6]) + sliced_series = original_series.iloc[:] + assert sliced_series is not original_series + + # should also be a shallow copy + original_series[:3] = [7, 8, 9] + assert all(sliced_series[:3] == [7, 8, 9]) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index fe2318be72eda..3e863a59df67e 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -630,3 +630,28 @@ def test_loc_empty_list_indexer_is_ok(self): tm.assert_frame_equal(df.loc[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True) + + def test_identity_slice_returns_new_object(self): + # GH13873 + original_df = DataFrame({'a': [1, 2, 3]}) + sliced_df = original_df.loc[:] + assert sliced_df is not original_df + assert original_df[:] is not original_df + + # should be a shallow copy + original_df['a'] = [4, 4, 4] + assert (sliced_df['a'] == 4).all() + + # These should not return copies + assert original_df is original_df.loc[:, :] + df = DataFrame(np.random.randn(10, 4)) + assert df[0] is df.loc[:, 0] + + # Same tests for Series + original_series = Series([1, 2, 3, 4, 5, 6]) + sliced_series = original_series.loc[:] + assert sliced_series is not original_series + assert original_series[:] is not original_series + + original_series[:3] = [7, 8, 9] + assert all(sliced_series[:3] == [7, 8, 9])
Previously they returned the original. This PR should make it consistent with numpy and list. - [x] closes #13873 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16443
2017-05-23T00:00:37Z
2017-06-14T23:03:28Z
2017-06-14T23:03:27Z
2017-06-14T23:03:49Z
GH10559: Minor improvement: Change read_excel sheet name
diff --git a/doc/source/io.rst b/doc/source/io.rst index 9692766505d7a..bca23dd18a0e3 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -2561,12 +2561,12 @@ Reading Excel Files ''''''''''''''''''' In the most basic use-case, ``read_excel`` takes a path to an Excel -file, and the ``sheetname`` indicating which sheet to parse. +file, and the ``sheet_name`` indicating which sheet to parse. .. code-block:: python # Returns a DataFrame - read_excel('path_to_file.xls', sheetname='Sheet1') + read_excel('path_to_file.xls', sheet_name='Sheet1') .. _io.excel.excelfile_class: @@ -2634,12 +2634,12 @@ of sheet names can simply be passed to ``read_excel`` with no loss in performanc Specifying Sheets +++++++++++++++++ -.. note :: The second argument is ``sheetname``, not to be confused with ``ExcelFile.sheet_names`` +.. note :: The second argument is ``sheet_name``, not to be confused with ``ExcelFile.sheet_names`` .. note :: An ExcelFile's attribute ``sheet_names`` provides access to a list of sheets. -- The arguments ``sheetname`` allows specifying the sheet or sheets to read. -- The default value for ``sheetname`` is 0, indicating to read the first sheet +- The arguments ``sheet_name`` allows specifying the sheet or sheets to read. +- The default value for ``sheet_name`` is 0, indicating to read the first sheet - Pass a string to refer to the name of a particular sheet in the workbook. - Pass an integer to refer to the index of a sheet. Indices follow Python convention, beginning at 0. @@ -2670,18 +2670,18 @@ Using None to get all sheets: .. code-block:: python # Returns a dictionary of DataFrames - read_excel('path_to_file.xls',sheetname=None) + read_excel('path_to_file.xls',sheet_name=None) Using a list to get multiple sheets: .. code-block:: python # Returns the 1st and 4th sheet, as a dictionary of DataFrames. - read_excel('path_to_file.xls',sheetname=['Sheet1',3]) + read_excel('path_to_file.xls',sheet_name=['Sheet1',3]) .. versionadded:: 0.16 -``read_excel`` can read more than one sheet, by setting ``sheetname`` to either +``read_excel`` can read more than one sheet, by setting ``sheet_name`` to either a list of sheet names, a list of sheet positions, or ``None`` to read all sheets. .. versionadded:: 0.13 diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 3734dc15be2e9..b6c9495765b2f 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -57,7 +57,7 @@ Other API Changes Deprecations ~~~~~~~~~~~~ - +- :func:`read_excel()` has deprecated ``sheetname`` in favor of ``sheet_name`` for consistency with to_excel() (:issue:`10559`). .. _whatsnew_0210.prior_deprecations: diff --git a/pandas/io/excel.py b/pandas/io/excel.py index fba3d7559aeaf..81a36b21b3617 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -30,7 +30,7 @@ import pandas.compat.openpyxl_compat as openpyxl_compat from warnings import warn from distutils.version import LooseVersion -from pandas.util._decorators import Appender +from pandas.util._decorators import Appender, deprecate_kwarg from textwrap import fill __all__ = ["read_excel", "ExcelWriter", "ExcelFile"] @@ -48,7 +48,7 @@ The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file://localhost/path/to/workbook.xlsx -sheetname : string, int, mixed list of strings/ints, or None, default 0 +sheet_name : string, int, mixed list of strings/ints, or None, default 0 Strings are used for sheet names, Integers are used in zero-indexed sheet positions. @@ -69,6 +69,10 @@ * [0,1,"Sheet5"] -> 1st, 2nd & 5th sheet as a dictionary of DataFrames * None -> All sheets as a dictionary of DataFrames +sheetname : string, int, mixed list of strings/ints, or None, default 0 + .. deprecated:: 0.21.0 + Use `sheet_name` instead + header : int, list of ints, default 0 Row (0-indexed) to use for the column labels of the parsed DataFrame. If a list of integers is passed those row positions will @@ -144,7 +148,7 @@ Returns ------- parsed : DataFrame or Dict of DataFrames - DataFrame from the passed in Excel file. See notes in sheetname + DataFrame from the passed in Excel file. See notes in sheet_name argument for more information on when a Dict of Dataframes is returned. """ @@ -189,8 +193,9 @@ def get_writer(engine_name): raise ValueError("No Excel writer '%s'" % engine_name) +@deprecate_kwarg('sheetname', 'sheet_name') @Appender(_read_excel_doc) -def read_excel(io, sheetname=0, header=0, skiprows=None, skip_footer=0, +def read_excel(io, sheet_name=0, header=0, skiprows=None, skip_footer=0, index_col=None, names=None, parse_cols=None, parse_dates=False, date_parser=None, na_values=None, thousands=None, convert_float=True, has_index_names=None, converters=None, @@ -201,7 +206,7 @@ def read_excel(io, sheetname=0, header=0, skiprows=None, skip_footer=0, io = ExcelFile(io, engine=engine) return io._parse_excel( - sheetname=sheetname, header=header, skiprows=skiprows, names=names, + sheetname=sheet_name, header=header, skiprows=skiprows, names=names, index_col=index_col, parse_cols=parse_cols, parse_dates=parse_dates, date_parser=date_parser, na_values=na_values, thousands=thousands, convert_float=convert_float, has_index_names=has_index_names, @@ -266,7 +271,7 @@ def __init__(self, io, **kwds): def __fspath__(self): return self._io - def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0, + def parse(self, sheet_name=0, header=0, skiprows=None, skip_footer=0, names=None, index_col=None, parse_cols=None, parse_dates=False, date_parser=None, na_values=None, thousands=None, convert_float=True, has_index_names=None, @@ -279,7 +284,7 @@ def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0, docstring for more info on accepted parameters """ - return self._parse_excel(sheetname=sheetname, header=header, + return self._parse_excel(sheetname=sheet_name, header=header, skiprows=skiprows, names=names, index_col=index_col, has_index_names=has_index_names, diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index bbf4f1107ac9e..0a79d4e8fd81b 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -544,6 +544,18 @@ def test_date_conversion_overflow(self): result = self.get_exceldf('testdateoverflow') tm.assert_frame_equal(result, expected) + def test_sheet_name_and_sheetname(self): + # GH10559: Minor improvement: Change "sheet_name" to "sheetname" + # GH10969: DOC: Consistent var names (sheetname vs sheet_name) + # GH12604: CLN GH10559 Rename sheetname variable to sheet_name + dfref = self.get_csv_refdf('test1') + df1 = self.get_exceldf('test1', sheet_name='Sheet1') # doc + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + df2 = self.get_exceldf('test1', sheetname='Sheet2') # bkwrd compat + + tm.assert_frame_equal(df1, dfref, check_names=False) + tm.assert_frame_equal(df2, dfref, check_names=False) + class XlrdTests(ReadingTestsBase): """
modify io/excel.py and relevant docs (io.rst) to use sheet_name for read_excel but allow sheetname to still be used for backwards compatibility. add test_excel to verify that sheet_name and sheetname args produce the same result. - [X] closes #10559 - [X] tests added / passed - [X] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16442
2017-05-22T23:49:13Z
2017-05-23T19:36:28Z
2017-05-23T19:36:28Z
2017-05-27T16:39:51Z
BUG: Render empty DataFrame as empty HTML table w/o raising IndexError.
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 57625b725ddba..6813518bdd9ec 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -54,6 +54,7 @@ I/O ^^^ - Bug that would force importing of the clipboard routines unnecessarily, potentially causing an import error on startup (:issue:`16288`) +- Bug that raised IndexError HTML-rendering an empty DataFrame (:issue:`15953`) Plotting diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index eac82ddde2318..3d7e0fcdc69b3 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -238,24 +238,25 @@ def format_attr(pair): "class": " ".join(cs), "is_visible": True}) - for c, value in enumerate(clabels[r]): - cs = [COL_HEADING_CLASS, "level%s" % r, "col%s" % c] - cs.extend(cell_context.get( - "col_headings", {}).get(r, {}).get(c, [])) - es = { - "type": "th", - "value": value, - "display_value": value, - "class": " ".join(cs), - "is_visible": _is_visible(c, r, col_lengths), - } - colspan = col_lengths.get((r, c), 0) - if colspan > 1: - es["attributes"] = [ - format_attr({"key": "colspan", "value": colspan}) - ] - row_es.append(es) - head.append(row_es) + if clabels: + for c, value in enumerate(clabels[r]): + cs = [COL_HEADING_CLASS, "level%s" % r, "col%s" % c] + cs.extend(cell_context.get( + "col_headings", {}).get(r, {}).get(c, [])) + es = { + "type": "th", + "value": value, + "display_value": value, + "class": " ".join(cs), + "is_visible": _is_visible(c, r, col_lengths), + } + colspan = col_lengths.get((r, c), 0) + if colspan > 1: + es["attributes"] = [ + format_attr({"key": "colspan", "value": colspan}) + ] + row_es.append(es) + head.append(row_es) if self.data.index.names and not all(x is None for x in self.data.index.names): diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index ee7356f12f498..9911888f758fb 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -103,6 +103,16 @@ def test_render(self): s.render() # it worked? + def test_render_empty_dfs(self): + empty_df = DataFrame() + es = Styler(empty_df) + es.render() + # An index but no columns + DataFrame(columns=['a']).style.render() + # A column but no index + DataFrame(index=['a']).style.render() + # No IndexError raised? + def test_render_double(self): df = pd.DataFrame({"A": [0, 1]}) style = lambda x: pd.Series(["color: red; border: 1px",
- [X] closes #15953 - [X] 1 test added / passed - [X] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry A one line change to add an ``if clabels`` guard to clabels enumeration. Returns HTML string consisting of empty table. Help requested with format and placement of whatsnew entry.
https://api.github.com/repos/pandas-dev/pandas/pulls/16441
2017-05-22T23:33:21Z
2017-05-23T16:52:45Z
2017-05-23T16:52:45Z
2017-05-30T12:20:22Z
DOC: add example on json_normalize
diff --git a/doc/source/io.rst b/doc/source/io.rst index e6b51b7e2f45c..e338407361705 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -2020,6 +2020,13 @@ into a flat table. .. ipython:: python from pandas.io.json import json_normalize + data = [{'id': 1, 'name': {'first': 'Coleen', 'last': 'Volk'}}, + {'name': {'given': 'Mose', 'family': 'Regner'}}, + {'id': 2, 'name': 'Faye Raker'}] + json_normalize(data) + +.. ipython:: python + data = [{'state': 'Florida', 'shortname': 'FL', 'info': { diff --git a/pandas/io/json/normalize.py b/pandas/io/json/normalize.py index 401d8d9ead2b8..72776ed01de15 100644 --- a/pandas/io/json/normalize.py +++ b/pandas/io/json/normalize.py @@ -135,6 +135,16 @@ def json_normalize(data, record_path=None, meta=None, Examples -------- + >>> from pandas.io.json import json_normalize + >>> data = [{'id': 1, 'name': {'first': 'Coleen', 'last': 'Volk'}}, + ... {'name': {'given': 'Mose', 'family': 'Regner'}}, + ... {'id': 2, 'name': 'Faye Raker'}] + >>> json_normalize(data) + id name name.family name.first name.given name.last + 0 1.0 NaN NaN Coleen NaN Volk + 1 NaN NaN Regner NaN Mose NaN + 2 2.0 Faye Raker NaN NaN NaN NaN + >>> data = [{'state': 'Florida', ... 'shortname': 'FL', ... 'info': { @@ -150,7 +160,6 @@ def json_normalize(data, record_path=None, meta=None, ... }, ... 'counties': [{'name': 'Summit', 'population': 1234}, ... {'name': 'Cuyahoga', 'population': 1337}]}] - >>> from pandas.io.json import json_normalize >>> result = json_normalize(data, 'counties', ['state', 'shortname', ... ['info', 'governor']]) >>> result
- [v ] closes #16415 - [v ] tests added / passed - [v ] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16438
2017-05-22T21:59:17Z
2017-08-18T15:27:21Z
2017-08-18T15:27:20Z
2017-08-18T16:02:38Z
[Issue: #16416] Adding examples for some DataFrame methods
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2e7d8693d48dd..126e6846c8970 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2055,6 +2055,37 @@ def drop(self, labels, axis=0, level=None, inplace=False, errors='raise'): Returns ------- dropped : type of caller + + Examples + -------- + >>> df = pd.DataFrame([[1, 2, 3, 4], + ... [5, 6, 7, 8], + ... [9, 1, 2, 3], + ... [4, 5, 6, 7] + ... ], + ... columns=list('ABCD')) + >>> df + A B C D + 0 1 2 3 4 + 1 5 6 7 8 + 2 9 1 2 3 + 3 4 5 6 7 + + Drop a row by index + + >>> df.drop([0, 1]) + A B C D + 2 9 1 2 3 + 3 4 5 6 7 + + Drop columns + + >>> df.drop(['A', 'B'], axis=1) + C D + 0 3 4 + 1 7 8 + 2 2 3 + 3 6 7 """ inplace = validate_bool_kwarg(inplace, 'inplace') axis = self._get_axis_number(axis) @@ -2168,6 +2199,66 @@ def add_suffix(self, suffix): Returns ------- sorted_obj : %(klass)s + + Examples + -------- + >>> df = pd.DataFrame({ + ... 'col1' : ['A', 'A', 'B', np.nan, 'D', 'C'], + ... 'col2' : [2, 1, 9, 8, 7, 4], + ... 'col3': [0, 1, 9, 4, 2, 3], + ... }) + >>> df + col1 col2 col3 + 0 A 2 0 + 1 A 1 1 + 2 B 9 9 + 3 NaN 8 4 + 4 D 7 2 + 5 C 4 3 + + Sort by col1 + + >>> df.sort_values(by=['col1']) + col1 col2 col3 + 0 A 2 0 + 1 A 1 1 + 2 B 9 9 + 5 C 4 3 + 4 D 7 2 + 3 NaN 8 4 + + Sort by multiple columns + + >>> df.sort_values(by=['col1', 'col2']) + col1 col2 col3 + 1 A 1 1 + 0 A 2 0 + 2 B 9 9 + 5 C 4 3 + 4 D 7 2 + 3 NaN 8 4 + + Sort Descending + + >>> df.sort_values(by='col1', ascending=False) + col1 col2 col3 + 4 D 7 2 + 5 C 4 3 + 2 B 9 9 + 0 A 2 0 + 1 A 1 1 + 3 NaN 8 4 + + Putting NAs first + + >>> df.sort_values(by='col1', ascending=False, na_position='first') + col1 col2 col3 + 3 NaN 8 4 + 4 D 7 2 + 5 C 4 3 + 2 B 9 9 + 0 A 2 0 + 1 A 1 1 """ def sort_values(self, by, axis=0, ascending=True, inplace=False, @@ -3468,6 +3559,58 @@ def convert_objects(self, convert_dates=True, convert_numeric=False, Returns ------- filled : %(klass)s + + Examples + -------- + >>> df = pd.DataFrame([[np.nan, 2, np.nan, 0], + ... [3, 4, np.nan, 1], + ... [np.nan, np.nan, np.nan, 5], + ... [np.nan, 3, np.nan, 4]], + ... columns=list('ABCD')) + >>> df + A B C D + 0 NaN 2.0 NaN 0 + 1 3.0 4.0 NaN 1 + 2 NaN NaN NaN 5 + 3 NaN 3.0 NaN 4 + + Replace all NaN elements with 0s. + + >>> df.fillna(0) + A B C D + 0 0.0 2.0 0.0 0 + 1 3.0 4.0 0.0 1 + 2 0.0 0.0 0.0 5 + 3 0.0 3.0 0.0 4 + + We can also propagate non-null values forward or backward. + + >>> df.fillna(method='ffill') + A B C D + 0 NaN 2.0 NaN 0 + 1 3.0 4.0 NaN 1 + 2 3.0 4.0 NaN 5 + 3 3.0 3.0 NaN 4 + + Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1, + 2, and 3 respectively. + + >>> values = {'A': 0, 'B': 1, 'C': 2, 'D': 3} + >>> df.fillna(value=values) + A B C D + 0 0.0 2.0 2.0 0 + 1 3.0 4.0 2.0 1 + 2 0.0 1.0 2.0 5 + 3 0.0 3.0 2.0 4 + + Only replace the first NaN element. + + >>> df.fillna(value=values, limit=1) + A B C D + 0 0.0 2.0 2.0 0 + 1 3.0 4.0 NaN 1 + 2 NaN 1.0 NaN 5 + 3 NaN 3.0 NaN 4 """) @Appender(_shared_docs['fillna'] % _shared_doc_kwargs)
Adding examples for [`fillna`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html), [`drop`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html), and [`sort_values`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html). - [x] related to #16416 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16437
2017-05-22T21:57:33Z
2017-05-25T17:44:37Z
2017-05-25T17:44:37Z
2017-05-25T17:44:45Z
change merge validate errors to MergeError from ValueError
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 3734dc15be2e9..d01b097ee1529 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -30,7 +30,7 @@ New features Other Enhancements ^^^^^^^^^^^^^^^^^^ -- The ``validate`` argument for :func:`merge` function now checks whether a merge is one-to-one, one-to-many, many-to-one, or many-to-many. If a merge is found to not be an example of specified merge type, an exception will be raised. For more, see :ref:`here <merging.validation>` (:issue:`16270`) +- The ``validate`` argument for :func:`merge` function now checks whether a merge is one-to-one, one-to-many, many-to-one, or many-to-many. If a merge is found to not be an example of specified merge type, an exception of type ``MergeError`` will be raised. For more, see :ref:`here <merging.validation>` (:issue:`16270`) - ``Series.to_dict()`` and ``DataFrame.to_dict()`` now support an ``into`` keyword which allows you to specify the ``collections.Mapping`` subclass that you would like returned. The default is ``dict``, which is backwards compatible. (:issue:`16122`) - ``RangeIndex.append`` now returns a ``RangeIndex`` object when possible (:issue:`16212`) - :func:`to_pickle` has gained a protocol parameter (:issue:`16252`). By default, this parameter is set to `HIGHEST_PROTOCOL <https://docs.python.org/3/library/pickle.html#data-stream-format>`__ @@ -51,6 +51,7 @@ Backwards incompatible API changes Other API Changes ^^^^^^^^^^^^^^^^^ +- Moved definition of ``MergeError`` to the ``pandas.errors`` module. .. _whatsnew_0210.deprecations: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index b5c483a52f14f..ffe0cac33ec8f 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -40,6 +40,7 @@ import pandas.core.algorithms as algos import pandas.core.common as com from pandas._libs import hashtable as libhashtable, join as libjoin, lib +from pandas.errors import MergeError @Substitution('\nleft : DataFrame') @@ -60,10 +61,6 @@ def merge(left, right, how='inner', on=None, left_on=None, right_on=None, merge.__doc__ = _merge_doc % '\nleft : DataFrame' -class MergeError(ValueError): - pass - - def _groupby_and_merge(by, on, left, right, _merge_pieces, check_duplicates=True): """ @@ -986,23 +983,23 @@ def _validate(self, validate): # Check data integrity if validate in ["one_to_one", "1:1"]: if not left_unique and not right_unique: - raise ValueError("Merge keys are not unique in either left" + raise MergeError("Merge keys are not unique in either left" " or right dataset; not a one-to-one merge") elif not left_unique: - raise ValueError("Merge keys are not unique in left dataset;" + raise MergeError("Merge keys are not unique in left dataset;" " not a one-to-one merge") elif not right_unique: - raise ValueError("Merge keys are not unique in right dataset;" + raise MergeError("Merge keys are not unique in right dataset;" " not a one-to-one merge") elif validate in ["one_to_many", "1:m"]: if not left_unique: - raise ValueError("Merge keys are not unique in left dataset;" + raise MergeError("Merge keys are not unique in left dataset;" "not a one-to-many merge") elif validate in ["many_to_one", "m:1"]: if not right_unique: - raise ValueError("Merge keys are not unique in right dataset;" + raise MergeError("Merge keys are not unique in right dataset;" " not a many-to-one merge") elif validate in ['many_to_many', 'm:m']: diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index 805e689dca840..6304f3a527f2c 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -57,3 +57,9 @@ class ParserWarning(Warning): """ +class MergeError(ValueError): + """ + Error raised when problems arise during merging due to problems + with input data. Subclass of `ValueError`. + + """ diff --git a/pandas/tests/reshape/test_merge.py b/pandas/tests/reshape/test_merge.py index 16c58354ad5c9..bacb605199e4a 100644 --- a/pandas/tests/reshape/test_merge.py +++ b/pandas/tests/reshape/test_merge.py @@ -789,11 +789,11 @@ def test_validation(self): merge(left, right_w_dups, left_index=True, right_index=True, validate='one_to_many') - with pytest.raises(ValueError): + with pytest.raises(MergeError): merge(left, right_w_dups, left_index=True, right_index=True, validate='one_to_one') - with pytest.raises(ValueError): + with pytest.raises(MergeError): merge(left, right_w_dups, on='a', validate='one_to_one') # Dups on left @@ -802,21 +802,21 @@ def test_validation(self): merge(left_w_dups, right, left_index=True, right_index=True, validate='many_to_one') - with pytest.raises(ValueError): + with pytest.raises(MergeError): merge(left_w_dups, right, left_index=True, right_index=True, validate='one_to_one') - with pytest.raises(ValueError): + with pytest.raises(MergeError): merge(left_w_dups, right, on='a', validate='one_to_one') # Dups on both merge(left_w_dups, right_w_dups, on='a', validate='many_to_many') - with pytest.raises(ValueError): + with pytest.raises(MergeError): merge(left_w_dups, right_w_dups, left_index=True, right_index=True, validate='many_to_one') - with pytest.raises(ValueError): + with pytest.raises(MergeError): merge(left_w_dups, right_w_dups, on='a', validate='one_to_many') @@ -842,7 +842,7 @@ def test_validation(self): 'um... weasel noise?']}, index=range(3)) - with pytest.raises(ValueError): + with pytest.raises(MergeError): merge(left, right, on='a', validate='1:1') result = merge(left, right, on=['a', 'b'], validate='1:1') diff --git a/pandas/tests/test_errors.py b/pandas/tests/test_errors.py index 4a0850734e134..babf88ef1df8d 100644 --- a/pandas/tests/test_errors.py +++ b/pandas/tests/test_errors.py @@ -10,7 +10,7 @@ "exc", ['UnsupportedFunctionCall', 'UnsortedIndexError', 'OutOfBoundsDatetime', 'ParserError', 'PerformanceWarning', 'DtypeWarning', - 'EmptyDataError', 'ParserWarning']) + 'EmptyDataError', 'ParserWarning', 'MergeError']) def test_exception_importable(exc): from pandas import errors e = getattr(errors, exc)
Final changes from #16275 that failed to push before merge. Converts errors from `validate` argument of `merge` command to `MergeError`s from `ValueError`s.
https://api.github.com/repos/pandas-dev/pandas/pulls/16436
2017-05-22T21:12:23Z
2017-05-23T09:10:12Z
2017-05-23T09:10:12Z
2017-05-23T09:10:21Z
Add README improvements.
diff --git a/README.md b/README.md index e05f1405419fc..01182d7b7b4b5 100644 --- a/README.md +++ b/README.md @@ -204,13 +204,13 @@ python setup.py build --compiler=mingw32 python setup.py install ``` -See http://pandas.pydata.org/ for more information. +See **[the docs](http://pandas.pydata.org/pandas-docs/stable/install.html#installing-from-source)** for more information. ## License BSD ## Documentation -The official documentation is hosted on PyData.org: http://pandas.pydata.org/ +The official documentation is hosted on PyData.org: http://pandas.pydata.org/pandas-docs/stable/ The Sphinx documentation should provide a good starting point for learning how to use the library. Expect the docs to continue to expand as time goes on. @@ -219,10 +219,21 @@ to use the library. Expect the docs to continue to expand as time goes on. Work on ``pandas`` started at AQR (a quantitative hedge fund) in 2008 and has been under active development since then. +## Getting Help + +For usage questions, the best place to go to is [StackOverflow](https://stackoverflow.com/questions/tagged/pandas). +Further, general questions and discussions can also take place on the [pydata mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata). + ## Discussion and Development -Since pandas development is related to a number of other scientific -Python projects, questions are welcome on the scipy-user mailing -list. Specialized discussions or design issues should take place on -the PyData mailing list / Google group: +Most development discussion is taking place on github in this repo. Further, the [pandas-dev mailing list](https://mail.python.org/mailman/listinfo/pandas-dev) can also be used for specialized discussions or design issues, and a [Gitter channel](https://gitter.im/pydata/pandas) is available for quick development related questions. + +## Contributing to pandas +All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. + +A detailed overview on how to contribute can be found in the **[contributing guide.](http://pandas.pydata.org/pandas-docs/stable/contributing.html)** + +If you are simply looking to start working with the pandas codebase, navigate to the [GitHub “issues” tab](https://github.com/pandas-dev/pandas/issues) and start looking through interesting issues. There are a number of issues listed under [Docs](https://github.com/pandas-dev/pandas/issues?labels=Docs&sort=updated&state=open) and [Difficulty Novice](https://github.com/pandas-dev/pandas/issues?q=is%3Aopen+is%3Aissue+label%3A%22Difficulty+Novice%22) where you could start out. + +Or maybe through using pandas you have an idea of your own or are looking for something in the documentation and thinking ‘this can be improved’...you can do something about it! -https://groups.google.com/forum/#!forum/pydata +Feel free to ask questions on the [mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata) or on [Gitter](https://gitter.im/pydata/pandas).
- [Y] closes #16427 - [Y] whatsnew entry ** Included reference to contribute guide in READEME. ** In the "installation from source" section, refer to the actual section in the docs, instead of to the general website ** Update "Discussion and Development" section: remove reference to scipy mailing list, but add one to pandas-dev mailing list
https://api.github.com/repos/pandas-dev/pandas/pulls/16435
2017-05-22T21:10:34Z
2017-05-23T08:17:00Z
2017-05-23T08:17:00Z
2017-05-24T00:17:21Z
BUG: fix isin with Series of tuples values (#16394)
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index e0857019d2fd4..57625b725ddba 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -80,7 +80,7 @@ Reshaping ^^^^^^^^^ - Bug in ``DataFrame.stack`` with unsorted levels in MultiIndex columns (:issue:`16323`) - +- Bug in ``Series.isin(..)`` with a list of tuples (:issue:`16394`) Numeric ^^^^^^^ diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index a745ec616eda8..77d79c9585e57 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -388,7 +388,7 @@ def isin(comps, values): "[{0}]".format(type(values).__name__)) if not isinstance(values, (ABCIndex, ABCSeries, np.ndarray)): - values = np.array(list(values), dtype='object') + values = lib.list_to_object_array(list(values)) comps, dtype, _ = _ensure_data(comps) values, _, _ = _ensure_data(values, dtype=dtype) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index fa9823bf000a2..da96fce36f3c9 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1201,6 +1201,14 @@ def test_isin_df(self): expected['B'] = False tm.assert_frame_equal(result, expected) + def test_isin_tuples(self): + # GH16394 + df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'f']}) + df['C'] = list(zip(df['A'], df['B'])) + result = df['C'].isin([(1, 'a')]) + tm.assert_series_equal(result, + Series([True, False, False], name="C")) + def test_isin_df_dupe_values(self): df1 = DataFrame({'A': [1, 2, 3, 4], 'B': [2, np.nan, 4, 4]}) # just cols duped
Switched out values = np.array(list(values), dtype='object') for values = lib.list_to_object_array(list(values)) in the isin() method found in core/algorithms.py Added test for comparing to a list of tuples - [ ] closes #16394 - [ ] tests added / passed - [ ] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16434
2017-05-22T20:03:21Z
2017-05-23T07:51:07Z
2017-05-23T07:51:07Z
2017-05-30T12:20:22Z
BUG: adding numpy errstate to dataframe/series broadcasting (GH16378)
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index e0857019d2fd4..04a63f98e0f7a 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -42,6 +42,7 @@ Conversion ^^^^^^^^^^ - Bug in ``pd.to_numeric()`` in which empty data inputs were causing Python to crash (:issue:`16302`) +- Silence numpy warnings when broadcasting DataFrame to Series with comparison ops (:issue:`16378`, :issue:`16306`) Indexing diff --git a/pandas/core/ops.py b/pandas/core/ops.py index e7cfbdb0fc9c6..55473ec8d7cad 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -1250,7 +1250,8 @@ def _flex_comp_method_FRAME(op, name, str_rep=None, default_axis='columns', masker=False): def na_op(x, y): try: - result = op(x, y) + with np.errstate(invalid='ignore'): + result = op(x, y) except TypeError: xrav = x.ravel() result = np.empty(x.size, dtype=bool) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index fa9823bf000a2..aa3604b86f3cb 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -2073,3 +2073,16 @@ def test_n_duplicate_index(self, df_duplicates, n, order): result = df.nlargest(n, order) expected = df.sort_values(order, ascending=False).head(n) tm.assert_frame_equal(result, expected) + + def test_series_broadcasting(self): + # smoke test for numpy warnings + # GH 16378, GH 16306 + df = DataFrame([1.0, 1.0, 1.0]) + df_nan = DataFrame({'A': [np.nan, 2.0, np.nan]}) + s = Series([1, 1, 1]) + s_nan = Series([np.nan, np.nan, 1]) + + with tm.assert_produces_warning(None): + df_nan.clip_lower(s, axis=0) + for op in ['lt', 'le', 'gt', 'ge', 'eq', 'ne']: + getattr(df, op)(s_nan, axis=0)
closes #16378 closes #16306
https://api.github.com/repos/pandas-dev/pandas/pulls/16433
2017-05-22T19:48:26Z
2017-05-25T02:09:25Z
2017-05-25T02:09:25Z
2017-05-30T12:20:22Z
DOC: correct docstring examples (#3439)
diff --git a/ci/build_docs.sh b/ci/build_docs.sh index 26917b8f9b792..a038304fe0f7a 100755 --- a/ci/build_docs.sh +++ b/ci/build_docs.sh @@ -59,6 +59,15 @@ if [ "$DOC" ]; then git remote -v git push origin gh-pages -f + + echo "Running doctests" + cd "$TRAVIS_BUILD_DIR" + pytest --doctest-modules \ + pandas/core/reshape/concat.py \ + pandas/core/reshape/pivot.py \ + pandas/core/reshape/reshape.py \ + pandas/core/reshape/tile.py + fi exit 0 diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index af2eb734a02f6..96603b6adc3b0 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -197,6 +197,8 @@ def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, 0 a 2 >>> pd.concat([df5, df6], verify_integrity=True) + Traceback (most recent call last): + ... ValueError: Indexes have overlapping values: ['a'] """ op = _Concatenator(objs, axis=axis, join_axes=join_axes, diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 74dbbfc00cb11..a9a5051965ece 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -50,26 +50,36 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', Examples -------- + >>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo", + ... "bar", "bar", "bar", "bar"], + ... "B": ["one", "one", "one", "two", "two", + ... "one", "one", "two", "two"], + ... "C": ["small", "large", "large", "small", + ... "small", "large", "small", "small", + ... "large"], + ... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7]}) >>> df - A B C D - 0 foo one small 1 - 1 foo one large 2 - 2 foo one large 2 - 3 foo two small 3 - 4 foo two small 3 - 5 bar one large 4 - 6 bar one small 5 - 7 bar two small 6 - 8 bar two large 7 + A B C D + 0 foo one small 1 + 1 foo one large 2 + 2 foo one large 2 + 3 foo two small 3 + 4 foo two small 3 + 5 bar one large 4 + 6 bar one small 5 + 7 bar two small 6 + 8 bar two large 7 >>> table = pivot_table(df, values='D', index=['A', 'B'], ... columns=['C'], aggfunc=np.sum) >>> table - small large - foo one 1 4 - two 6 NaN - bar one 5 4 - two 6 7 + ... # doctest: +NORMALIZE_WHITESPACE + C large small + A B + bar one 4.0 5.0 + two 7.0 6.0 + foo one 4.0 1.0 + two NaN 6.0 Returns ------- @@ -438,27 +448,27 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None, Examples -------- - >>> a - array([foo, foo, foo, foo, bar, bar, - bar, bar, foo, foo, foo], dtype=object) - >>> b - array([one, one, one, two, one, one, - one, two, two, two, one], dtype=object) - >>> c - array([dull, dull, shiny, dull, dull, shiny, - shiny, dull, shiny, shiny, shiny], dtype=object) - - >>> crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c']) - b one two - c dull shiny dull shiny + >>> a = np.array(["foo", "foo", "foo", "foo", "bar", "bar", + ... "bar", "bar", "foo", "foo", "foo"], dtype=object) + >>> b = np.array(["one", "one", "one", "two", "one", "one", + ... "one", "two", "two", "two", "one"], dtype=object) + >>> c = np.array(["dull", "dull", "shiny", "dull", "dull", "shiny", + ... "shiny", "dull", "shiny", "shiny", "shiny"], + ... dtype=object) + + >>> pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c']) + ... # doctest: +NORMALIZE_WHITESPACE + b one two + c dull shiny dull shiny a - bar 1 2 1 0 - foo 2 2 1 2 + bar 1 2 1 0 + foo 2 2 1 2 >>> foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c']) >>> bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f']) >>> crosstab(foo, bar) # 'c' and 'f' are not represented in the data, - # but they still will be counted in the output + ... # but they still will be counted in the output + ... # doctest: +SKIP col_0 d e f row_0 a 1 0 0 diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index f944dfe22361a..dcb83d225699d 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -48,23 +48,23 @@ class _Unstacker(object): >>> import pandas as pd >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'), ... ('two', 'a'), ('two', 'b')]) - >>> s = pd.Series(np.arange(1.0, 5.0), index=index) + >>> s = pd.Series(np.arange(1, 5, dtype=np.int64), index=index) >>> s - one a 1 - b 2 - two a 3 - b 4 - dtype: float64 + one a 1 + b 2 + two a 3 + b 4 + dtype: int64 >>> s.unstack(level=-1) - a b + a b one 1 2 two 3 4 >>> s.unstack(level=0) one two - a 1 2 - b 3 4 + a 1 3 + b 2 4 Returns ------- @@ -789,18 +789,18 @@ def lreshape(data, groups, dropna=True, label=None): >>> import pandas as pd >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526], ... 'team': ['Red Sox', 'Yankees'], - ... 'year1': [2007, 2008], 'year2': [2008, 2008]}) + ... 'year1': [2007, 2007], 'year2': [2008, 2008]}) >>> data hr1 hr2 team year1 year2 0 514 545 Red Sox 2007 2008 1 573 526 Yankees 2007 2008 >>> pd.lreshape(data, {'year': ['year1', 'year2'], 'hr': ['hr1', 'hr2']}) - team hr year - 0 Red Sox 514 2007 - 1 Yankees 573 2007 - 2 Red Sox 545 2008 - 3 Yankees 526 2008 + team year hr + 0 Red Sox 2007 514 + 1 Yankees 2007 573 + 2 Red Sox 2008 545 + 3 Yankees 2008 526 Returns ------- @@ -905,11 +905,12 @@ def wide_to_long(df, stubnames, i, j, sep="", suffix='\d+'): ... }) >>> df["id"] = df.index >>> df - A1970 A1980 B1970 B1980 X id + A1970 A1980 B1970 B1980 X id 0 a d 2.5 3.2 -1.085631 0 1 b e 1.2 1.3 0.997345 1 2 c f 0.7 0.1 0.282978 2 >>> pd.wide_to_long(df, ["A", "B"], i="id", j="year") + ... # doctest: +NORMALIZE_WHITESPACE X A B id year 0 1970 -1.085631 a 2.5 @@ -940,6 +941,7 @@ def wide_to_long(df, stubnames, i, j, sep="", suffix='\d+'): 8 3 3 2.1 2.9 >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age') >>> l + ... # doctest: +NORMALIZE_WHITESPACE ht famid birth age 1 1 1 2.8 @@ -979,41 +981,44 @@ def wide_to_long(df, stubnames, i, j, sep="", suffix='\d+'): Less wieldy column names are also handled + >>> np.random.seed(0) >>> df = pd.DataFrame({'A(quarterly)-2010': np.random.rand(3), ... 'A(quarterly)-2011': np.random.rand(3), ... 'B(quarterly)-2010': np.random.rand(3), ... 'B(quarterly)-2011': np.random.rand(3), ... 'X' : np.random.randint(3, size=3)}) >>> df['id'] = df.index - >>> df - A(quarterly)-2010 A(quarterly)-2011 B(quarterly)-2010 B(quarterly)-2011 - 0 0.531828 0.724455 0.322959 0.293714 - 1 0.634401 0.611024 0.361789 0.630976 - 2 0.849432 0.722443 0.228263 0.092105 - \ + >>> df # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS + A(quarterly)-2010 A(quarterly)-2011 B(quarterly)-2010 ... + 0 0.548814 0.544883 0.437587 ... + 1 0.715189 0.423655 0.891773 ... + 2 0.602763 0.645894 0.963663 ... X id 0 0 0 1 1 1 - 2 2 2 - >>> pd.wide_to_long(df, ['A(quarterly)', 'B(quarterly)'], - i='id', j='year', sep='-') - X A(quarterly) B(quarterly) + 2 1 2 + + >>> pd.wide_to_long(df, ['A(quarterly)', 'B(quarterly)'], i='id', + ... j='year', sep='-') + ... # doctest: +NORMALIZE_WHITESPACE + X A(quarterly) B(quarterly) id year - 0 2010 0 0.531828 0.322959 - 1 2010 2 0.634401 0.361789 - 2 2010 2 0.849432 0.228263 - 0 2011 0 0.724455 0.293714 - 1 2011 2 0.611024 0.630976 - 2 2011 2 0.722443 0.092105 + 0 2010 0 0.548814 0.437587 + 1 2010 1 0.715189 0.891773 + 2 2010 1 0.602763 0.963663 + 0 2011 0 0.544883 0.383442 + 1 2011 1 0.423655 0.791725 + 2 2011 1 0.645894 0.528895 If we have many columns, we could also use a regex to find our stubnames and pass that list on to wide_to_long - >>> stubnames = set([match[0] for match in - df.columns.str.findall('[A-B]\(.*\)').values - if match != [] ]) + >>> stubnames = sorted( + ... set([match[0] for match in df.columns.str.findall( + ... r'[A-B]\(.*\)').values if match != [] ]) + ... ) >>> list(stubnames) - ['B(quarterly)', 'A(quarterly)'] + ['A(quarterly)', 'B(quarterly)'] Notes ----- @@ -1133,7 +1138,7 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, 2 0 0 1 >>> df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'], - 'C': [1, 2, 3]}) + ... 'C': [1, 2, 3]}) >>> pd.get_dummies(df, prefix=['col1', 'col2']) C col1_a col1_b col2_a col2_b col2_c @@ -1149,7 +1154,7 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, 3 1 0 0 4 1 0 0 - >>> pd.get_dummies(pd.Series(list('abcaa')), drop_first=True)) + >>> pd.get_dummies(pd.Series(list('abcaa')), drop_first=True) b c 0 0 0 1 1 0 diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 746742f47f2aa..866f229bec418 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -75,18 +75,18 @@ def cut(x, bins, right=True, labels=None, retbins=False, precision=3, Examples -------- >>> pd.cut(np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1]), 3, retbins=True) - ([(0.191, 3.367], (0.191, 3.367], (0.191, 3.367], (3.367, 6.533], - (6.533, 9.7], (0.191, 3.367]] - Categories (3, object): [(0.191, 3.367] < (3.367, 6.533] < (6.533, 9.7]], - array([ 0.1905 , 3.36666667, 6.53333333, 9.7 ])) + ... # doctest: +ELLIPSIS + ([(0.19, 3.367], (0.19, 3.367], (0.19, 3.367], (3.367, 6.533], ... + Categories (3, interval[float64]): [(0.19, 3.367] < (3.367, 6.533] ... - >>> pd.cut(np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1]), 3, - labels=["good","medium","bad"]) + >>> pd.cut(np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1]), + ... 3, labels=["good", "medium", "bad"]) + ... # doctest: +SKIP [good, good, good, medium, bad, good] Categories (3, object): [good < medium < bad] >>> pd.cut(np.ones(5), 4, labels=False) - array([1, 1, 1, 1, 1], dtype=int64) + array([1, 1, 1, 1, 1]) """ # NOTE: this binning code is changed a bit from histogram for var(x) == 0 @@ -182,15 +182,17 @@ def qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise'): Examples -------- >>> pd.qcut(range(5), 4) - [[0, 1], [0, 1], (1, 2], (2, 3], (3, 4]] - Categories (4, object): [[0, 1] < (1, 2] < (2, 3] < (3, 4]] + ... # doctest: +ELLIPSIS + [(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]] + Categories (4, interval[float64]): [(-0.001, 1.0] < (1.0, 2.0] ... - >>> pd.qcut(range(5), 3, labels=["good","medium","bad"]) + >>> pd.qcut(range(5), 3, labels=["good", "medium", "bad"]) + ... # doctest: +SKIP [good, good, medium, bad, bad] Categories (3, object): [good < medium < bad] >>> pd.qcut(range(5), 4, labels=False) - array([0, 0, 1, 2, 3], dtype=int64) + array([0, 0, 1, 2, 3]) """ x_is_series, series_index, name, x = _preprocess_for_cut(x)
xref #3439
https://api.github.com/repos/pandas-dev/pandas/pulls/16432
2017-05-22T19:48:17Z
2017-05-31T09:37:49Z
2017-05-31T09:37:49Z
2017-05-31T09:37:49Z
15819 rolling window on empty df
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index e0857019d2fd4..03afc11156cc2 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -38,6 +38,7 @@ Bug Fixes - Bug in using ``pathlib.Path`` or ``py.path.local`` objects with io functions (:issue:`16291`) + Conversion ^^^^^^^^^^ @@ -68,7 +69,7 @@ Plotting Groupby/Resample/Rolling ^^^^^^^^^^^^^^^^^^^^^^^^ - +- Bug creating datetime rolling window on an empty DataFrame (:issue:`15819`) Sparse diff --git a/pandas/core/window.py b/pandas/core/window.py index df8e0c05009f4..cf1bad706ae1d 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -1074,7 +1074,7 @@ def validate(self): super(Rolling, self).validate() # we allow rolling on a datetimelike index - if (self.is_datetimelike and + if ((self.obj.empty or self.is_datetimelike) and isinstance(self.window, (compat.string_types, DateOffset, timedelta))): diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 634cd5fe2586b..6a640d62108b3 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -441,6 +441,20 @@ def test_closed(self): with pytest.raises(ValueError): df.rolling(window=3, closed='neither') + @pytest.mark.parametrize('roller', ['1s', 1]) + def tests_empty_df_rolling(self, roller): + # GH 15819 Verifies that datetime and integer rolling windows can be + # applied to empty DataFrames + expected = DataFrame() + result = DataFrame().rolling(roller).sum() + tm.assert_frame_equal(result, expected) + + # Verifies that datetime and integer rolling windows can be applied to + # empty DataFrames with datetime index + expected = DataFrame(index=pd.DatetimeIndex([])) + result = DataFrame(index=pd.DatetimeIndex([])).rolling(roller).sum() + tm.assert_frame_equal(result, expected) + class TestExpanding(Base): @@ -483,6 +497,24 @@ def test_numpy_compat(self): tm.assert_raises_regex(UnsupportedFunctionCall, msg, getattr(e, func), dtype=np.float64) + @pytest.mark.parametrize( + 'expander', + [1, pytest.mark.xfail( + reason='GH 16425 expanding with offset not supported')('1s')]) + def tests_empty_df_expanding(self, expander): + # GH 15819 Verifies that datetime and integer expanding windows can be + # applied to empty DataFrames + expected = DataFrame() + result = DataFrame().expanding(expander).sum() + tm.assert_frame_equal(result, expected) + + # Verifies that datetime and integer expanding windows can be applied + # to empty DataFrames with datetime index + expected = DataFrame(index=pd.DatetimeIndex([])) + result = DataFrame( + index=pd.DatetimeIndex([])).expanding(expander).sum() + tm.assert_frame_equal(result, expected) + class TestEWM(Base):
- [x] closes #15819 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16431
2017-05-22T19:46:27Z
2017-05-25T10:23:19Z
2017-05-25T10:23:19Z
2017-05-30T12:20:22Z
BUG: handle nan values in DataFrame.update when overwrite=False (#15593)
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 6d6a148ed025f..737de38cbc3e2 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -37,6 +37,7 @@ Bug Fixes ~~~~~~~~~ - Bug in using ``pathlib.Path`` or ``py.path.local`` objects with io functions (:issue:`16291`) +- Bug in ``DataFrame.update()`` with ``overwrite=False`` and ``NaN values`` (:issue:`15593`) Conversion ^^^^^^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 78a369761afc1..beea0e9d3d8ad 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3921,13 +3921,13 @@ def update(self, other, join='left', overwrite=True, filter_func=None, if overwrite: mask = isnull(that) - - # don't overwrite columns unecessarily - if mask.all(): - continue else: mask = notnull(this) + # don't overwrite columns unecessarily + if mask.all(): + continue + self[col] = expressions.where(mask, this, that, raise_on_error=True) diff --git a/pandas/tests/frame/test_combine_concat.py b/pandas/tests/frame/test_combine_concat.py index 688cacdee263e..f32efccf85fc6 100644 --- a/pandas/tests/frame/test_combine_concat.py +++ b/pandas/tests/frame/test_combine_concat.py @@ -763,3 +763,25 @@ def test_concat_datetime_datetime64_frame(self): # it works! pd.concat([df1, df2_obj]) + + +class TestDataFrameUpdate(TestData): + + def test_update_nan(self): + # #15593 #15617 + # test 1 + df1 = DataFrame({'A': [1.0, 2, 3], 'B': date_range('2000', periods=3)}) + df2 = DataFrame({'A': [None, 2, 3]}) + expected = df1.copy() + df1.update(df2, overwrite=False) + + tm.assert_frame_equal(df1, expected) + + # test 2 + df1 = DataFrame({'A': [1.0, None, 3], 'B': date_range('2000', periods=3)}) + df2 = DataFrame({'A': [None, 2, 3]}) + expected = DataFrame({'A': [1.0, 2, 3], 'B': date_range('2000', periods=3)}) + df1.update(df2, overwrite=False) + + tm.assert_frame_equal(df1, expected) +
BUG: handle nan values in DataFrame.update when overwrite=False (#15593) add nan test for DataFrame.update update whatsnew v0.20.2 - [x] closes #15593 closes #15617 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16430
2017-05-22T19:38:49Z
2017-05-24T23:15:32Z
2017-05-24T23:15:32Z
2017-05-30T12:20:22Z
BUG: Interpolate limit=n GH16282
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index e0a8065d9a507..74a0212e9a4f7 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -77,7 +77,7 @@ Reshaping Numeric ^^^^^^^ - +- Bug in .interpolate(), where limit_direction was not respected when limit=None (default) was passed (:issue:16282) diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 3010348423340..51778684d68f5 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -160,35 +160,41 @@ def _interp_limit(invalid, fw_limit, bw_limit): start_nans = set(range(ys.first_valid_index())) end_nans = set(range(1 + ys.last_valid_index(), len(valid))) - # This is a list of the indexes in the series whose yvalue is currently - # NaN, but whose interpolated yvalue will be overwritten with NaN after - # computing the interpolation. For each index in this list, one of these - # conditions is true of the corresponding NaN in the yvalues: + # violate_limit is a list of the indexes in the series whose yvalue is + # currently NaN, and should still be NaN after the interpolation. + # Specifically: # - # a) It is one of a chain of NaNs at the beginning of the series, and - # either limit is not specified or limit_direction is 'forward'. - # b) It is one of a chain of NaNs at the end of the series, and limit is - # specified and limit_direction is 'backward' or 'both'. - # c) Limit is nonzero and it is further than limit from the nearest non-NaN - # value (with respect to the limit_direction setting). + # If limit_direction='forward' or None then the list will contain NaNs at + # the beginning of the series, and NaNs that are more than 'limit' away + # from the prior non-NaN. # - # The default behavior is to fill forward with no limit, ignoring NaNs at - # the beginning (see issues #9218 and #10420) - violate_limit = sorted(start_nans) - - if limit is not None: - if not is_integer(limit): - raise ValueError('Limit must be an integer') - if limit < 1: - raise ValueError('Limit must be greater than 0') - if limit_direction == 'forward': - violate_limit = sorted(start_nans | set(_interp_limit(invalid, - limit, 0))) - if limit_direction == 'backward': - violate_limit = sorted(end_nans | set(_interp_limit(invalid, 0, - limit))) - if limit_direction == 'both': - violate_limit = sorted(_interp_limit(invalid, limit, limit)) + # If limit_direction='backward' then the list will contain NaNs at + # the end of the series, and NaNs that are more than 'limit' away + # from the subsequent non-NaN. + # + # If limit_direction='both' then the list will contain NaNs that + # are more than 'limit' away from any non-NaN. + # + # If limit=None, then use default behavior of filling an unlimited number + # of NaNs in the direction specified by limit_direction + + # default limit is unlimited GH #16282 + if limit is None: + limit = len(xvalues) + elif not is_integer(limit): + raise ValueError('Limit must be an integer') + elif limit < 1: + raise ValueError('Limit must be greater than 0') + + # each possible limit_direction + if limit_direction == 'forward': + violate_limit = sorted(start_nans | + set(_interp_limit(invalid, limit, 0))) + elif limit_direction == 'backward': + violate_limit = sorted(end_nans | + set(_interp_limit(invalid, 0, limit))) + elif limit_direction == 'both': + violate_limit = sorted(_interp_limit(invalid, limit, limit)) xvalues = getattr(xvalues, 'values', xvalues) yvalues = getattr(yvalues, 'values', yvalues) diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index c52c41877d5c0..8e73c17684a16 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -931,6 +931,24 @@ def test_interp_limit_forward(self): limit_direction='FORWARD') assert_series_equal(result, expected) + def test_interp_unlimited(self): + # these test are for issue #16282 default Limit=None is unlimited + s = Series([np.nan, 1., 3., np.nan, np.nan, np.nan, 11., np.nan]) + expected = Series([1., 1., 3., 5., 7., 9., 11., 11.]) + result = s.interpolate(method='linear', + limit_direction='both') + assert_series_equal(result, expected) + + expected = Series([np.nan, 1., 3., 5., 7., 9., 11., 11.]) + result = s.interpolate(method='linear', + limit_direction='forward') + assert_series_equal(result, expected) + + expected = Series([1., 1., 3., 5., 7., 9., 11., np.nan]) + result = s.interpolate(method='linear', + limit_direction='backward') + assert_series_equal(result, expected) + def test_interp_limit_bad_direction(self): s = Series([1, 3, np.nan, np.nan, np.nan, 11]) diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index d7dbaccb87ee8..77ef535e08964 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -16,6 +16,7 @@ def test_mut_exclusive(): com._mut_exclusive(a=1, b=2) assert com._mut_exclusive(a=1, b=None) == 1 assert com._mut_exclusive(major=None, major_axis=None) is None + assert com._mut_exclusive(a=None, b=2) == 2 def test_get_callable_name():
- [x] closes #16282 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16429
2017-05-22T19:32:28Z
2017-05-23T15:59:17Z
2017-05-23T15:59:16Z
2017-06-03T00:14:50Z
Error with .drop([]) on non-unique index
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index e0857019d2fd4..7231b497c4bd4 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -93,3 +93,5 @@ Categorical Other ^^^^^ + +- Bug in ``pd.drop([])`` for DataFrame with non-unique indices (:issue:`16270`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2e7d8693d48dd..b19a0751ea2e4 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -12,6 +12,7 @@ from pandas._libs import tslib, lib from pandas.core.dtypes.common import ( _ensure_int64, + _ensure_object, needs_i8_conversion, is_scalar, is_number, @@ -2076,7 +2077,7 @@ def drop(self, labels, axis=0, level=None, inplace=False, errors='raise'): result = dropped else: - labels = com._index_labels_to_array(labels) + labels = _ensure_object(com._index_labels_to_array(labels)) if level is not None: if not isinstance(axis, MultiIndex): raise AssertionError('axis must be a MultiIndex') diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index a6326083c1bee..87d942101f5f1 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -61,6 +61,11 @@ def test_drop_names(self): expected = Index(['e', 'f'], name='second') tm.assert_index_equal(dropped.columns, expected) + # GH 16398 + dropped = df.drop([], errors='ignore') + expected = Index(['a', 'b', 'c'], name='first') + tm.assert_index_equal(dropped.index, expected) + def test_drop_col_still_multiindex(self): arrays = [['a', 'b', 'c', 'top'], ['', '', '', 'OD'], @@ -100,6 +105,7 @@ def test_drop(self): columns=['a', 'a', 'b']) assert_frame_equal(nu_df.drop('a', axis=1), nu_df[['b']]) assert_frame_equal(nu_df.drop('b', axis='columns'), nu_df['a']) + assert_frame_equal(nu_df.drop([]), nu_df) # GH 16398 nu_df = nu_df.set_index(pd.Index(['X', 'Y', 'X'])) nu_df.columns = list('abc')
Wraps the labels array in `_ensure_object`. The labels array is being cast to a float by default, causing the error raised in #16398. - [X] closes #16398 - [X] tests added / passed - [X] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16428
2017-05-22T19:10:05Z
2017-05-24T23:24:14Z
2017-05-24T23:24:14Z
2017-05-30T12:20:22Z
ENH: Add the decimal.Decimal type to infer_dtypes (#15690)
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 3734dc15be2e9..857f1aaf48b42 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -34,6 +34,7 @@ Other Enhancements - ``Series.to_dict()`` and ``DataFrame.to_dict()`` now support an ``into`` keyword which allows you to specify the ``collections.Mapping`` subclass that you would like returned. The default is ``dict``, which is backwards compatible. (:issue:`16122`) - ``RangeIndex.append`` now returns a ``RangeIndex`` object when possible (:issue:`16212`) - :func:`to_pickle` has gained a protocol parameter (:issue:`16252`). By default, this parameter is set to `HIGHEST_PROTOCOL <https://docs.python.org/3/library/pickle.html#data-stream-format>`__ +- :func:`api.types.infer_dtype` now infers decimals. (:issue: `15690`) .. _whatsnew_0210.api_breaking: diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx index ddd38979e326c..38e95fe6ee652 100644 --- a/pandas/_libs/src/inference.pyx +++ b/pandas/_libs/src/inference.pyx @@ -243,6 +243,7 @@ def infer_dtype(object value): - integer - mixed-integer - mixed-integer-float + - decimal - complex - categorical - boolean @@ -286,6 +287,9 @@ def infer_dtype(object value): >>> infer_dtype(['a', 1]) 'mixed-integer' + >>> infer_dtype([Decimal(1), Decimal(2.0)]) + 'decimal' + >>> infer_dtype([True, False]) 'boolean' @@ -308,7 +312,6 @@ def infer_dtype(object value): 'categorical' """ - cdef: Py_ssize_t i, n object val @@ -407,6 +410,9 @@ def infer_dtype(object value): if is_time_array(values): return 'time' + elif is_decimal(val): + return 'decimal' + elif util.is_float_object(val): if is_float_array(values): return 'floating' diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 3790ebe0d3e7c..b88481abcb2ec 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -9,6 +9,7 @@ import collections import re from datetime import datetime, date, timedelta, time +from decimal import Decimal import numpy as np import pytz import pytest @@ -462,6 +463,16 @@ def test_floats(self): result = lib.infer_dtype(arr) assert result == 'floating' + def test_decimals(self): + # GH15690 + arr = np.array([Decimal(1), Decimal(2), Decimal(3)]) + result = lib.infer_dtype(arr) + assert result == 'decimal' + + arr = np.array([1.0, 2.0, Decimal(3)]) + result = lib.infer_dtype(arr) + assert result == 'mixed' + def test_string(self): pass
- [x] closes #15690 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16426
2017-05-22T18:55:46Z
2017-05-23T10:56:31Z
2017-05-23T10:56:31Z
2017-05-23T10:56:35Z
Option Page Typos
diff --git a/doc/source/options.rst b/doc/source/options.rst index 5f6bf2fbb9662..6ff5b76014c95 100644 --- a/doc/source/options.rst +++ b/doc/source/options.rst @@ -28,7 +28,7 @@ You can get/set options directly as attributes of the top-level ``options`` attr pd.options.display.max_rows = 999 pd.options.display.max_rows -There is also an API composed of 5 relevant functions, available directly from the ``pandas`` +The API is composed of 5 relevant functions, available directly from the ``pandas`` namespace: - :func:`~pandas.get_option` / :func:`~pandas.set_option` - get/set the value of a single option. @@ -40,7 +40,7 @@ namespace: **Note:** developers can check out pandas/core/config.py for more info. All of the functions above accept a regexp pattern (``re.search`` style) as an argument, -and so passing in a substring will work - as long as it is unambiguous : +and so passing in a substring will work - as long as it is unambiguous: .. ipython:: python @@ -241,7 +241,7 @@ suggestion. df ``display.chop_threshold`` sets at what level pandas rounds to zero when -it displays a Series of DataFrame. Note, this does not effect the +it displays a Series of DataFrame. Note, this does not effect the precision at which the number is stored. .. ipython:: python @@ -420,15 +420,15 @@ mode.chained_assignment warn Raise an exception, warn, or no action if trying to use chained assignment, The default is warn mode.sim_interactive False Whether to simulate interactive mode - for purposes of testing + for purposes of testing. mode.use_inf_as_null False True means treat None, NaN, -INF, INF as null (old way), False means None and NaN are null, but INF, -INF are not null (new way). compute.use_bottleneck True Use the bottleneck library to accelerate - computation if it is installed + computation if it is installed. compute.use_numexpr True Use the numexpr library to accelerate - computation if it is installed + computation if it is installed. =================================== ============ ==================================
#### Problem description There are typos on this page and one confusing sentence. Trying to learn the workflow.
https://api.github.com/repos/pandas-dev/pandas/pulls/16421
2017-05-22T17:34:53Z
2017-05-22T17:47:49Z
2017-05-22T17:47:49Z
2017-05-22T18:31:21Z
SAS DOC update - add documentation for sas_read(format='sas7bdat')
diff --git a/doc/source/comparison_with_sas.rst b/doc/source/comparison_with_sas.rst index 7ec91d251f15d..875358521173a 100644 --- a/doc/source/comparison_with_sas.rst +++ b/doc/source/comparison_with_sas.rst @@ -577,9 +577,8 @@ Data Interop ~~~~~~~~~~~~ pandas provides a :func:`read_sas` method that can read SAS data saved in -the XPORT format. The ability to read SAS's binary format is planned for a -future release. - +the XPORT or SAS7BDAT binary format. + .. code-block:: none libname xportout xport 'transport-file.xpt'; @@ -591,6 +590,15 @@ future release. .. code-block:: python df = pd.read_sas('transport-file.xpt') + df = pd.read_sas('binary-file.sas7bdat') + +You can also specify the file format directly. By default, pandas will try +to infer the file format based on its extension. + +.. code-block:: python + + df = pd.read_sas('transport-file.xpt', format='xport') + df = pd.read_sas('binary-file.sas7bdat', format='sas7bdat') XPORT is a relatively limited format and the parsing of it is not as optimized as some of the other pandas readers. An alternative way @@ -605,3 +613,4 @@ to interop data between SAS and pandas is to serialize to csv. In [9]: %time df = pd.read_csv('big.csv') Wall time: 4.86 s +
- [ ] closes #12700
https://api.github.com/repos/pandas-dev/pandas/pulls/16420
2017-05-22T17:31:20Z
2017-05-22T17:49:50Z
2017-05-22T17:49:50Z
2017-05-22T18:18:38Z
COMPAT: Catch warnings on tab-complete in IPy 6
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 1f71710d19e44..eb9e31279616e 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -40,6 +40,10 @@ Bug Fixes - Bug in ``DataFrame.update()`` with ``overwrite=False`` and ``NaN values`` (:issue:`15593`) + +- Fixed a compatibility issue with IPython 6.0's tab completion showing deprecation warnings on Categoricals (:issue:`16409`) + + Conversion ^^^^^^^^^^ diff --git a/pandas/conftest.py b/pandas/conftest.py index 1149fae3fc0b0..8a3ffe22242ac 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -45,3 +45,13 @@ def spmatrix(request): tm._skip_if_no_scipy() from scipy import sparse return getattr(sparse, request.param + '_matrix') + + +@pytest.fixture +def ip(): + """An instance of IPython.InteractiveShell. + Will raise a skip if IPython is not installed. + """ + pytest.importorskip('IPython', minversion="6.0.0") + from IPython.core.interactiveshell import InteractiveShell + return InteractiveShell() diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 5b663f1d85ee7..f58eed74f760e 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -342,6 +342,13 @@ def __init__(self, values, categories=None, ordered=False, fastpath=False): self._categories = categories self._codes = coerce_indexer_dtype(codes, categories) + def __dir__(self): + # Avoid IPython warnings for deprecated properties + # https://github.com/pandas-dev/pandas/issues/16409 + rv = set(dir(type(self))) + rv.discard("labels") + return sorted(rv) + @property def _constructor(self): return Categorical diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 631b91c3aad11..2bb825541e23b 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -184,6 +184,12 @@ def __getattr__(self, attr): matches_pattern = any(attr.startswith(x) for x in self._deprecated_valid_patterns) if not matches_pattern and attr not in self._deprecated_valids: + # avoid the warning, if it's just going to be an exception + # anyway. + if not hasattr(self.obj, attr): + raise AttributeError("'{}' has no attribute '{}'".format( + type(self.obj).__name__, attr + )) self = self._deprecated(attr) return object.__getattribute__(self, attr) diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index f48eea23220b8..1ffe956b3a607 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -736,6 +736,17 @@ def test_unicode_print(self): assert _rep(c) == expected + def test_tab_complete_warning(self, ip): + # https://github.com/pandas-dev/pandas/issues/16409 + pytest.importorskip('IPython', minversion="6.0.0") + from IPython.core.completer import provisionalcompleter + + code = "import pandas as pd; c = pd.Categorical([])" + ip.run_code(code) + with tm.assert_produces_warning(None): + with provisionalcompleter('ignore'): + list(ip.Completer.completions('c.', 1)) + def test_periodindex(self): idx1 = PeriodIndex(['2014-01', '2014-01', '2014-02', '2014-02', '2014-03', '2014-03'], freq='M') diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 37e2fd0e9b188..170cab4947a5a 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -3,6 +3,7 @@ from warnings import catch_warnings from datetime import datetime, timedelta from functools import partial +from textwrap import dedent import pytz import pytest @@ -284,8 +285,7 @@ def test_attribute_access(self): tm.assert_series_equal(r.A.sum(), r['A'].sum()) # getting - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - pytest.raises(AttributeError, lambda: r.F) + pytest.raises(AttributeError, lambda: r.F) # setting def f(): @@ -2816,6 +2816,19 @@ def test_back_compat_v180(self): expected = df.groupby('A').resample('4s').mean().ffill() assert_frame_equal(result, expected) + def test_tab_complete_ipython6_warning(self, ip): + from IPython.core.completer import provisionalcompleter + code = dedent("""\ + import pandas.util.testing as tm + s = tm.makeTimeSeries() + rs = s.resample("D") + """) + ip.run_code(code) + + with tm.assert_produces_warning(None): + with provisionalcompleter('ignore'): + list(ip.Completer.completions('rs.', 1)) + def test_deferred_with_groupby(self): # GH 12486
Properties may run code with Jedi completion in IPython 6 Closes https://github.com/pandas-dev/pandas/issues/16409 I want to leave this open for a couple days to see if I can find other places that trigger this warning. I'm pretty sure I've seen other instances, but they may have been from other libraries.
https://api.github.com/repos/pandas-dev/pandas/pulls/16414
2017-05-22T14:12:28Z
2017-05-26T12:32:53Z
2017-05-26T12:32:53Z
2017-05-30T12:20:22Z
PERF: don't materialize arrays on checking in groupby
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index c0c3a42cc4464..13b5cd2b06032 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -368,6 +368,11 @@ def setup(self): self.dates = (np.datetime64('now') + self.offsets) self.df = DataFrame({'key1': np.random.randint(0, 500, size=self.n), 'key2': np.random.randint(0, 100, size=self.n), 'value1': np.random.randn(self.n), 'value2': np.random.randn(self.n), 'value3': np.random.randn(self.n), 'dates': self.dates, }) + N = 1000000 + self.draws = pd.Series(np.random.randn(N)) + labels = pd.Series(['foo', 'bar', 'baz', 'qux'] * (N // 4)) + self.cats = labels.astype('category') + def time_groupby_multi_size(self): self.df.groupby(['key1', 'key2']).size() @@ -377,6 +382,10 @@ def time_groupby_dt_size(self): def time_groupby_dt_timegrouper_size(self): self.df.groupby(TimeGrouper(key='dates', freq='M')).size() + def time_groupby_size(self): + self.draws.groupby(self.cats).size() + + #---------------------------------------------------------------------- # groupby with a variable value for ngroups diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 4ec9daff4c0fc..e0857019d2fd4 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -29,7 +29,7 @@ Performance Improvements - Performance regression fix when indexing with a list-like (:issue:`16285`) - Performance regression fix for MultiIndexes (:issue:`16319`, :issue:`16346`) - Improved performance of ``.clip()`` with scalar arguments (:issue:`15400`) - +- Improved performance of groupby with categorical groupers (:issue:`16413`) .. _whatsnew_0202.bug_fixes: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 9b29f1b04ff73..2af4f112ca941 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2388,7 +2388,6 @@ def get_loc(self, key, method=None, tolerance=None): if tolerance is not None: raise ValueError('tolerance argument only valid if using pad, ' 'backfill or nearest lookups') - key = _values_from_object(key) try: return self._engine.get_loc(key) except KeyError:
``` before after ratio [a6fcec6c] [6edcdc0d] - 15.41ms 9.48ms 0.62 groupby.groupby_size.time_groupby_size ``` this is more dramatic as the size increases as this should be pretty much a constant time operation (the actual size computation itself).
https://api.github.com/repos/pandas-dev/pandas/pulls/16413
2017-05-22T11:08:31Z
2017-05-22T13:10:28Z
2017-05-22T13:10:28Z
2017-05-30T12:23:25Z
DOC: add google analytics to the documentation
diff --git a/doc/source/themes/nature_with_gtoc/layout.html b/doc/source/themes/nature_with_gtoc/layout.html index ddf1e861f5f81..a2106605c5562 100644 --- a/doc/source/themes/nature_with_gtoc/layout.html +++ b/doc/source/themes/nature_with_gtoc/layout.html @@ -94,4 +94,15 @@ <h3 style="margin-top: 1.5em;">{{ _('Search') }}</h3> }); }); </script> +<script type="text/javascript"> + var _gaq = _gaq || []; + _gaq.push(['_setAccount', 'UA-27880019-2']); + _gaq.push(['_trackPageview']); + + (function() { + var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; + ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); + })(); +</script> {% endblock %} \ No newline at end of file
The main pandas website (pandas.pydata.org) has google analytics tracking, but I think it would be interesting to also have this on the docs, so adding it to the theme.
https://api.github.com/repos/pandas-dev/pandas/pulls/16412
2017-05-22T09:23:22Z
2017-05-22T13:02:09Z
2017-05-22T13:02:09Z
2017-05-30T12:20:21Z
Update tutorials.rst
diff --git a/doc/source/tutorials.rst b/doc/source/tutorials.rst index 2489b787560d0..9a97294d4e6d6 100644 --- a/doc/source/tutorials.rst +++ b/doc/source/tutorials.rst @@ -178,3 +178,4 @@ Various Tutorials - `Pandas and Python: Top 10, by Manish Amde <http://manishamde.github.io/blog/2013/03/07/pandas-and-python-top-10/>`_ - `Pandas Tutorial, by Mikhail Semeniuk <http://www.bearrelroll.com/2013/05/python-pandas-tutorial>`_ - `Pandas DataFrames Tutorial, by Karlijn Willems <http://www.datacamp.com/community/tutorials/pandas-tutorial-dataframe-python>`_ +- `A concise tutorial with real life examples <https://tutswiki.com/pandas-cookbook/chapter1>`_
- [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff``
https://api.github.com/repos/pandas-dev/pandas/pulls/16411
2017-05-22T07:42:17Z
2017-05-22T09:11:42Z
2017-05-22T09:11:42Z
2017-05-22T10:45:35Z
BUG: wide_to_long should check for unique id vars (#16382)
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index d5fd879d3f9bf..b53a9dd06b2a5 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -80,8 +80,10 @@ Reshaping ^^^^^^^^^ - Bug in ``DataFrame.stack`` with unsorted levels in MultiIndex columns (:issue:`16323`) +- Bug in ``pd.wide_to_long()`` where no error was raised when ``i`` was not a unique identifier (:issue:`16382`) - Bug in ``Series.isin(..)`` with a list of tuples (:issue:`16394`) + Numeric ^^^^^^^ - Bug in .interpolate(), where limit_direction was not respected when limit=None (default) was passed (:issue:16282) diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index b0ed6d4c4b84d..f944dfe22361a 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -1046,6 +1046,9 @@ def melt_stub(df, stub, i, j, value_vars, sep): else: i = list(i) + if df[i].duplicated().any(): + raise ValueError("the id variables need to uniquely identify each row") + value_vars = list(map(lambda stub: get_var_names(df, stub, sep, suffix), stubnames)) diff --git a/pandas/tests/reshape/test_reshape.py b/pandas/tests/reshape/test_reshape.py index 79626d89026a7..d47a95924bd10 100644 --- a/pandas/tests/reshape/test_reshape.py +++ b/pandas/tests/reshape/test_reshape.py @@ -976,3 +976,14 @@ def test_multiple_id_columns(self): exp_frame = exp_frame.set_index(['famid', 'birth', 'age'])[['ht']] long_frame = wide_to_long(df, 'ht', i=['famid', 'birth'], j='age') tm.assert_frame_equal(long_frame, exp_frame) + + def test_non_unique_idvars(self): + # GH16382 + # Raise an error message if non unique id vars (i) are passed + df = pd.DataFrame({ + 'A_A1': [1, 2, 3, 4, 5], + 'B_B1': [1, 2, 3, 4, 5], + 'x': [1, 1, 1, 1, 1] + }) + with pytest.raises(ValueError): + wide_to_long(df, ['A_A', 'B_B'], i='x', j='colname')
- [x] closes #16382 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` Input validation: raise a ValueError in case `i` does not uniquely identify each row.
https://api.github.com/repos/pandas-dev/pandas/pulls/16403
2017-05-20T19:04:40Z
2017-05-23T19:52:23Z
2017-05-23T19:52:23Z
2017-05-30T12:20:21Z
DOC: Added examples for union_categoricals
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index ddff78c9d511f..292d5f608d4cb 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -242,6 +242,74 @@ def union_categoricals(to_union, sort_categories=False, ignore_order=False): - sort_categories=True and Categoricals are ordered ValueError Empty list of categoricals passed + + Notes + ----- + + To learn more about categories, see `link + <http://pandas.pydata.org/pandas-docs/stable/categorical.html#unioning>`__ + + Examples + -------- + + >>> from pandas.api.types import union_categoricals + + If you want to combine categoricals that do not necessarily have + the same categories, `union_categoricals` will combine a list-like + of categoricals. The new categories will be the union of the + categories being combined. + + >>> a = pd.Categorical(["b", "c"]) + >>> b = pd.Categorical(["a", "b"]) + >>> union_categoricals([a, b]) + [b, c, a, b] + Categories (3, object): [b, c, a] + + By default, the resulting categories will be ordered as they appear + in the `categories` of the data. If you want the categories to be + lexsorted, use `sort_categories=True` argument. + + >>> union_categoricals([a, b], sort_categories=True) + [b, c, a, b] + Categories (3, object): [a, b, c] + + `union_categoricals` also works with the case of combining two + categoricals of the same categories and order information (e.g. what + you could also `append` for). + + >>> a = pd.Categorical(["a", "b"], ordered=True) + >>> b = pd.Categorical(["a", "b", "a"], ordered=True) + >>> union_categoricals([a, b]) + [a, b, a, b, a] + Categories (2, object): [a < b] + + Raises `TypeError` because the categories are ordered and not identical. + + >>> a = pd.Categorical(["a", "b"], ordered=True) + >>> b = pd.Categorical(["a", "b", "c"], ordered=True) + >>> union_categoricals([a, b]) + TypeError: to union ordered Categoricals, all categories must be the same + + New in version 0.20.0 + + Ordered categoricals with different categories or orderings can be + combined by using the `ignore_ordered=True` argument. + + >>> a = pd.Categorical(["a", "b", "c"], ordered=True) + >>> b = pd.Categorical(["c", "b", "a"], ordered=True) + >>> union_categoricals([a, b], ignore_order=True) + [a, b, c, c, b, a] + Categories (3, object): [a, b, c] + + `union_categoricals` also works with a `CategoricalIndex`, or `Series` + containing categorical data, but note that the resulting array will + always be a plain `Categorical` + + >>> a = pd.Series(["b", "c"], dtype='category') + >>> b = pd.Series(["a", "b"], dtype='category') + >>> union_categoricals([a, b]) + [b, c, a, b] + Categories (3, object): [b, c, a] """ from pandas import Index, Categorical, CategoricalIndex, Series
- [x] closes #16390 - [ ] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry Copied and posted over examples into the doc string; added link.
https://api.github.com/repos/pandas-dev/pandas/pulls/16397
2017-05-20T09:14:50Z
2017-05-22T08:24:01Z
2017-05-22T08:24:01Z
2017-09-07T20:49:57Z
DOC: Try with new token
diff --git a/.travis.yml b/.travis.yml index 0156f17aa32a5..8386dce478eb3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,10 +20,10 @@ env: # pandas-docs/pandas-docs-travis GH # # # create a github personal access token - # cd pandas-docs/pandas-docs-travis - # travis encrypt - # PANDAS_GH_TOKEN=personal_access_token - secure: "S49Tn5dzBRu6QaQcSV8MoCeX9rn7l8xuHFJbFsT9jPm1l0YPb94S8iDk0Isw71SqvHBgh+j2cms9jgYn2N3VCArh5MpA0oKwTKRZEX3iLQv248dCY2C6LdzAKLA+8m2naDGcfc0qMLeNieCGZICccs0EKIGDt8m7VQBMqeT0YU0=" + # cd pandas-dev/pandas + # travis encrypt PANDAS_GH_TOKEN=personal_access_token + # correct the repo to be pandas-dev/pandas, not your fork + secure: "EkWLZhbrp/mXJOx38CHjs7BnjXafsqHtwxPQrqWy457VDFWhIY1DMnIR/lOWG+a20Qv52sCsFtiZEmMfUjf0pLGXOqurdxbYBGJ7/ikFLk9yV2rDwiArUlVM9bWFnFxHvdz9zewBH55WurrY4ShZWyV+x2dWjjceWG5VpWeI6sA=" git: # for cloning
Let's see if this works @jreback. I think you have to be in the `pandas` git repo when you `travis-encrypt`, since that's the Travis build that's accessing the env var.
https://api.github.com/repos/pandas-dev/pandas/pulls/16389
2017-05-18T22:08:46Z
2017-05-18T22:39:22Z
2017-05-18T22:39:22Z
2017-05-27T16:40:24Z
TST: remove some Panel/Panel4D deprecation warnings from tests
diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 81d452318d0b4..f987045c27d5f 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1802,22 +1802,24 @@ def makePeriodFrame(nper=None): def makePanel(nper=None): - cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]] - data = dict((c, makeTimeDataFrame(nper)) for c in cols) - return Panel.fromDict(data) + with warnings.catch_warnings(record=True): + cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]] + data = dict((c, makeTimeDataFrame(nper)) for c in cols) + return Panel.fromDict(data) def makePeriodPanel(nper=None): - cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]] - data = dict((c, makePeriodFrame(nper)) for c in cols) - return Panel.fromDict(data) + with warnings.catch_warnings(record=True): + cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]] + data = dict((c, makePeriodFrame(nper)) for c in cols) + return Panel.fromDict(data) def makePanel4D(nper=None): with warnings.catch_warnings(record=True): d = dict(l1=makePanel(nper), l2=makePanel(nper), l3=makePanel(nper)) - return Panel4D(d) + return Panel4D(d) def makeCustomIndex(nentries, nlevels, prefix='#', names=False, ndupe_l=None,
https://api.github.com/repos/pandas-dev/pandas/pulls/16387
2017-05-18T20:48:49Z
2017-05-18T22:00:12Z
2017-05-18T22:00:12Z
2017-05-18T22:01:49Z
New Interval / IntervalIndex behavior spec
diff --git a/pandas/tests/indexes/interval/__init__.py b/pandas/tests/indexes/interval/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/interval/test_interval.py similarity index 98% rename from pandas/tests/indexes/test_interval.py rename to pandas/tests/indexes/interval/test_interval.py index 4169c93809059..8ce3c74fe6a31 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -627,6 +627,7 @@ def test_repr_max_seq_item_setting(self): def test_repr_roundtrip(self): super(TestIntervalIndex, self).test_repr_roundtrip() + # TODO: check this behavior is consistent with test_interval_new.py def test_get_item(self, closed): i = IntervalIndex.from_arrays((0, 1, np.nan), (1, 2, np.nan), closed=closed) @@ -647,6 +648,7 @@ def test_get_item(self, closed): closed=closed) tm.assert_index_equal(result, expected) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_get_loc_value(self): pytest.raises(KeyError, self.index.get_loc, 0) assert self.index.get_loc(0.5) == 0 @@ -669,6 +671,7 @@ def test_get_loc_value(self): idx = IntervalIndex.from_arrays([0, 2], [1, 3]) pytest.raises(KeyError, idx.get_loc, 1.5) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def slice_locs_cases(self, breaks): # TODO: same tests for more index types index = IntervalIndex.from_breaks([0, 1, 2], closed='right') @@ -697,12 +700,15 @@ def slice_locs_cases(self, breaks): assert index.slice_locs(1, 1) == (0, 1) assert index.slice_locs(1, 2) == (0, 2) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_slice_locs_int64(self): self.slice_locs_cases([0, 1, 2]) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_slice_locs_float64(self): self.slice_locs_cases([0.0, 1.0, 2.0]) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def slice_locs_decreasing_cases(self, tuples): index = IntervalIndex.from_tuples(tuples) assert index.slice_locs(1.5, 0.5) == (1, 3) @@ -716,17 +722,21 @@ def slice_locs_decreasing_cases(self, tuples): slice_locs = index.slice_locs(-1, -1) assert slice_locs[0] == slice_locs[1] + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_slice_locs_decreasing_int64(self): self.slice_locs_cases([(2, 4), (1, 3), (0, 2)]) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_slice_locs_decreasing_float64(self): self.slice_locs_cases([(2., 4.), (1., 3.), (0., 2.)]) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_slice_locs_fails(self): index = IntervalIndex.from_tuples([(1, 2), (0, 1), (2, 3)]) with pytest.raises(KeyError): index.slice_locs(1, 2) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_get_loc_interval(self): assert self.index.get_loc(Interval(0, 1)) == 0 assert self.index.get_loc(Interval(0, 0.5)) == 0 @@ -735,6 +745,7 @@ def test_get_loc_interval(self): pytest.raises(KeyError, self.index.get_loc, Interval(-1, 0, 'left')) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_get_indexer(self): actual = self.index.get_indexer([-1, 0, 0.5, 1, 1.5, 2, 3]) expected = np.array([-1, -1, 0, 0, 1, 1, -1], dtype='intp') @@ -757,6 +768,7 @@ def test_get_indexer(self): expected = np.array([-1, 1], dtype='intp') tm.assert_numpy_array_equal(actual, expected) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_get_indexer_subintervals(self): # TODO: is this right? @@ -780,6 +792,7 @@ def test_get_indexer_subintervals(self): expected = np.array([0, 0, 0], dtype='intp') tm.assert_numpy_array_equal(actual, expected) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_contains(self): # Only endpoints are valid. i = IntervalIndex.from_arrays([0, 1], [1, 2]) @@ -796,6 +809,7 @@ def test_contains(self): assert Interval(3, 5) not in i assert Interval(-1, 0, closed='left') not in i + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def testcontains(self): # can select values that are IN the range of a value i = IntervalIndex.from_arrays([0, 1], [1, 2]) @@ -827,6 +841,7 @@ def test_dropna(self, closed): result = ii.dropna() tm.assert_index_equal(result, expected) + # TODO: check this behavior is consistent with test_interval_new.py def test_non_contiguous(self, closed): index = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed) target = [0.5, 1.5, 2.5] diff --git a/pandas/tests/indexes/interval/test_interval_new.py b/pandas/tests/indexes/interval/test_interval_new.py new file mode 100644 index 0000000000000..c8b30e19daa02 --- /dev/null +++ b/pandas/tests/indexes/interval/test_interval_new.py @@ -0,0 +1,316 @@ +from __future__ import division + +import pytest +import numpy as np + +from pandas import Interval, IntervalIndex, Int64Index +from pandas.tests.indexes.common import Base +import pandas.util.testing as tm + + +pytestmark = pytest.mark.skip(reason="new indexing tests for issue 16316") + + +class TestIntervalIndex(Base): + + def _compare_tuple_of_numpy_array(self, result, expected): + lidx, ridx = result + lidx_expected, ridx_expected = expected + + tm.assert_numpy_array_equal(lidx, lidx_expected) + tm.assert_numpy_array_equal(ridx, ridx_expected) + + @pytest.mark.parametrize("idx_side", ['right', 'left', 'both', 'neither']) + @pytest.mark.parametrize("side", ['right', 'left', 'both', 'neither']) + def test_get_loc_interval(self, idx_side, side): + + idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=idx_side) + + for bound in [[0, 1], [1, 2], [2, 3], [3, 4], + [0, 2], [2.5, 3], [-1, 4]]: + # if get_loc is supplied an interval, it should only search + # for exact matches, not overlaps or covers, else KeyError. + if idx_side == side: + if bound == [0, 1]: + assert idx.get_loc(Interval(0, 1, closed=side)) == 0 + elif bound == [2, 3]: + assert idx.get_loc(Interval(2, 3, closed=side)) == 1 + else: + with pytest.raises(KeyError): + idx.get_loc(Interval(*bound, closed=side)) + else: + with pytest.raises(KeyError): + idx.get_loc(Interval(*bound, closed=side)) + + @pytest.mark.parametrize("idx_side", ['right', 'left', 'both', 'neither']) + @pytest.mark.parametrize("scalar", [-0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5]) + def test_get_loc_scalar(self, idx_side, scalar): + + # correct = {side: {query: answer}}. + # If query is not in the dict, that query should raise a KeyError + correct = {'right': {0.5: 0, 1: 0, 2.5: 1, 3: 1}, + 'left': {0: 0, 0.5: 0, 2: 1, 2.5: 1}, + 'both': {0: 0, 0.5: 0, 1: 0, 2: 1, 2.5: 1, 3: 1}, + 'neither': {0.5: 0, 2.5: 1}} + + idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=idx_side) + + # if get_loc is supplied a scalar, it should return the index of + # the interval which contains the scalar, or KeyError. + if scalar in correct[idx_side].keys(): + assert idx.get_loc(scalar) == correct[idx_side][scalar] + else: + pytest.raises(KeyError, idx.get_loc, scalar) + + def test_slice_locs_with_interval(self): + + # increasing monotonically + index = IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)]) + + assert index.slice_locs( + start=Interval(0, 2), end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(start=Interval(0, 2)) == (0, 3) + assert index.slice_locs(end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(end=Interval(0, 2)) == (0, 1) + assert index.slice_locs( + start=Interval(2, 4), end=Interval(0, 2)) == (2, 1) + + # decreasing monotonically + index = IntervalIndex.from_tuples([(2, 4), (1, 3), (0, 2)]) + + assert index.slice_locs( + start=Interval(0, 2), end=Interval(2, 4)) == (2, 1) + assert index.slice_locs(start=Interval(0, 2)) == (2, 3) + assert index.slice_locs(end=Interval(2, 4)) == (0, 1) + assert index.slice_locs(end=Interval(0, 2)) == (0, 3) + assert index.slice_locs( + start=Interval(2, 4), end=Interval(0, 2)) == (0, 3) + + # sorted duplicates + index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4)]) + + assert index.slice_locs( + start=Interval(0, 2), end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(start=Interval(0, 2)) == (0, 3) + assert index.slice_locs(end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(end=Interval(0, 2)) == (0, 2) + assert index.slice_locs( + start=Interval(2, 4), end=Interval(0, 2)) == (2, 2) + + # unsorted duplicates + index = IntervalIndex.from_tuples([(0, 2), (2, 4), (0, 2)]) + + pytest.raises(KeyError, index.slice_locs( + start=Interval(0, 2), end=Interval(2, 4))) + pytest.raises(KeyError, index.slice_locs(start=Interval(0, 2))) + assert index.slice_locs(end=Interval(2, 4)) == (0, 2) + pytest.raises(KeyError, index.slice_locs(end=Interval(0, 2))) + pytest.raises(KeyError, index.slice_locs( + start=Interval(2, 4), end=Interval(0, 2))) + + # another unsorted duplicates + index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4), (1, 3)]) + + assert index.slice_locs( + start=Interval(0, 2), end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(start=Interval(0, 2)) == (0, 4) + assert index.slice_locs(end=Interval(2, 4)) == (0, 3) + assert index.slice_locs(end=Interval(0, 2)) == (0, 2) + assert index.slice_locs( + start=Interval(2, 4), end=Interval(0, 2)) == (2, 2) + + def test_slice_locs_with_ints_and_floats_succeeds(self): + + # increasing non-overlapping + index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)]) + + assert index.slice_locs(0, 1) == (0, 1) + assert index.slice_locs(0, 2) == (0, 2) + assert index.slice_locs(0, 3) == (0, 2) + assert index.slice_locs(3, 1) == (2, 1) + assert index.slice_locs(3, 4) == (2, 3) + assert index.slice_locs(0, 4) == (0, 3) + + # decreasing non-overlapping + index = IntervalIndex.from_tuples([(3, 4), (1, 2), (0, 1)]) + assert index.slice_locs(0, 1) == (3, 2) + assert index.slice_locs(0, 2) == (3, 1) + assert index.slice_locs(0, 3) == (3, 1) + assert index.slice_locs(3, 1) == (1, 2) + assert index.slice_locs(3, 4) == (1, 0) + assert index.slice_locs(0, 4) == (3, 0) + + @pytest.mark.parametrize("query", [[0, 1], [0, 2], [0, 3], + [3, 1], [3, 4], [0, 4]]) + def test_slice_locs_with_ints_and_floats_fails(self, query): + + # increasing overlapping + index = IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)]) + pytest.raises(KeyError, index.slice_locs, query) + + # decreasing overlapping + index = IntervalIndex.from_tuples([(2, 4), (1, 3), (0, 2)]) + pytest.raises(KeyError, index.slice_locs, query) + + # sorted duplicates + index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4)]) + pytest.raises(KeyError, index.slice_locs, query) + + # unsorted duplicates + index = IntervalIndex.from_tuples([(0, 2), (2, 4), (0, 2)]) + pytest.raises(KeyError, index.slice_locs, query) + + # another unsorted duplicates + index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4), (1, 3)]) + pytest.raises(KeyError, index.slice_locs, query) + + @pytest.mark.parametrize("query", [ + Interval(1, 3, closed='right'), + Interval(1, 3, closed='left'), + Interval(1, 3, closed='both'), + Interval(1, 3, closed='neither'), + Interval(1, 4, closed='right'), + Interval(0, 4, closed='right'), + Interval(1, 2, closed='right')]) + @pytest.mark.parametrize("expected_result", [1, -1, -1, -1, -1, -1, -1]) + def test_get_indexer_with_interval_single_queries( + self, query, expected_result): + + index = IntervalIndex.from_tuples( + [(0, 2.5), (1, 3), (2, 4)], closed='right') + + result = index.get_indexer([query]) + expect = np.array([expected_result], dtype='intp') + tm.assert_numpy_array_equal(result, expect) + + @pytest.mark.parametrize("query", [ + [Interval(2, 4, closed='right'), Interval(1, 3, closed='right')], + [Interval(1, 3, closed='right'), Interval(0, 2, closed='right')], + [Interval(1, 3, closed='right'), Interval(1, 3, closed='left')]]) + @pytest.mark.parametrize("expected_result", [[2, 1], [1, -1], [1, -1]]) + def test_get_indexer_with_interval_multiple_queries( + self, query, expected_result): + + index = IntervalIndex.from_tuples( + [(0, 2.5), (1, 3), (2, 4)], closed='right') + + result = index.get_indexer(query) + expect = np.array(expected_result, dtype='intp') + tm.assert_numpy_array_equal(result, expect) + + @pytest.mark.parametrize( + "query", + [-0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]) + @pytest.mark.parametrize( + "expected_result", + [-1, -1, 0, 0, 1, 1, -1, -1, 2, 2, -1]) + def test_get_indexer_with_ints_and_floats_single_queries( + self, query, expected_result): + + index = IntervalIndex.from_tuples( + [(0, 1), (1, 2), (3, 4)], closed='right') + + result = index.get_indexer([query]) + expect = np.array([expected_result], dtype='intp') + tm.assert_numpy_array_equal(result, expect) + + @pytest.mark.parametrize( + "query", + [[1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 2]]) + @pytest.mark.parametrize( + "expected_result", + [[0, 1], [0, 1, -1], [0, 1, -1, 2], [0, 1, -1, 2, 1]]) + def test_get_indexer_with_ints_and_floats_multiple_queries( + self, query, expected_result): + + index = IntervalIndex.from_tuples( + [(0, 1), (1, 2), (3, 4)], closed='right') + + result = index.get_indexer(query) + expect = np.array(expected_result, dtype='intp') + tm.assert_numpy_array_equal(result, expect) + + index = IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)]) + # TODO: @shoyer believes this should raise, master branch doesn't + + @pytest.mark.parametrize( + "query", + [-0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]) + @pytest.mark.parametrize("expected_result", [ + (Int64Index([], dtype='int64'), np.array([0])), + (Int64Index([0], dtype='int64'), np.array([])), + (Int64Index([0], dtype='int64'), np.array([])), + (Int64Index([0, 1], dtype='int64'), np.array([])), + (Int64Index([0, 1], dtype='int64'), np.array([])), + (Int64Index([0, 1, 2], dtype='int64'), np.array([])), + (Int64Index([1, 2], dtype='int64'), np.array([])), + (Int64Index([2], dtype='int64'), np.array([])), + (Int64Index([2], dtype='int64'), np.array([])), + (Int64Index([], dtype='int64'), np.array([0])), + (Int64Index([], dtype='int64'), np.array([0]))]) + def test_get_indexer_non_unique_with_ints_and_floats_single_queries( + self, query, expected_result): + + index = IntervalIndex.from_tuples( + [(0, 2.5), (1, 3), (2, 4)], closed='left') + + result = index.get_indexer_non_unique([query]) + tm.assert_numpy_array_equal(result, expected_result) + + @pytest.mark.parametrize( + "query", + [[1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 2]]) + @pytest.mark.parametrize("expected_result", [ + (Int64Index([0, 1, 0, 1, 2], dtype='int64'), np.array([])), + (Int64Index([0, 1, 0, 1, 2, 2], dtype='int64'), np.array([])), + (Int64Index([0, 1, 0, 1, 2, 2, -1], dtype='int64'), np.array([3])), + (Int64Index([0, 1, 0, 1, 2, 2, -1, 0, 1, 2], dtype='int64'), + np.array([3]))]) + def test_get_indexer_non_unique_with_ints_and_floats_multiple_queries( + self, query, expected_result): + + index = IntervalIndex.from_tuples( + [(0, 2.5), (1, 3), (2, 4)], closed='left') + + result = index.get_indexer_non_unique(query) + tm.assert_numpy_array_equal(result, expected_result) + + # TODO we may also want to test get_indexer for the case when + # the intervals are duplicated, decreasing, non-monotonic, etc.. + + def test_contains(self): + + index = IntervalIndex.from_arrays([0, 1], [1, 2], closed='right') + + # __contains__ requires perfect matches to intervals. + assert 0 not in index + assert 1 not in index + assert 2 not in index + + assert Interval(0, 1, closed='right') in index + assert Interval(0, 2, closed='right') not in index + assert Interval(0, 0.5, closed='right') not in index + assert Interval(3, 5, closed='right') not in index + assert Interval(-1, 0, closed='left') not in index + assert Interval(0, 1, closed='left') not in index + assert Interval(0, 1, closed='both') not in index + + def test_contains_method(self): + + index = IntervalIndex.from_arrays([0, 1], [1, 2], closed='right') + + assert not index.contains(0) + assert index.contains(0.1) + assert index.contains(0.5) + assert index.contains(1) + + assert index.contains(Interval(0, 1), closed='right') + assert not index.contains(Interval(0, 1), closed='left') + assert not index.contains(Interval(0, 1), closed='both') + assert not index.contains(Interval(0, 2), closed='right') + + assert not index.contains(Interval(0, 3), closed='right') + assert not index.contains(Interval(1, 3), closed='right') + + assert not index.contains(20) + assert not index.contains(-20) diff --git a/pandas/tests/indexing/interval/__init__.py b/pandas/tests/indexing/interval/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/pandas/tests/indexing/test_interval.py b/pandas/tests/indexing/interval/test_interval.py similarity index 91% rename from pandas/tests/indexing/test_interval.py rename to pandas/tests/indexing/interval/test_interval.py index e29dc627a5d94..233fbd2c8d7be 100644 --- a/pandas/tests/indexing/test_interval.py +++ b/pandas/tests/indexing/interval/test_interval.py @@ -12,6 +12,7 @@ class TestIntervalIndex(object): def setup_method(self, method): self.s = Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_loc_with_scalar(self): s = self.s @@ -30,6 +31,7 @@ def test_loc_with_scalar(self): expected = s.iloc[2:5] tm.assert_series_equal(expected, s.loc[s >= 2]) + # TODO: check this behavior is consistent with test_interval_new.py def test_getitem_with_scalar(self): s = self.s @@ -48,6 +50,7 @@ def test_getitem_with_scalar(self): expected = s.iloc[2:5] tm.assert_series_equal(expected, s[s >= 2]) + # TODO: check this behavior is consistent with test_interval_new.py @pytest.mark.parametrize('direction, closed', product(('increasing', 'decreasing'), ('left', 'right', 'neither', 'both'))) @@ -83,6 +86,7 @@ def test_nonoverlapping_monotonic(self, direction, closed): assert s[key] == expected assert s.loc[key] == expected + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_with_interval(self): s = self.s @@ -119,6 +123,7 @@ def test_with_interval(self): with pytest.raises(KeyError): s[Interval(5, 6)] + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_with_slices(self): s = self.s @@ -138,6 +143,7 @@ def test_with_slices(self): with pytest.raises(ValueError): s[0:4:2] + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_with_overlaps(self): s = self.s @@ -175,6 +181,7 @@ def test_with_overlaps(self): with pytest.raises(KeyError): s.loc[[Interval(3, 5)]] + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_non_unique(self): idx = IntervalIndex.from_tuples([(1, 3), (3, 7)]) @@ -188,6 +195,7 @@ def test_non_unique(self): expected = s.iloc[0:1] tm.assert_series_equal(expected, result) + # To be removed, replaced by test_interval_new.py (see #16316, #16386) def test_non_unique_moar(self): idx = IntervalIndex.from_tuples([(1, 3), (1, 3), (3, 7)]) @@ -208,6 +216,7 @@ def test_non_unique_moar(self): with pytest.raises(ValueError): s[[Interval(1, 3)]] + # TODO: check this behavior is consistent with test_interval_new.py def test_non_matching(self): s = self.s diff --git a/pandas/tests/indexing/interval/test_interval_new.py b/pandas/tests/indexing/interval/test_interval_new.py new file mode 100644 index 0000000000000..16326845de1d5 --- /dev/null +++ b/pandas/tests/indexing/interval/test_interval_new.py @@ -0,0 +1,248 @@ +import pytest +import numpy as np +import pandas as pd + +from pandas import Series, IntervalIndex, Interval +import pandas.util.testing as tm + + +pytestmark = pytest.mark.skip(reason="new indexing tests for issue 16316") + + +class TestIntervalIndex(object): + + def setup_method(self, method): + self.s = Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) + + def test_loc_with_interval(self): + + # loc with single label / list of labels: + # - Intervals: only exact matches + # - scalars: those that contain it + + s = self.s + + expected = 0 + result = s.loc[Interval(0, 1)] + assert result == expected + result = s[Interval(0, 1)] + assert result == expected + + expected = s.iloc[3:5] + result = s.loc[[Interval(3, 4), Interval(4, 5)]] + tm.assert_series_equal(expected, result) + result = s[[Interval(3, 4), Interval(4, 5)]] + tm.assert_series_equal(expected, result) + + # missing or not exact + with pytest.raises(KeyError): + s.loc[Interval(3, 5, closed='left')] + + with pytest.raises(KeyError): + s[Interval(3, 5, closed='left')] + + with pytest.raises(KeyError): + s[Interval(3, 5)] + + with pytest.raises(KeyError): + s.loc[Interval(3, 5)] + + with pytest.raises(KeyError): + s[Interval(3, 5)] + + with pytest.raises(KeyError): + s.loc[Interval(-2, 0)] + + with pytest.raises(KeyError): + s[Interval(-2, 0)] + + with pytest.raises(KeyError): + s.loc[Interval(5, 6)] + + with pytest.raises(KeyError): + s[Interval(5, 6)] + + def test_loc_with_scalar(self): + + # loc with single label / list of labels: + # - Intervals: only exact matches + # - scalars: those that contain it + + s = self.s + + assert s.loc[1] == 0 + assert s.loc[1.5] == 1 + assert s.loc[2] == 1 + + # TODO with __getitem__ same rules as loc, or positional ? + # assert s[1] == 0 + # assert s[1.5] == 1 + # assert s[2] == 1 + + expected = s.iloc[1:4] + tm.assert_series_equal(expected, s.loc[[1.5, 2.5, 3.5]]) + tm.assert_series_equal(expected, s.loc[[2, 3, 4]]) + tm.assert_series_equal(expected, s.loc[[1.5, 3, 4]]) + + expected = s.iloc[[1, 1, 2, 1]] + tm.assert_series_equal(expected, s.loc[[1.5, 2, 2.5, 1.5]]) + + expected = s.iloc[2:5] + tm.assert_series_equal(expected, s.loc[s >= 2]) + + def test_loc_with_slices(self): + + # loc with slices: + # - Interval objects: only works with exact matches + # - scalars: only works for non-overlapping, monotonic intervals, + # and start/stop select location based on the interval that + # contains them: + # (slice_loc(start, stop) == (idx.get_loc(start), idx.get_loc(stop)) + + s = self.s + + # slice of interval + + expected = s.iloc[:3] + result = s.loc[Interval(0, 1):Interval(2, 3)] + tm.assert_series_equal(expected, result) + result = s[Interval(0, 1):Interval(2, 3)] + tm.assert_series_equal(expected, result) + + expected = s.iloc[4:] + result = s.loc[Interval(3, 4):] + tm.assert_series_equal(expected, result) + result = s[Interval(3, 4):] + tm.assert_series_equal(expected, result) + + with pytest.raises(KeyError): + s.loc[Interval(3, 6):] + + with pytest.raises(KeyError): + s[Interval(3, 6):] + + with pytest.raises(KeyError): + s.loc[Interval(3, 4, closed='left'):] + + with pytest.raises(KeyError): + s[Interval(3, 4, closed='left'):] + + # TODO with non-existing intervals ? + # s.loc[Interval(-1, 0):Interval(2, 3)] + + # slice of scalar + + expected = s.iloc[:3] + tm.assert_series_equal(expected, s.loc[:3]) + tm.assert_series_equal(expected, s.loc[:2.5]) + tm.assert_series_equal(expected, s.loc[0.1:2.5]) + + # TODO should this work? (-1 is not contained in any of the Intervals) + # tm.assert_series_equal(expected, s.loc[-1:3]) + + # TODO with __getitem__ same rules as loc, or positional ? + # tm.assert_series_equal(expected, s[:3]) + # tm.assert_series_equal(expected, s[:2.5]) + # tm.assert_series_equal(expected, s[0.1:2.5]) + + # slice of scalar with step != 1 + with pytest.raises(NotImplementedError): + s[0:4:2] + + def test_loc_with_overlap(self): + + idx = IntervalIndex.from_tuples([(1, 5), (3, 7)]) + s = Series(range(len(idx)), index=idx) + + # scalar + expected = s + result = s.loc[4] + tm.assert_series_equal(expected, result) + + result = s[4] + tm.assert_series_equal(expected, result) + + result = s.loc[[4]] + tm.assert_series_equal(expected, result) + + result = s[[4]] + tm.assert_series_equal(expected, result) + + # interval + expected = 0 + result = s.loc[pd.interval(1, 5)] + tm.assert_series_equal(expected, result) + + result = s[pd.interval(1, 5)] + tm.assert_series_equal(expected, result) + + expected = s + result = s.loc[[pd.interval(1, 5), pd.Interval(3, 7)]] + tm.assert_series_equal(expected, result) + + result = s[[pd.interval(1, 5), pd.Interval(3, 7)]] + tm.assert_series_equal(expected, result) + + with pytest.raises(KeyError): + s.loc[Interval(3, 5)] + + with pytest.raises(KeyError): + s.loc[[Interval(3, 5)]] + + with pytest.raises(KeyError): + s[Interval(3, 5)] + + with pytest.raises(KeyError): + s[[Interval(3, 5)]] + + # slices with interval (only exact matches) + expected = s + result = s.loc[pd.interval(1, 5):pd.Interval(3, 7)] + tm.assert_series_equal(expected, result) + + result = s[pd.interval(1, 5):pd.Interval(3, 7)] + tm.assert_series_equal(expected, result) + + with pytest.raises(KeyError): + s.loc[pd.interval(1, 6):pd.Interval(3, 8)] + + with pytest.raises(KeyError): + s[pd.interval(1, 6):pd.Interval(3, 8)] + + # slices with scalar raise for overlapping intervals + # TODO KeyError is the appropriate error? + with pytest.raises(KeyError): + s.loc[1:4] + + def test_non_unique(self): + + idx = IntervalIndex.from_tuples([(1, 3), (3, 7)]) + s = pd.Series(range(len(idx)), index=idx) + + result = s.loc[Interval(1, 3)] + assert result == 0 + + result = s.loc[[Interval(1, 3)]] + expected = s.iloc[0:1] + tm.assert_series_equal(expected, result) + + def test_non_unique_moar(self): + + idx = IntervalIndex.from_tuples([(1, 3), (1, 3), (3, 7)]) + s = Series(range(len(idx)), index=idx) + + expected = s.iloc[[0, 1]] + result = s.loc[Interval(1, 3)] + tm.assert_series_equal(expected, result) + + expected = s + result = s.loc[Interval(1, 3):] + tm.assert_series_equal(expected, result) + + expected = s + result = s[Interval(1, 3):] + tm.assert_series_equal(expected, result) + + expected = s.iloc[[0, 1]] + result = s[[Interval(1, 3)]] + tm.assert_series_equal(expected, result)
- [x] part of #16316 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/16386
2017-05-18T19:48:02Z
2017-12-28T14:29:07Z
2017-12-28T14:29:07Z
2020-02-04T17:15:32Z
TST: remove pandas-datareader xfail as 0.4.0 works
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index 12976272cb8b1..27e3c29a70a9f 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -84,12 +84,10 @@ def test_pandas_gbq(df): pandas_gbq = import_module('pandas_gbq') # noqa -@pytest.mark.xfail(reason=("pandas_datareader<=0.3.0 " - "broken w.r.t. pandas >= 0.20.0")) def test_pandas_datareader(): pandas_datareader = import_module('pandas_datareader') # noqa - pandas_datareader.get_data_yahoo('AAPL') + pandas_datareader.get_data_google('AAPL') def test_geopandas():
https://api.github.com/repos/pandas-dev/pandas/pulls/16374
2017-05-17T00:52:50Z
2017-05-17T02:14:45Z
2017-05-17T02:14:45Z
2017-05-30T12:21:46Z
TST: followup to #16364, catch errstate warnings
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 3e1c5c3f354fd..c33b30c78d812 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4113,11 +4113,15 @@ def _clip_with_scalar(self, lower, upper): result = self.values mask = isnull(result) - if upper is not None: - result = np.where(result >= upper, upper, result) - if lower is not None: - result = np.where(result <= lower, lower, result) - result[mask] = np.nan + + with np.errstate(all='ignore'): + if upper is not None: + result = np.where(result >= upper, upper, result) + if lower is not None: + result = np.where(result <= lower, lower, result) + if np.any(mask): + result[mask] = np.nan + return self._constructor( result, **self._construct_axes_dict()).__finalize__(self) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 1b6471fcef565..fa9823bf000a2 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1824,6 +1824,17 @@ def test_dataframe_clip(self): assert (clipped_df.values[ub_mask] == ub).all() assert (clipped_df.values[mask] == df.values[mask]).all() + @pytest.mark.xfail(reason=("clip on mixed integer or floats " + "with integer clippers coerces to float")) + def test_clip_mixed_numeric(self): + + df = DataFrame({'A': [1, 2, 3], + 'B': [1., np.nan, 3.]}) + result = df.clip(1, 2) + expected = DataFrame({'A': [1, 2, 2], + 'B': [1., np.nan, 2.]}) + tm.assert_frame_equal(result, expected, check_like=True) + def test_clip_against_series(self): # GH #6966
fixing the int/float issue is quite hard actually.
https://api.github.com/repos/pandas-dev/pandas/pulls/16373
2017-05-16T22:58:17Z
2017-05-17T00:53:28Z
2017-05-17T00:53:28Z
2017-05-30T12:23:31Z
TST: Add test for clip-na
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index be89b27912d1c..1b6471fcef565 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1863,6 +1863,23 @@ def test_clip_against_frame(self): tm.assert_frame_equal(clipped_df[ub_mask], ub[ub_mask]) tm.assert_frame_equal(clipped_df[mask], df[mask]) + def test_clip_na(self): + msg = "Cannot use an NA" + with tm.assert_raises_regex(ValueError, msg): + self.frame.clip(lower=np.nan) + + with tm.assert_raises_regex(ValueError, msg): + self.frame.clip(lower=[np.nan]) + + with tm.assert_raises_regex(ValueError, msg): + self.frame.clip(upper=np.nan) + + with tm.assert_raises_regex(ValueError, msg): + self.frame.clip(upper=[np.nan]) + + with tm.assert_raises_regex(ValueError, msg): + self.frame.clip(lower=np.nan, upper=np.nan) + # Matrix-like def test_dot(self):
Additional test cases for https://github.com/pandas-dev/pandas/pull/16364 when upper and / or lower is nan. cc @jreback [this line](https://github.com/pandas-dev/pandas/pull/16364/files#diff-03b380f521c43cf003207b0711bac67fR4112) was missing tests I think.
https://api.github.com/repos/pandas-dev/pandas/pulls/16369
2017-05-16T15:31:33Z
2017-05-16T22:37:14Z
2017-05-16T22:37:14Z
2017-05-30T12:20:21Z
MAINT: Add .iml to .gitignore
diff --git a/.gitignore b/.gitignore index 495429fcde429..ff0a6aef47163 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ *$ *.bak *flymake* +*.iml *.kdev4 *.log *.swp
Title is self-explanatory. No need to run tests given that this is just a change to the `.gitignore`.
https://api.github.com/repos/pandas-dev/pandas/pulls/16368
2017-05-16T15:22:20Z
2017-05-16T22:21:03Z
2017-05-16T22:21:03Z
2017-05-16T22:22:07Z
Fixes truncated error message "C extension: umpy.core.multiarray failed to import"
diff --git a/pandas/__init__.py b/pandas/__init__.py index 48ac9d173559d..8d9b75ccd6c2c 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -28,7 +28,7 @@ tslib as _tslib) except ImportError as e: # pragma: no cover # hack but overkill to use re - module = str(e).lstrip('cannot import name ') + module = str(e).replace('cannot import name ', '') raise ImportError("C extension: {0} not built. If you want to import " "pandas from the source directory, you may need to run " "'python setup.py build_ext --inplace --force' to build "
This occurred because lstrip is the wrong tool here: ``` >>> e = 'cannot import name numpy.core.multiarray' >>> str(e).lstrip('cannot import name ') 'umpy.core.multiarray' ``` Better: ``` >>> str(e).replace('cannot import name ', '') 'numpy.core.multiarray' ``` -- - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16366
2017-05-16T09:43:30Z
2017-05-18T20:43:25Z
2017-05-18T20:43:25Z
2017-06-07T10:56:22Z
PERF: improved clip performance
diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index c66654ee1e006..3c0e2869357ae 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -111,6 +111,7 @@ def setup(self): def time_series_dropna_int64(self): self.s.dropna() + class series_dropna_datetime(object): goal_time = 0.2 @@ -120,3 +121,13 @@ def setup(self): def time_series_dropna_datetime(self): self.s.dropna() + + +class series_clip(object): + goal_time = 0.2 + + def setup(self): + self.s = pd.Series(np.random.randn(50)) + + def time_series_dropna_datetime(self): + self.s.clip(0, 1) diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 03579dab0d6a3..10a6b4354290d 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -19,7 +19,7 @@ Highlights include: Enhancements ~~~~~~~~~~~~ -- Unblocked access to additional compression types supported in pytables: 'blosc:blosclz, 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy', 'blosc:zlib', 'blosc:zstd' (:issue:`14478`) +- Unblocked access to additional compression types supported in pytables: 'blosc:blosclz, 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy', 'blosc:zlib', 'blosc:zstd' (:issue:`14478`) .. _whatsnew_0202.performance: @@ -28,6 +28,7 @@ Performance Improvements - Performance regression fix when indexing with a list-like (:issue:`16285`) - Performance regression fix for small MultiIndexes (:issuse:`16319`) +- Improved performance of ``.clip()`` with scalar arguments (:issue:`15400`) .. _whatsnew_0202.bug_fixes: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 777cfcae7a326..3e1c5c3f354fd 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -14,6 +14,7 @@ _ensure_int64, needs_i8_conversion, is_scalar, + is_number, is_integer, is_bool, is_bool_dtype, is_numeric_dtype, @@ -4104,6 +4105,22 @@ def isnull(self): def notnull(self): return notnull(self).__finalize__(self) + def _clip_with_scalar(self, lower, upper): + + if ((lower is not None and np.any(isnull(lower))) or + (upper is not None and np.any(isnull(upper)))): + raise ValueError("Cannot use an NA value as a clip threshold") + + result = self.values + mask = isnull(result) + if upper is not None: + result = np.where(result >= upper, upper, result) + if lower is not None: + result = np.where(result <= lower, lower, result) + result[mask] = np.nan + return self._constructor( + result, **self._construct_axes_dict()).__finalize__(self) + def clip(self, lower=None, upper=None, axis=None, *args, **kwargs): """ Trim values at input threshold(s). @@ -4122,12 +4139,13 @@ def clip(self, lower=None, upper=None, axis=None, *args, **kwargs): Examples -------- >>> df - 0 1 + 0 1 0 0.335232 -1.256177 1 -1.367855 0.746646 2 0.027753 -1.176076 3 0.230930 -0.679613 4 1.261967 0.570967 + >>> df.clip(-1.0, 0.5) 0 1 0 0.335232 -1.000000 @@ -4135,6 +4153,7 @@ def clip(self, lower=None, upper=None, axis=None, *args, **kwargs): 2 0.027753 -1.000000 3 0.230930 -0.679613 4 0.500000 0.500000 + >>> t 0 -0.3 1 -0.2 @@ -4142,6 +4161,7 @@ def clip(self, lower=None, upper=None, axis=None, *args, **kwargs): 3 0.0 4 0.1 dtype: float64 + >>> df.clip(t, t + 1, axis=0) 0 1 0 0.335232 -0.300000 @@ -4160,6 +4180,11 @@ def clip(self, lower=None, upper=None, axis=None, *args, **kwargs): if is_scalar(lower) and is_scalar(upper): lower, upper = min(lower, upper), max(lower, upper) + # fast-path for scalars + if ((lower is None or (is_scalar(lower) and is_number(lower))) and + (upper is None or (is_scalar(upper) and is_number(upper)))): + return self._clip_with_scalar(lower, upper) + result = self if lower is not None: result = result.clip_lower(lower, axis) @@ -4189,6 +4214,9 @@ def clip_upper(self, threshold, axis=None): if np.any(isnull(threshold)): raise ValueError("Cannot use an NA value as a clip threshold") + if is_scalar(threshold) and is_number(threshold): + return self._clip_with_scalar(None, threshold) + subset = self.le(threshold, axis=axis) | isnull(self) return self.where(subset, threshold, axis=axis) @@ -4213,6 +4241,9 @@ def clip_lower(self, threshold, axis=None): if np.any(isnull(threshold)): raise ValueError("Cannot use an NA value as a clip threshold") + if is_scalar(threshold) and is_number(threshold): + return self._clip_with_scalar(threshold, None) + subset = self.ge(threshold, axis=axis) | isnull(self) return self.where(subset, threshold, axis=axis) diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index ec6a118ec3639..18c6c9a6dd021 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -1011,6 +1011,7 @@ def test_clip_against_series(self): lower = Series([1.0, 2.0, 3.0]) upper = Series([1.5, 2.5, 3.5]) + assert_series_equal(s.clip(lower, upper), Series([1.0, 2.0, 3.5])) assert_series_equal(s.clip(1.5, upper), Series([1.5, 1.5, 3.5]))
closes #15400 In [1]: np.random.seed(1234) In [2]: s = pd.Series(np.random.randn(50)) master ``` In [3]: %timeit s.clip(0, 1) 1.65 ms ± 48.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` PR ``` In [3]: %timeit s.clip(0, 1) 124 µs ± 2.79 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` prob as good as can do for now as we still have 2 where ops (numpy does this in a single loop), and we have a mask check and fill (and final construction). but about 15x better
https://api.github.com/repos/pandas-dev/pandas/pulls/16364
2017-05-16T02:33:08Z
2017-05-16T11:02:41Z
2017-05-16T11:02:40Z
2017-05-30T12:22:29Z
GH15943 Fixed defaults for compression in HDF5
diff --git a/doc/source/io.rst b/doc/source/io.rst index 7ea476514e88d..c8a9bfb658e6e 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -4066,26 +4066,64 @@ Compression +++++++++++ ``PyTables`` allows the stored data to be compressed. This applies to -all kinds of stores, not just tables. +all kinds of stores, not just tables. Two parameters are used to +control compression: ``complevel`` and ``complib``. + +``complevel`` specifies if and how hard data is to be compressed. + ``complevel=0`` and ``complevel=None`` disables + compression and ``0<complevel<10`` enables compression. + +``complib`` specifies which compression library to use. If nothing is + specified the default library ``zlib`` is used. A + compression library usually optimizes for either good + compression rates or speed and the results will depend on + the type of data. Which type of + compression to choose depends on your specific needs and + data. The list of supported compression libraries: + + - `zlib <http://zlib.net/>`_: The default compression library. A classic in terms of compression, achieves good compression rates but is somewhat slow. + - `lzo <http://www.oberhumer.com/opensource/lzo/>`_: Fast compression and decompression. + - `bzip2 <http://bzip.org/>`_: Good compression rates. + - `blosc <http://www.blosc.org/>`_: Fast compression and decompression. + + .. versionadded:: 0.20.2 + + Support for alternative blosc compressors: + + - `blosc:blosclz <http://www.blosc.org/>`_ This is the + default compressor for ``blosc`` + - `blosc:lz4 + <https://fastcompression.blogspot.dk/p/lz4.html>`_: + A compact, very popular and fast compressor. + - `blosc:lz4hc + <https://fastcompression.blogspot.dk/p/lz4.html>`_: + A tweaked version of LZ4, produces better + compression ratios at the expense of speed. + - `blosc:snappy <https://google.github.io/snappy/>`_: + A popular compressor used in many places. + - `blosc:zlib <http://zlib.net/>`_: A classic; + somewhat slower than the previous ones, but + achieving better compression ratios. + - `blosc:zstd <https://facebook.github.io/zstd/>`_: An + extremely well balanced codec; it provides the best + compression ratios among the others above, and at + reasonably fast speed. + + If ``complib`` is defined as something other than the + listed libraries a ``ValueError`` exception is issued. -- Pass ``complevel=int`` for a compression level (1-9, with 0 being no - compression, and the default) -- Pass ``complib=lib`` where lib is any of ``zlib, bzip2, lzo, blosc`` for - whichever compression library you prefer. +.. note:: -``HDFStore`` will use the file based compression scheme if no overriding -``complib`` or ``complevel`` options are provided. ``blosc`` offers very -fast compression, and is my most used. Note that ``lzo`` and ``bzip2`` -may not be installed (by Python) by default. + If the library specified with the ``complib`` option is missing on your platform, + compression defaults to ``zlib`` without further ado. -Compression for all objects within the file +Enable compression for all objects within the file: .. code-block:: python - store_compressed = pd.HDFStore('store_compressed.h5', complevel=9, complib='blosc') + store_compressed = pd.HDFStore('store_compressed.h5', complevel=9, complib='blosc:blosclz') -Or on-the-fly compression (this only applies to tables). You can turn -off file compression for a specific table by passing ``complevel=0`` +Or on-the-fly compression (this only applies to tables) in stores where compression is not enabled: .. code-block:: python diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 36ca79e8b8714..9b25f7d67aad4 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -46,13 +46,12 @@ Backwards incompatible API changes - Support has been dropped for Python 3.4 (:issue:`15251`) - The Categorical constructor no longer accepts a scalar for the ``categories`` keyword. (:issue:`16022`) - - Accessing a non-existent attribute on a closed :class:`HDFStore` will now raise an ``AttributeError`` rather than a ``ClosedFileError`` (:issue:`16301`) - :func:`read_csv` now treats ``'null'`` strings as missing values by default (:issue:`16471`) - :func:`read_csv` now treats ``'n/a'`` strings as missing values by default (:issue:`16078`) - - :class:`pandas.HDFStore`'s string representation is now faster and less detailed. For the previous behavior, use ``pandas.HDFStore.info()``. (:issue:`16503`). +- Compression defaults in HDF stores now follow pytable standards. Default is no compression and if ``complib`` is missing and ``complevel`` > 0 ``zlib`` is used (:issue:`15943`) .. _whatsnew_0210.api: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 8b186bab29d5e..e978dd8b1b62e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1278,10 +1278,10 @@ def to_hdf(self, path_or_buf, key, **kwargs): <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__. Applicable only to format='table'. - complevel : int, 0-9, default 0 + complevel : int, 0-9, default None Specifies a compression level for data. A value of 0 disables compression. - complib : {'zlib', 'lzo', 'bzip2', 'blosc', None}, default None + complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib' Specifies the compression library to be used. As of v0.20.2 these additional compressors for Blosc are supported (default if no compressor specified: 'blosc:blosclz'): diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 9539b73c754e1..f83380b18beb3 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -411,10 +411,10 @@ class HDFStore(StringMixin): and if the file does not exist it is created. ``'r+'`` It is similar to ``'a'``, but the file must already exist. - complevel : int, 0-9, default 0 + complevel : int, 0-9, default None Specifies a compression level for data. A value of 0 disables compression. - complib : {'zlib', 'lzo', 'bzip2', 'blosc', None}, default None + complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib' Specifies the compression library to be used. As of v0.20.2 these additional compressors for Blosc are supported (default if no compressor specified: 'blosc:blosclz'): @@ -449,12 +449,15 @@ def __init__(self, path, mode=None, complevel=None, complib=None, "complib only supports {libs} compression.".format( libs=tables.filters.all_complibs)) + if complib is None and complevel is not None: + complib = tables.filters.default_complib + self._path = _stringify_path(path) if mode is None: mode = 'a' self._mode = mode self._handle = None - self._complevel = complevel + self._complevel = complevel if complevel else 0 self._complib = complib self._fletcher32 = fletcher32 self._filters = None @@ -566,11 +569,8 @@ def open(self, mode='a', **kwargs): if self.is_open: self.close() - if self._complib is not None: - if self._complevel is None: - self._complevel = 9 - self._filters = _tables().Filters(self._complevel, - self._complib, + if self._complevel and self._complevel > 0: + self._filters = _tables().Filters(self._complevel, self._complib, fletcher32=self._fletcher32) try: diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index efec778e12b50..86ff368e97b9e 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -736,6 +736,59 @@ def test_put_compression_blosc(self): store.put('c', df, format='table', complib='blosc') tm.assert_frame_equal(store['c'], df) + def test_complibs_default_settings(self): + # GH15943 + df = tm.makeDataFrame() + + # Set complevel and check if complib is automatically set to + # default value + with ensure_clean_path(self.path) as tmpfile: + df.to_hdf(tmpfile, 'df', complevel=9) + result = pd.read_hdf(tmpfile, 'df') + tm.assert_frame_equal(result, df) + + with tables.open_file(tmpfile, mode='r') as h5file: + for node in h5file.walk_nodes(where='/df', classname='Leaf'): + assert node.filters.complevel == 9 + assert node.filters.complib == 'zlib' + + # Set complib and check to see if compression is disabled + with ensure_clean_path(self.path) as tmpfile: + df.to_hdf(tmpfile, 'df', complib='zlib') + result = pd.read_hdf(tmpfile, 'df') + tm.assert_frame_equal(result, df) + + with tables.open_file(tmpfile, mode='r') as h5file: + for node in h5file.walk_nodes(where='/df', classname='Leaf'): + assert node.filters.complevel == 0 + assert node.filters.complib is None + + # Check if not setting complib or complevel results in no compression + with ensure_clean_path(self.path) as tmpfile: + df.to_hdf(tmpfile, 'df') + result = pd.read_hdf(tmpfile, 'df') + tm.assert_frame_equal(result, df) + + with tables.open_file(tmpfile, mode='r') as h5file: + for node in h5file.walk_nodes(where='/df', classname='Leaf'): + assert node.filters.complevel == 0 + assert node.filters.complib is None + + # Check if file-defaults can be overridden on a per table basis + with ensure_clean_path(self.path) as tmpfile: + store = pd.HDFStore(tmpfile) + store.append('dfc', df, complevel=9, complib='blosc') + store.append('df', df) + store.close() + + with tables.open_file(tmpfile, mode='r') as h5file: + for node in h5file.walk_nodes(where='/df', classname='Leaf'): + assert node.filters.complevel == 0 + assert node.filters.complib is None + for node in h5file.walk_nodes(where='/dfc', classname='Leaf'): + assert node.filters.complevel == 9 + assert node.filters.complib == 'blosc' + def test_complibs(self): # GH14478 df = tm.makeDataFrame()
- [x] closes #15943 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16355
2017-05-15T11:41:29Z
2017-06-13T23:20:59Z
2017-06-13T23:20:59Z
2017-06-14T06:10:37Z
ENH: Improve error message for header argument containing non int types. GH16338
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 3df0a21facb02..861bde7161519 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -83,6 +83,7 @@ Indexing I/O ^^^ +- Bug in ``pd.read_csv()`` in which non integer values for the header argument generated an unhelpful / unrelated error message (:issue:`16338`) Plotting diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index ce8643504932f..e287d92f67ef6 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1164,6 +1164,8 @@ def __init__(self, kwds): # validate header options for mi self.header = kwds.get('header') if isinstance(self.header, (list, tuple, np.ndarray)): + if not all(map(is_integer, self.header)): + raise ValueError("header must be integer or list of integers") if kwds.get('as_recarray'): raise ValueError("cannot specify as_recarray when " "specifying a multi-index header") @@ -1184,6 +1186,10 @@ def __init__(self, kwds): raise ValueError("index_col must only contain row numbers " "when specifying a multi-index header") + # GH 16338 + elif self.header is not None and not is_integer(self.header): + raise ValueError("header must be integer or list of integers") + self._name_processed = False self._first_chunk = True diff --git a/pandas/tests/io/parser/header.py b/pandas/tests/io/parser/header.py index 1e5fb42b4c1d4..4935fd2cd910a 100644 --- a/pandas/tests/io/parser/header.py +++ b/pandas/tests/io/parser/header.py @@ -277,3 +277,12 @@ def test_no_header(self): tm.assert_index_equal(df.columns, Index(lrange(5))) tm.assert_index_equal(df2.columns, Index(names)) + + def test_non_int_header(self): + # GH 16338 + msg = 'header must be integer or list of integers' + data = """1,2\n3,4""" + with tm.assert_raises_regex(ValueError, msg): + self.read_csv(StringIO(data), sep=',', header=['a', 'b']) + with tm.assert_raises_regex(ValueError, msg): + self.read_csv(StringIO(data), sep=',', header='string_header')
Adds error "header must be integer or list of integers" when the header argument is a list, tuple or numpy array containing non-integers. Initially intended to read_csv, but applies to other functions with similar header arguments. GH16338 refers to a case in which the user mixes up the "names" and "header" arguments. - [x] closes #16338 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16351
2017-05-14T05:42:09Z
2017-05-24T13:28:05Z
2017-05-24T13:28:05Z
2017-05-24T13:28:07Z
DOC: add dataframe construction in merge_asof example
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index c55f4b5bf935f..7bf25e37340c4 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -347,12 +347,15 @@ def merge_asof(left, right, on=None, Examples -------- + >>> left = pd.DataFrame({'a': [1, 5, 10], 'left_val': ['a', 'b', 'c']}) >>> left a left_val 0 1 a 1 5 b 2 10 c + >>> right = pd.DataFrame({'a': [1, 2, 3, 6, 7], + ... 'right_val': [1, 2, 3, 6, 7]}) >>> right a right_val 0 1 1 @@ -387,12 +390,15 @@ def merge_asof(left, right, on=None, We can use indexed DataFrames as well. + >>> left = pd.DataFrame({'left_val': ['a', 'b', 'c']}, index=[1, 5, 10]) >>> left left_val 1 a 5 b 10 c + >>> right = pd.DataFrame({'right_val': [1, 2, 3, 6, 7]}, + ... index=[1, 2, 3, 6, 7]) >>> right right_val 1 1
https://api.github.com/repos/pandas-dev/pandas/pulls/16348
2017-05-12T21:45:29Z
2017-05-13T12:10:53Z
2017-05-13T12:10:53Z
2017-05-13T12:10:53Z
PERF: improve MultiIndex get_loc performance
diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index e1676715853a4..6a2c9d48c4a28 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -227,12 +227,24 @@ def time_multiindex_get_indexer(self): def time_multiindex_large_get_loc(self): self.mi_large.get_loc((999, 19, 'Z')) + def time_multiindex_large_get_loc_warm(self): + for _ in range(1000): + self.mi_large.get_loc((999, 19, 'Z')) + def time_multiindex_med_get_loc(self): self.mi_med.get_loc((999, 9, 'A')) + def time_multiindex_med_get_loc_warm(self): + for _ in range(1000): + self.mi_med.get_loc((999, 9, 'A')) + def time_multiindex_string_get_loc(self): self.mi_small.get_loc((99, 'A', 'A')) + def time_multiindex_small_get_loc_warm(self): + for _ in range(1000): + self.mi_small.get_loc((99, 'A', 'A')) + def time_is_monotonic(self): self.miint.is_monotonic diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 10a6b4354290d..7773f5abfb0ba 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -27,9 +27,10 @@ Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Performance regression fix when indexing with a list-like (:issue:`16285`) -- Performance regression fix for small MultiIndexes (:issuse:`16319`) +- Performance regression fix for MultiIndexes (:issue:`16319`, :issue:`16346`) - Improved performance of ``.clip()`` with scalar arguments (:issue:`15400`) + .. _whatsnew_0202.bug_fixes: Bug Fixes diff --git a/pandas/_libs/hashtable.pxd b/pandas/_libs/hashtable.pxd index 3366751af144d..014da22df3382 100644 --- a/pandas/_libs/hashtable.pxd +++ b/pandas/_libs/hashtable.pxd @@ -38,6 +38,8 @@ cdef class MultiIndexHashTable(HashTable): cpdef get_item(self, object val) cpdef set_item(self, object key, Py_ssize_t val) + cdef inline void _check_for_collision(self, Py_ssize_t loc, object label) + cdef class StringHashTable(HashTable): cdef kh_str_t *table diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in index b80a592669eca..3ef52c5c59c9d 100644 --- a/pandas/_libs/hashtable_class_helper.pxi.in +++ b/pandas/_libs/hashtable_class_helper.pxi.in @@ -4,6 +4,9 @@ Template for each `dtype` helper function for hashtable WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in """ +from lib cimport is_null_datetimelike + + #---------------------------------------------------------------------- # VectorData #---------------------------------------------------------------------- @@ -921,6 +924,19 @@ cdef class MultiIndexHashTable(HashTable): "hash collision\nlocs:\n{}\n" "result:\n{}\nmi:\n{}".format(alocs, result, mi)) + cdef inline void _check_for_collision(self, Py_ssize_t loc, object label): + # validate that the loc maps to the actual value + # version of _check_for_collisions above for single label (tuple) + + result = self.mi[loc] + + if not all(l == r or (is_null_datetimelike(l) + and is_null_datetimelike(r)) + for l, r in zip(result, label)): + raise AssertionError( + "hash collision\nloc:\n{}\n" + "result:\n{}\nmi:\n{}".format(loc, result, label)) + def __contains__(self, object key): try: self.get_item(key) @@ -939,8 +955,7 @@ cdef class MultiIndexHashTable(HashTable): k = kh_get_uint64(self.table, value) if k != self.table.n_buckets: loc = self.table.vals[k] - locs = np.array([loc], dtype=np.int64) - self._check_for_collisions(locs, key) + self._check_for_collision(loc, key) return loc else: raise KeyError(key) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 3db5633ec30bd..569e16f2141ae 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -748,7 +748,7 @@ def _hashed_indexing_key(self, key): we need to stringify if we have mixed levels """ - from pandas.core.util.hashing import hash_tuples + from pandas.core.util.hashing import hash_tuples, hash_tuple if not isinstance(key, tuple): return hash_tuples(key) @@ -762,7 +762,7 @@ def f(k, stringify): return k key = tuple([f(k, stringify) for k, stringify in zip(key, self._have_mixed_levels)]) - return hash_tuples(key) + return hash_tuple(key) @Appender(base._shared_docs['duplicated'] % _index_doc_kwargs) def duplicated(self, keep='first'): diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index f0829adc94500..e41ffae9d03c2 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -4,7 +4,7 @@ import itertools import numpy as np -from pandas._libs import hashing +from pandas._libs import hashing, tslib from pandas.core.dtypes.generic import ( ABCMultiIndex, ABCIndexClass, @@ -12,6 +12,9 @@ ABCDataFrame) from pandas.core.dtypes.common import ( is_categorical_dtype, is_list_like) +from pandas.core.dtypes.missing import isnull +from pandas.core.dtypes.cast import infer_dtype_from_scalar + # 16 byte long hashing key _default_hash_key = '0123456789123456' @@ -164,6 +167,29 @@ def hash_tuples(vals, encoding='utf8', hash_key=None): return h +def hash_tuple(val, encoding='utf8', hash_key=None): + """ + Hash a single tuple efficiently + + Parameters + ---------- + val : single tuple + encoding : string, default 'utf8' + hash_key : string key to encode, default to _default_hash_key + + Returns + ------- + hash + + """ + hashes = (_hash_scalar(v, encoding=encoding, hash_key=hash_key) + for v in val) + + h = _combine_hash_arrays(hashes, len(val))[0] + + return h + + def _hash_categorical(c, encoding, hash_key): """ Hash a Categorical by hashing its categories, and then mapping the codes @@ -276,3 +302,31 @@ def hash_array(vals, encoding='utf8', hash_key=None, categorize=True): vals *= np.uint64(0x94d049bb133111eb) vals ^= vals >> 31 return vals + + +def _hash_scalar(val, encoding='utf8', hash_key=None): + """ + Hash scalar value + + Returns + ------- + 1d uint64 numpy array of hash value, of length 1 + """ + + if isnull(val): + # this is to be consistent with the _hash_categorical implementation + return np.array([np.iinfo(np.uint64).max], dtype='u8') + + if getattr(val, 'tzinfo', None) is not None: + # for tz-aware datetimes, we need the underlying naive UTC value and + # not the tz aware object or pd extension type (as + # infer_dtype_from_scalar would do) + if not isinstance(val, tslib.Timestamp): + val = tslib.Timestamp(val) + val = val.tz_convert(None) + + dtype, val = infer_dtype_from_scalar(val) + vals = np.array([val], dtype=dtype) + + return hash_array(vals, hash_key=hash_key, encoding=encoding, + categorize=False) diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py index e1e6e43529a7d..289592939e3da 100644 --- a/pandas/tests/util/test_hashing.py +++ b/pandas/tests/util/test_hashing.py @@ -1,4 +1,5 @@ import pytest +import datetime from warnings import catch_warnings import numpy as np @@ -6,7 +7,7 @@ from pandas import DataFrame, Series, Index, MultiIndex from pandas.util import hash_array, hash_pandas_object -from pandas.core.util.hashing import hash_tuples +from pandas.core.util.hashing import hash_tuples, hash_tuple, _hash_scalar import pandas.util.testing as tm @@ -79,6 +80,27 @@ def test_hash_tuples(self): result = hash_tuples(tups[0]) assert result == expected[0] + def test_hash_tuple(self): + # test equivalence between hash_tuples and hash_tuple + for tup in [(1, 'one'), (1, np.nan), (1.0, pd.NaT, 'A'), + ('A', pd.Timestamp("2012-01-01"))]: + result = hash_tuple(tup) + expected = hash_tuples([tup])[0] + assert result == expected + + def test_hash_scalar(self): + for val in [1, 1.4, 'A', b'A', u'A', pd.Timestamp("2012-01-01"), + pd.Timestamp("2012-01-01", tz='Europe/Brussels'), + datetime.datetime(2012, 1, 1), + pd.Timestamp("2012-01-01", tz='EST').to_pydatetime(), + pd.Timedelta('1 days'), datetime.timedelta(1), + pd.Period('2012-01-01', freq='D'), pd.Interval(0, 1), + np.nan, pd.NaT, None]: + result = _hash_scalar(val) + expected = hash_array(np.array([val], dtype=object), + categorize=True) + assert result[0] == expected[0] + def test_hash_tuples_err(self): for val in [5, 'foo', pd.Timestamp('20130101')]:
While I was timing the MultiIndex get_loc in https://github.com/pandas-dev/pandas/pull/16324, I saw some 'quick wins' with some further profiling. Rationale: - big part of the time was spent in checking for a hash collision: `_check_for_collisions`. This function was a generic one for one or multiple labels. I added a slightly adapted version specialized for a single tuple - another important factor was the hash creation with `hash_tuples`. Again, added specialized version for a single tuple. @jreback I have some questions (will add them as comments), as this is not my specialty, but good opportunity to get more familiar with the inner guts :-) Some timings using ``` import string mi_large = pd.MultiIndex.from_product( [np.arange(1000), np.arange(20), list(string.ascii_letters)], names=['one', 'two', 'three']) ``` master: ``` In [2]: %time mi_large.get_loc((999, 19, 'E')) # <--- first slower cold one CPU times: user 140 ms, sys: 8 ms, total: 148 ms Wall time: 145 ms Out[2]: 1039978 In [3]: %time mi_large.get_loc((999, 19, 'E')) CPU times: user 0 ns, sys: 4 ms, total: 4 ms Wall time: 4.33 ms Out[3]: 1039978 In [4]: %time mi_large.get_loc((999, 19, 'E')) CPU times: user 4 ms, sys: 4 ms, total: 8 ms Wall time: 4.18 ms Out[4]: 1039978 In [5]: %timeit mi_large.get_loc((999, 19, 'E')) 100 loops, best of 3: 2.56 ms per loop In [6]: %%timeit ...: for _ in range(1000): ...: mi_large.get_loc((999, 19, 'E')) ...: 1 loop, best of 3: 2.62 s per loop ``` PR: ``` In [3]: %time mi_large.get_loc((999, 19, 'E')) # <--- first slower cold one CPU times: user 128 ms, sys: 24 ms, total: 152 ms Wall time: 152 ms Out[3]: 1039978 In [4]: %time mi_large.get_loc((999, 19, 'E')) CPU times: user 4 ms, sys: 0 ns, total: 4 ms Wall time: 716 µs Out[4]: 1039978 In [5]: %time mi_large.get_loc((999, 19, 'E')) CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 371 µs Out[5]: 1039978 In [6]: %timeit mi_large.get_loc((999, 19, 'E')) 1000 loops, best of 3: 189 µs per loop In [15]: %%timeit ...: for _ in range(1000): ...: mi_large.get_loc((999, 19, 'E')) ...: 1 loop, best of 3: 188 ms per loop ``` So something between a 5x and 15x improvement (big variability between individual timings)
https://api.github.com/repos/pandas-dev/pandas/pulls/16346
2017-05-12T21:15:35Z
2017-05-17T07:36:52Z
2017-05-17T07:36:52Z
2017-11-27T19:51:31Z
DOC: minor enhancement of DataFrame.insert docstring
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 3b0cc5619a1cd..3d3d56c1e0331 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2559,15 +2559,17 @@ def insert(self, loc, column, value, allow_duplicates=False): """ Insert column into DataFrame at specified location. - If `allow_duplicates` is False, raises Exception if column - is already contained in the DataFrame. + Raises a ValueError if `column` is already contained in the DataFrame, + unless `allow_duplicates` is set to True. Parameters ---------- loc : int - Must have 0 <= loc <= len(columns) - column : object - value : scalar, Series, or array-like + Insertion index. Must verify 0 <= loc <= len(columns) + column : string, number, or hashable object + label of the inserted column + value : int, Series, or array-like + allow_duplicates : bool, optional """ self._ensure_valid_index(value) value = self._sanitize_column(column, value, broadcast=False)
- [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` (but not clear to me if I did properly, because the first of the pipe only reports the filename of the changed file, no actual diff.) My first objective was to clarify the role of `column` vs `value` keyword. For the reference, this is how this function is documented on http://stackoverflow.com/a/18674915/2822346. Function call is presented as `df.insert(idx, col_name, value)`. I find the `col_name` slightly more explicit than just `column`, which is ambiguous (i.e. "does column holds the Series?"). But of course this name cannot change without breaking the API. So this small PR is just an attempt to clarify things. Since I was touching the docstring, I've also make it a bit more tidy (e.g. removed a too long line).
https://api.github.com/repos/pandas-dev/pandas/pulls/16341
2017-05-12T13:41:17Z
2017-05-18T20:22:31Z
2017-05-18T20:22:31Z
2017-05-18T20:22:40Z
BUG: Categorical constructor scalar categories
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index f392687a0a3fd..afee6a0c2025e 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -36,6 +36,8 @@ Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Support has been dropped for Python 3.4 (:issue:`15251`) +- The Categorical constructor no longer accepts a scalar for the ``categories`` keyword. (:issue:`16022`) + .. _whatsnew_0210.api: @@ -109,6 +111,9 @@ Numeric ^^^^^^^ +Categorical +^^^^^^^^^^^ + Other ^^^^^ diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 7eb86232cbb07..edbb07b7069e9 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -533,6 +533,9 @@ def _validate_categories(cls, categories, fastpath=False): if not isinstance(categories, ABCIndexClass): dtype = None if not hasattr(categories, "dtype"): + if not is_list_like(categories): + raise TypeError("`categories` must be list-like. " + "Got {} instead".format(repr(categories))) categories = _convert_to_list_like(categories) # On categories with NaNs, int values would be converted to # float. Use "object" dtype to prevent this. diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 03adf17f50300..57676be68bedf 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -256,12 +256,6 @@ def f(): assert len(cat.codes) == 1 assert cat.codes[0] == 0 - cat = pd.Categorical([1], categories=1) - assert len(cat.categories) == 1 - assert cat.categories[0] == 1 - assert len(cat.codes) == 1 - assert cat.codes[0] == 0 - # Catch old style constructor useage: two arrays, codes + categories # We can only catch two cases: # - when the first is an integer dtype and the second is not @@ -285,6 +279,11 @@ def f(): c = Categorical(np.array([], dtype='int64'), # noqa categories=[3, 2, 1], ordered=True) + def test_constructor_not_sequence(self): + # https://github.com/pandas-dev/pandas/issues/16022 + with pytest.raises(TypeError): + Categorical(['a', 'b'], categories='a') + def test_constructor_with_null(self): # Cannot have NaN in categories
Categorical constructor no longer accepts scalars for categories. Closes #16022
https://api.github.com/repos/pandas-dev/pandas/pulls/16340
2017-05-12T13:30:29Z
2017-05-16T17:33:59Z
2017-05-16T17:33:59Z
2017-05-27T16:36:48Z
BUG: Categorical comparison with unordered
diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst index a508e84465107..ef558381c5e6f 100644 --- a/doc/source/categorical.rst +++ b/doc/source/categorical.rst @@ -453,6 +453,14 @@ the original values: np.asarray(cat) > base +When you compare two unordered categoricals with the same categories, the order is not considered: + +.. ipython:: python + + c1 = pd.Categorical(['a', 'b'], categories=['a', 'b'], ordered=False) + c2 = pd.Categorical(['a', 'b'], categories=['b', 'a'], ordered=False) + c1 == c2 + Operations ---------- diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 7773f5abfb0ba..be4cf85606935 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -85,7 +85,10 @@ Numeric ^^^^^^^ +Categorical +^^^^^^^^^^^ +- Fixed comparison operations considering the order of the categories when both categoricals are unordered (:issue:`16014`) Other ^^^^^ diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index edbb07b7069e9..5b663f1d85ee7 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -55,17 +55,31 @@ def f(self, other): "equality or not") if isinstance(other, Categorical): # Two Categoricals can only be be compared if the categories are - # the same - if ((len(self.categories) != len(other.categories)) or - not ((self.categories == other.categories).all())): - raise TypeError("Categoricals can only be compared if " - "'categories' are the same") + # the same (maybe up to ordering, depending on ordered) + + msg = ("Categoricals can only be compared if " + "'categories' are the same.") + if len(self.categories) != len(other.categories): + raise TypeError(msg + " Categories are different lengths") + elif (self.ordered and not (self.categories == + other.categories).all()): + raise TypeError(msg) + elif not set(self.categories) == set(other.categories): + raise TypeError(msg) + if not (self.ordered == other.ordered): raise TypeError("Categoricals can only be compared if " "'ordered' is the same") - na_mask = (self._codes == -1) | (other._codes == -1) + if not self.ordered and not self.categories.equals( + other.categories): + # both unordered and different order + other_codes = _get_codes_for_values(other, self.categories) + else: + other_codes = other._codes + + na_mask = (self._codes == -1) | (other_codes == -1) f = getattr(self._codes, op) - ret = f(other._codes) + ret = f(other_codes) if na_mask.any(): # In other series, the leads to False, so do that here too ret[na_mask] = False diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 57676be68bedf..f48eea23220b8 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -3821,6 +3821,43 @@ def test_cat_equality(self): pytest.raises(TypeError, lambda: a > b) pytest.raises(TypeError, lambda: b > a) + @pytest.mark.parametrize('ctor', [ + lambda *args, **kwargs: Categorical(*args, **kwargs), + lambda *args, **kwargs: Series(Categorical(*args, **kwargs)), + ]) + def test_unordered_different_order_equal(self, ctor): + # https://github.com/pandas-dev/pandas/issues/16014 + c1 = ctor(['a', 'b'], categories=['a', 'b'], ordered=False) + c2 = ctor(['a', 'b'], categories=['b', 'a'], ordered=False) + assert (c1 == c2).all() + + c1 = ctor(['a', 'b'], categories=['a', 'b'], ordered=False) + c2 = ctor(['b', 'a'], categories=['b', 'a'], ordered=False) + assert (c1 != c2).all() + + c1 = ctor(['a', 'a'], categories=['a', 'b'], ordered=False) + c2 = ctor(['b', 'b'], categories=['b', 'a'], ordered=False) + assert (c1 != c2).all() + + c1 = ctor(['a', 'a'], categories=['a', 'b'], ordered=False) + c2 = ctor(['a', 'b'], categories=['b', 'a'], ordered=False) + result = c1 == c2 + tm.assert_numpy_array_equal(np.array(result), np.array([True, False])) + + def test_unordered_different_categories_raises(self): + c1 = Categorical(['a', 'b'], categories=['a', 'b'], ordered=False) + c2 = Categorical(['a', 'c'], categories=['c', 'a'], ordered=False) + with tm.assert_raises_regex(TypeError, + "Categoricals can only be compared"): + c1 == c2 + + def test_compare_different_lengths(self): + c1 = Categorical([], categories=['a', 'b']) + c2 = Categorical([], categories=['a']) + msg = "Categories are different lengths" + with tm.assert_raises_regex(TypeError, msg): + c1 == c2 + def test_concat_append(self): cat = pd.Categorical(["a", "b"], categories=["a", "b"]) vals = [1, 2]
Fixes categorical comparison operations improperly considering ordering when two unordered categoricals are compared. Closes #16014
https://api.github.com/repos/pandas-dev/pandas/pulls/16339
2017-05-12T13:07:14Z
2017-05-18T14:05:55Z
2017-05-18T14:05:55Z
2017-05-30T12:20:38Z
Correctly redirect to SetupTools documentations
diff --git a/doc/source/install.rst b/doc/source/install.rst index 578caae605471..48d51e1200447 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -202,7 +202,7 @@ installed), make sure you have `pytest Dependencies ------------ -* `setuptools <http://pythonhosted.org/setuptools>`__ +* `setuptools <https://setuptools.readthedocs.io/en/latest/>`__ * `NumPy <http://www.numpy.org>`__: 1.7.1 or higher * `python-dateutil <http://labix.org/python-dateutil>`__: 1.5 or higher * `pytz <http://pytz.sourceforge.net/>`__: Needed for time zone support
- [x] closes #16332 - [x] tests added / passed - [ ] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] Correct doc string from http://pythonhosted.org/setuptools to https://setuptools.readthedocs.io/en/latest
https://api.github.com/repos/pandas-dev/pandas/pulls/16333
2017-05-11T18:58:19Z
2017-05-11T19:24:47Z
2017-05-11T19:24:47Z
2017-05-30T12:20:38Z
DOC: Handle missing nbconvert in html build
diff --git a/doc/make.py b/doc/make.py index e70655c3e2f92..316ce58812f82 100755 --- a/doc/make.py +++ b/doc/make.py @@ -115,15 +115,28 @@ def maybe_exclude_notebooks(): notebooks = [os.path.join(base, 'source', nb) for nb in ['style.ipynb']] contents = {} - try: - import nbconvert - nbconvert.utils.pandoc.get_pandoc_version() - except (ImportError, nbconvert.utils.pandoc.PandocMissing): - print("Warning: Pandoc is not installed. Skipping Notebooks.") + + def _remove_notebooks(): for nb in notebooks: with open(nb, 'rt') as f: contents[nb] = f.read() os.remove(nb) + + # Skip notebook conversion if + # 1. nbconvert isn't installed, or + # 2. nbconvert is installed, but pandoc isn't + try: + import nbconvert + except ImportError: + print("Warning: nbconvert not installed. Skipping notebooks.") + _remove_notebooks() + else: + try: + nbconvert.utils.pandoc.get_pandoc_version() + except nbconvert.utils.pandoc.PandocMissing: + print("Warning: Pandoc is not installed. Skipping notebooks.") + _remove_notebooks() + yield for nb, content in contents.items(): with open(nb, 'wt') as f:
Closes https://github.com/pandas-dev/pandas/issues/16329
https://api.github.com/repos/pandas-dev/pandas/pulls/16330
2017-05-11T14:17:32Z
2017-05-12T15:32:11Z
2017-05-12T15:32:11Z
2017-05-27T16:36:45Z
ENH: _dir_additions returns also the first level of a MultiIndex
diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index 81c43f7bc975f..0ce003d1a9277 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -177,3 +177,13 @@ def time_value_counts_float64(self): def time_value_counts_strings(self): self.s.value_counts() + + +class series_dir(object): + goal_time = 0.2 + + def setup(self): + self.s = Series(index=tm.makeStringIndex(10000)) + + def time_dir_strings(self): + dir(self.s) diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 29c6dcaef19ab..2ea44722d343d 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -135,6 +135,7 @@ Other Enhancements - Improved wording of ``ValueError`` raised in :func:`read_csv` when the ``usecols`` argument cannot match all columns. (:issue:`17301`) - :func:`DataFrame.corrwith` now silently drops non-numeric columns when passed a Series. Before, an exception was raised (:issue:`18570`). - :class:`IntervalIndex` now supports time zone aware ``Interval`` objects (:issue:`18537`, :issue:`18538`) +- :func:`Series` / :func:`DataFrame` tab completion also returns identifiers in the first level of a :func:`MultiIndex`. (:issue:`16326`) - :func:`read_excel()` has gained the ``nrows`` parameter (:issue:`16645`) - :func:``DataFrame.to_json`` and ``Series.to_json`` now accept an ``index`` argument which allows the user to exclude the index from the JSON output (:issue:`17394`) @@ -232,9 +233,10 @@ Performance Improvements - The overriden ``Timedelta`` properties of days, seconds and microseconds have been removed, leveraging their built-in Python versions instead (:issue:`18242`) - ``Series`` construction will reduce the number of copies made of the input data in certain cases (:issue:`17449`) - Improved performance of :func:`Series.dt.date` and :func:`DatetimeIndex.date` (:issue:`18058`) +- Improved performance of :func:`Series.dt.time` and :func:`DatetimeIndex.time` (:issue:`18461`) - Improved performance of :func:`IntervalIndex.symmetric_difference()` (:issue:`18475`) - Improved performance of ``DatetimeIndex`` and ``Series`` arithmetic operations with Business-Month and Business-Quarter frequencies (:issue:`18489`) -- Improved performance of :func:`Series.dt.time` and :func:`DatetimeIndex.time` +- :func:`Series` / :func:`DataFrame` tab completion limits to 100 values, for better performance. (:issue:`18587`) .. _whatsnew_0220.docs: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 79ba18140c651..da550dccc9c89 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -195,9 +195,12 @@ def __unicode__(self): return '%s(%s)' % (self.__class__.__name__, prepr) def _dir_additions(self): - """ add the string-like attributes from the info_axis """ - additions = set([c for c in self._info_axis - if isinstance(c, string_types) and isidentifier(c)]) + """ add the string-like attributes from the info_axis. + If info_axis is a MultiIndex, it's first level values are used. + """ + additions = set( + [c for c in self._info_axis.unique(level=0)[:100] + if isinstance(c, string_types) and isidentifier(c)]) return super(NDFrame, self)._dir_additions().union(additions) @property diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 7e952a87688bc..91fe7f99ca681 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -128,6 +128,24 @@ def test_column_contains_typeerror(self): except TypeError: pass + def test_tab_completion(self): + # DataFrame whose columns are identifiers shall have them in __dir__. + df = pd.DataFrame([list('abcd'), list('efgh')], columns=list('ABCD')) + for key in list('ABCD'): + assert key in dir(df) + assert isinstance(df.__getitem__('A'), pd.Series) + + # DataFrame whose first-level columns are identifiers shall have + # them in __dir__. + df = pd.DataFrame( + [list('abcd'), list('efgh')], + columns=pd.MultiIndex.from_tuples(list(zip('ABCD', 'EFGH')))) + for key in list('ABCD'): + assert key in dir(df) + for key in list('EFGH'): + assert key not in dir(df) + assert isinstance(df.__getitem__('A'), pd.DataFrame) + def test_not_hashable(self): df = self.klass([1]) pytest.raises(TypeError, hash, df) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 2898ace27f535..617ca2199f588 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -10,7 +10,7 @@ from pandas import Index, Series, DataFrame, date_range from pandas.core.indexes.datetimes import Timestamp -from pandas.compat import range +from pandas.compat import range, lzip, isidentifier, string_types from pandas import (compat, Categorical, period_range, timedelta_range, DatetimeIndex, PeriodIndex, TimedeltaIndex) import pandas.io.formats.printing as printing @@ -250,6 +250,33 @@ def get_dir(s): results = get_dir(s) tm.assert_almost_equal(results, list(sorted(set(ok_for_cat)))) + @pytest.mark.parametrize("index", [ + tm.makeUnicodeIndex(10), + tm.makeStringIndex(10), + tm.makeCategoricalIndex(10), + Index(['foo', 'bar', 'baz'] * 2), + tm.makeDateIndex(10), + tm.makePeriodIndex(10), + tm.makeTimedeltaIndex(10), + tm.makeIntIndex(10), + tm.makeUIntIndex(10), + tm.makeIntIndex(10), + tm.makeFloatIndex(10), + Index([True, False]), + Index(['a{}'.format(i) for i in range(101)]), + pd.MultiIndex.from_tuples(lzip('ABCD', 'EFGH')), + pd.MultiIndex.from_tuples(lzip([0, 1, 2, 3], 'EFGH')), ]) + def test_index_tab_completion(self, index): + # dir contains string-like values of the Index. + s = pd.Series(index=index) + dir_s = dir(s) + for i, x in enumerate(s.index.unique(level=0)): + if i < 100: + assert (not isinstance(x, string_types) or + not isidentifier(x) or x in dir_s) + else: + assert x not in dir_s + def test_not_hashable(self): s_empty = Series() s = Series([1])
- [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry Assuming a DataFrame with MultiIndex columns like this: ```python >> df foo bar foo bar 0 0.32 0.15 0.45 1 0.62 0.73 0.36 2 0.21 0.68 0.10 3 0.05 0.36 0.90 ``` one can access to `df['foo']` and `df['bar']` with the shortcuts `df.foo` and `df.bar`, but one don't benefit from autocompletion because 'foo' and 'bar' are not listed in `dir(df)`. ```python >> 'bar' in dir(df) False ``` This PR extends `df._dir_additions` so that the first level of a MultiIndex is listed in `dir(df)`. ```python >> 'bar' in dir(df) True ```
https://api.github.com/repos/pandas-dev/pandas/pulls/16326
2017-05-11T09:29:24Z
2017-12-11T11:23:44Z
2017-12-11T11:23:44Z
2017-12-11T13:16:34Z
BUG: Preserve data order when stacking unsorted levels (#16323)
diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index bca92137891a0..983f3edfa2f46 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -73,7 +73,7 @@ Sparse Reshaping ^^^^^^^^^ - +- Bug in ``DataFrame.stack`` with unsorted levels in MultiIndex columns (:issue:`16323`) Numeric diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 779002b300cc7..b0ed6d4c4b84d 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -689,7 +689,7 @@ def _convert_level_number(level_num, columns): new_labels = [np.arange(N).repeat(levsize)] new_names = [this.index.name] # something better? - new_levels.append(frame.columns.levels[level_num]) + new_levels.append(level_vals) new_labels.append(np.tile(level_labels, N)) new_names.append(frame.columns.names[level_num]) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 9d80190ae2813..c8c210c42eac2 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -1193,6 +1193,37 @@ def test_unstack_unobserved_keys(self): recons = result.stack() tm.assert_frame_equal(recons, df) + def test_stack_order_with_unsorted_levels(self): + # GH 16323 + + def manual_compare_stacked(df, df_stacked, lev0, lev1): + assert all(df.loc[row, col] == + df_stacked.loc[(row, col[lev0]), col[lev1]] + for row in df.index for col in df.columns) + + # deep check for 1-row case + for width in [2, 3]: + levels_poss = itertools.product( + itertools.permutations([0, 1, 2], width), + repeat=2) + + for levels in levels_poss: + columns = MultiIndex(levels=levels, + labels=[[0, 0, 1, 1], + [0, 1, 0, 1]]) + df = DataFrame(columns=columns, data=[range(4)]) + for stack_lev in range(2): + df_stacked = df.stack(stack_lev) + manual_compare_stacked(df, df_stacked, + stack_lev, 1 - stack_lev) + + # check multi-row case + mi = MultiIndex(levels=[["A", "C", "B"], ["B", "A", "C"]], + labels=[np.repeat(range(3), 3), np.tile(range(3), 3)]) + df = DataFrame(columns=mi, index=range(5), + data=np.arange(5 * len(mi)).reshape(5, -1)) + manual_compare_stacked(df, df.stack(0), 0, 1) + def test_groupby_corner(self): midx = MultiIndex(levels=[['foo'], ['bar'], ['baz']], labels=[[0], [0], [0]],
This should fix the df.stack() problems in #16323-- the levels being used to build the new index were those of the original frame, which fails when the levels get sorted. - [X] closes #16323 - [X] tests added / passed - [X] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16325
2017-05-11T03:41:10Z
2017-05-11T11:25:14Z
2017-05-11T11:25:14Z
2017-05-30T12:20:38Z
PERF: improved performance of small multiindexes
diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 31af56b3715a5..e1676715853a4 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -193,9 +193,15 @@ def setup(self): np.arange(1000)], names=['one', 'two']) import string - self.mistring = MultiIndex.from_product( - [np.arange(1000), - np.arange(20), list(string.ascii_letters)], + + self.mi_large = MultiIndex.from_product( + [np.arange(1000), np.arange(20), list(string.ascii_letters)], + names=['one', 'two', 'three']) + self.mi_med = MultiIndex.from_product( + [np.arange(1000), np.arange(10), list('A')], + names=['one', 'two', 'three']) + self.mi_small = MultiIndex.from_product( + [np.arange(100), list('A'), list('A')], names=['one', 'two', 'three']) def time_series_xs_mi_ix(self): @@ -218,8 +224,14 @@ def time_multiindex_get_indexer(self): (0, 16), (0, 17), (0, 18), (0, 19)], dtype=object)) + def time_multiindex_large_get_loc(self): + self.mi_large.get_loc((999, 19, 'Z')) + + def time_multiindex_med_get_loc(self): + self.mi_med.get_loc((999, 9, 'A')) + def time_multiindex_string_get_loc(self): - self.mistring.get_loc((999, 19, 'Z')) + self.mi_small.get_loc((99, 'A', 'A')) def time_is_monotonic(self): self.miint.is_monotonic diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index cbfebee2ceba2..eb8da474be6b3 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -27,7 +27,7 @@ Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Performance regression fix when indexing with a list-like (:issue:`16285`) - +- Performance regression fix for small MultiIndexes (:issuse:`16319`) .. _whatsnew_0202.bug_fixes: diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index c7a537acf5d6f..21680fb0b3921 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -553,7 +553,34 @@ cdef inline bint _is_utc(object tz): return tz is UTC or isinstance(tz, _du_utc) -cdef class MultiIndexEngine(IndexEngine): +cdef class MultiIndexObjectEngine(ObjectEngine): + """ + provide the same interface as the MultiIndexEngine + but use the IndexEngine for computation + + This provides good performance with samller MI's + """ + def get_indexer(self, values): + # convert a MI to an ndarray + if hasattr(values, 'values'): + values = values.values + return super(MultiIndexObjectEngine, self).get_indexer(values) + + cpdef get_loc(self, object val): + + # convert a MI to an ndarray + if hasattr(val, 'values'): + val = val.values + return super(MultiIndexObjectEngine, self).get_loc(val) + + +cdef class MultiIndexHashEngine(ObjectEngine): + """ + Use a hashing based MultiIndex impl + but use the IndexEngine for computation + + This provides good performance with larger MI's + """ def _call_monotonic(self, object mi): # defer these back to the mi iteself @@ -584,6 +611,10 @@ cdef class MultiIndexEngine(IndexEngine): except TypeError: raise KeyError(val) + def get_indexer(self, values): + self._ensure_mapping_populated() + return self.mapping.lookup(values) + cdef _make_hash_table(self, n): return _hash.MultiIndexHashTable(n) diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 561f1951a4151..dc2c56ea476f9 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -88,12 +88,12 @@ def is_dtype(cls, dtype): """ if hasattr(dtype, 'dtype'): dtype = dtype.dtype - if isinstance(dtype, cls): - return True - elif isinstance(dtype, np.dtype): + if isinstance(dtype, np.dtype): return False elif dtype is None: return False + elif isinstance(dtype, cls): + return True try: return cls.construct_from_string(dtype) is not None except: diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 7ef037d8f3536..3db5633ec30bd 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -75,7 +75,6 @@ class MultiIndex(Index): _levels = FrozenList() _labels = FrozenList() _comparables = ['names'] - _engine_type = libindex.MultiIndexEngine rename = Index.set_names def __new__(cls, levels=None, labels=None, sortorder=None, names=None, @@ -629,7 +628,16 @@ def _get_level_number(self, level): @cache_readonly def _engine(self): - return self._engine_type(lambda: self, len(self)) + + # choose our engine based on our size + # the hashing based MultiIndex for larger + # sizes, and the MultiIndexOjbect for smaller + # xref: https://github.com/pandas-dev/pandas/pull/16324 + l = len(self) + if l > 10000: + return libindex.MultiIndexHashEngine(lambda: self, l) + + return libindex.MultiIndexObjectEngine(lambda: self.values, l) @property def values(self): diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index 6a5343e8a8e25..f0829adc94500 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -5,16 +5,13 @@ import numpy as np from pandas._libs import hashing -from pandas._libs.lib import is_bool_array from pandas.core.dtypes.generic import ( ABCMultiIndex, ABCIndexClass, ABCSeries, ABCDataFrame) from pandas.core.dtypes.common import ( - is_categorical_dtype, is_numeric_dtype, - is_datetime64_dtype, is_timedelta64_dtype, - is_list_like) + is_categorical_dtype, is_list_like) # 16 byte long hashing key _default_hash_key = '0123456789123456' @@ -136,7 +133,6 @@ def hash_tuples(vals, encoding='utf8', hash_key=None): ------- ndarray of hashed values array """ - is_tuple = False if isinstance(vals, tuple): vals = [vals] @@ -231,6 +227,7 @@ def hash_array(vals, encoding='utf8', hash_key=None, categorize=True): if not hasattr(vals, 'dtype'): raise TypeError("must pass a ndarray-like") + dtype = vals.dtype if hash_key is None: hash_key = _default_hash_key @@ -238,22 +235,21 @@ def hash_array(vals, encoding='utf8', hash_key=None, categorize=True): # For categoricals, we hash the categories, then remap the codes to the # hash values. (This check is above the complex check so that we don't ask # numpy if categorical is a subdtype of complex, as it will choke. - if is_categorical_dtype(vals.dtype): + if is_categorical_dtype(dtype): return _hash_categorical(vals, encoding, hash_key) # we'll be working with everything as 64-bit values, so handle this # 128-bit value early - if np.issubdtype(vals.dtype, np.complex128): + elif np.issubdtype(dtype, np.complex128): return hash_array(vals.real) + 23 * hash_array(vals.imag) # First, turn whatever array this is into unsigned 64-bit ints, if we can # manage it. - if is_bool_array(vals): + elif isinstance(dtype, np.bool): vals = vals.astype('u8') - elif (is_datetime64_dtype(vals) or - is_timedelta64_dtype(vals)): + elif issubclass(dtype.type, (np.datetime64, np.timedelta64)): vals = vals.view('i8').astype('u8', copy=False) - elif (is_numeric_dtype(vals) and vals.dtype.itemsize <= 8): + elif issubclass(dtype.type, np.number) and dtype.itemsize <= 8: vals = vals.view('u{}'.format(vals.dtype.itemsize)).astype('u8') else: # With repeated values, its MUCH faster to categorize object dtypes,
closes #16319 When I did #15245 the goal was two fold - Reduce the hashtable creation time for a MultiIndex - Reduce the memory footprint original impl ------------- These are interrelated, as the original impl of a MI constructed a list of tuples for each value (the len of the tuple is the number of levels). Then we construct a PyObject based hashtable. This is pretty slow & has the side effect of blowing up memory as a list of tuples is pretty heavyweight (when you have a large one). Indexing is simple, you simply hash a passed tuple and do a lookup in the hashtable. This is quite fast. hashtable impl --------------- The new implementation, instead data hashes the levels themselves and performs transforms to preserve ordering. This is much faster than the original implementation because we have common dtypes and can construct these hashes in a vectorized way. So this is fast and memory efficient Looking up a value involves constructing the hash for a tuple. This has some overhead as for impl simplicity this is partly python code and has a few steps. This could be improved. So the actual construction of the hash of the value to be lookuped up is slower than the original impl. Naive timing of an indexing on a new DataFrame is very misleading. ``%timeit`` gives the min time, which includes the construction cost on the first iteration, and subequent access times. However it returns the min, which is obviously not including the cached time. We actually care about the *sum* of access times. We *always* have to construct the hash table in order to index, so its cost is more than relevant, in fact it would dominate things. This PR allow the original implementation for smaller MultiIndexes. I chose 10000 elmenents (times are still slightly slower for the hash-based construction by bout 1.5x, but balancing memory bloat here). It is vastly better for larger than this. (if some enterprising soul wants to draw the graph of amortized construction cost would be great!) So we at run-time choose the engine for indexing. We can then have good smallish perf, and nice scaling on larger hash tables. setup ``` import string mi_large = pd.MultiIndex.from_product( [np.arange(1000), np.arange(20), list(string.ascii_letters)], names=['one', 'two', 'three']) mi_med = pd.MultiIndex.from_product( [np.arange(1000), np.arange(10), list('A')], names=['one', 'two', 'three']) mi_small = pd.MultiIndex.from_product( [np.arange(100), list('A'), list('A')], names=['one', 'two', 'three']) ``` These timing show index construction cost (first execution), and marginal after than (2nd) for small, med, large. v0.19.2 ``` In [2]: %time mi_small.get_loc((99, 'A')) CPU times: user 281 µs, sys: 90 µs, total: 371 µs Wall time: 329 µs Out[2]: slice(99, 100, None) In [3]: %time mi_small.get_loc((99, 'A')) CPU times: user 117 µs, sys: 20 µs, total: 137 µs Wall time: 125 µs Out[3]: slice(99, 100, None) In [4]: %time mi_med.get_loc((999, 9, 'A')) CPU times: user 3.37 ms, sys: 918 µs, total: 4.29 ms Wall time: 3.67 ms Out[4]: 9999 In [5]: %time mi_med.get_loc((999, 9, 'A')) CPU times: user 28 µs, sys: 0 ns, total: 28 µs Wall time: 31 µs Out[5]: 9999 In [6]: %time mi_large.get_loc((999, 19, 'E')) CPU times: user 875 ms, sys: 67.9 ms, total: 943 ms Wall time: 943 ms Out[6]: 1039978 In [7]: %time mi_large.get_loc((999, 19, 'E')) CPU times: user 31 µs, sys: 0 ns, total: 31 µs Wall time: 33.9 µs Out[7]: 1039978 ``` PR ``` In [2]: %time mi_small.get_loc((99, 'A')) CPU times: user 254 µs, sys: 37 µs, total: 291 µs Wall time: 260 µs Out[2]: slice(99, 100, None) In [3]: %time mi_small.get_loc((99, 'A')) CPU times: user 129 µs, sys: 17 µs, total: 146 µs Wall time: 135 µs Out[3]: slice(99, 100, None) In [4]: %time mi_med.get_loc((999, 9, 'A')) CPU times: user 3.31 ms, sys: 1.12 ms, total: 4.43 ms Wall time: 5.75 ms Out[4]: 9999 In [5]: %time mi_med.get_loc((999, 9, 'A')) CPU times: user 32 µs, sys: 1 µs, total: 33 µs Wall time: 35.8 µs Out[5]: 9999 In [6]: %time mi_large.get_loc((999, 19, 'E')) CPU times: user 130 ms, sys: 40.3 ms, total: 170 ms Wall time: 171 ms Out[6]: 1039978 In [7]: %time mi_large.get_loc((999, 19, 'E')) CPU times: user 3.44 ms, sys: 348 µs, total: 3.79 ms Wall time: 3.53 ms Out[7]: 1039978 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/16324
2017-05-11T02:50:50Z
2017-05-11T23:14:21Z
2017-05-11T23:14:21Z
2017-05-30T12:23:23Z
Lint rule to catch incorrect sphinx directives
diff --git a/ci/lint.sh b/ci/lint.sh index 4027737900bf9..5d9fafe6c9064 100755 --- a/ci/lint.sh +++ b/ci/lint.sh @@ -90,13 +90,26 @@ if [ "$LINT" ]; then # # Check the following functions: # any(), all(), sum(), max(), min(), list(), dict(), set(), frozenset(), tuple(), str.join() - grep -R --include="*.py*" -E "[^_](any|all|sum|max|min|list|dict|set|frozenset|tuple|join)\(\[.* for .* in .*\]\)" + grep -R --include="*.py*" -E "[^_](any|all|sum|max|min|list|dict|set|frozenset|tuple|join)\(\[.* for .* in .*\]\)" * if [ $? = "0" ]; then RET=1 fi echo "Check for use of lists instead of generators in built-in Python functions DONE" + echo "Check for incorrect sphinx directives" + SPHINX_DIRECTIVES=$(echo \ + "autosummary|contents|currentmodule|deprecated|function|image|"\ + "important|include|ipython|literalinclude|math|module|note|raw|"\ + "seealso|toctree|versionadded|versionchanged|warning" | tr -d "[:space:]") + for path in './pandas' './doc/source' + do + grep -R --include="*.py" --include="*.pyx" --include="*.rst" -E "\.\. ($SPHINX_DIRECTIVES):[^:]" $path + if [ $? = "0" ]; then + RET=1 + fi + done + echo "Check for incorrect sphinx directives DONE" else echo "NOT Linting" fi diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7145fa709c345..f847fbebb091a 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4513,7 +4513,7 @@ def unstack(self, level=-1, fill_value=None): fill_value : replace NaN with this value if the unstack produces missing values - .. versionadded: 0.18.0 + .. versionadded:: 0.18.0 See also -------- @@ -4676,7 +4676,7 @@ def diff(self, periods=1, axis=0): axis : {0 or 'index', 1 or 'columns'}, default 0 Take difference over rows (0) or columns (1). - .. versionadded: 0.16.1 + .. versionadded:: 0.16.1 Returns ------- diff --git a/pandas/core/series.py b/pandas/core/series.py index be1de4c6814ba..d7833526c0408 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1626,7 +1626,7 @@ def append(self, to_append, ignore_index=False, verify_integrity=False): ignore_index : boolean, default False If True, do not use the index labels. - .. versionadded: 0.19.0 + .. versionadded:: 0.19.0 verify_integrity : boolean, default False If True, raise Exception on creating index with duplicates @@ -2213,7 +2213,7 @@ def unstack(self, level=-1, fill_value=None): fill_value : replace NaN with this value if the unstack produces missing values - .. versionadded: 0.18.0 + .. versionadded:: 0.18.0 Examples -------- diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 65f4704da3800..219fb3f67db97 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -114,7 +114,7 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, ---------- arg : integer, float, string, datetime, list, tuple, 1-d array, Series - .. versionadded: 0.18.1 + .. versionadded:: 0.18.1 or DataFrame/dict-like @@ -140,7 +140,7 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, Warning: yearfirst=True is not strict, but will prefer to parse with year first (this is a known bug, based on dateutil beahavior). - .. versionadded: 0.16.1 + .. versionadded:: 0.16.1 utc : boolean, default None Return UTC DatetimeIndex if True (converting any tz-aware @@ -178,13 +178,13 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, - If Timestamp convertible, origin is set to Timestamp identified by origin. - .. versionadded: 0.20.0 + .. versionadded:: 0.20.0 cache : boolean, default False If True, use a cache of unique, converted dates to apply the datetime conversion. May produce sigificant speed-up when parsing duplicate date strings, especially ones with timezone offsets. - .. versionadded: 0.22.0 + .. versionadded:: 0.22.0 Returns ------- diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 2097fb22b3ec5..eef9d165e2447 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -774,7 +774,7 @@ class BusinessHour(BusinessHourMixin, SingleConstructorOffset): """ DateOffset subclass representing possibly n business days - .. versionadded: 0.16.1 + .. versionadded:: 0.16.1 """ _prefix = 'BH' @@ -878,7 +878,7 @@ class CustomBusinessHour(BusinessHourMixin, SingleConstructorOffset): """ DateOffset subclass representing possibly n custom business days - .. versionadded: 0.18.1 + .. versionadded:: 0.18.1 """ _prefix = 'CBH'
- [x] closes #18425 - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/18437
2017-11-22T23:28:18Z
2017-11-24T16:57:04Z
2017-11-24T16:57:03Z
2017-11-24T16:57:10Z
BUG: Copy categorical codes if empty (fixes #18051)
diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 5829481cdb731..682776de2e62c 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -135,6 +135,7 @@ Categorical - Bug in :meth:`DataFrame.astype` where casting to 'category' on an empty ``DataFrame`` causes a segmentation fault (:issue:`18004`) - Error messages in the testing module have been improved when items have different ``CategoricalDtype`` (:issue:`18069`) - ``CategoricalIndex`` can now correctly take a ``pd.api.types.CategoricalDtype`` as its dtype (:issue:`18116`) +- Bug in ``Categorical.unique()`` returning read-only ``codes`` array when all categories were ``NaN`` (:issue:`18051`) Other ^^^^^ diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 03bf09352862b..deaec20586005 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -2276,7 +2276,7 @@ def _recode_for_categories(codes, old_categories, new_categories): if len(old_categories) == 0: # All null anyway, so just retain the nulls - return codes + return codes.copy() indexer = coerce_indexer_dtype(new_categories.get_indexer(old_categories), new_categories) new_codes = take_1d(indexer, codes.copy(), fill_value=-1) diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index ff788fb2347b8..cfc319da1598d 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -848,6 +848,12 @@ def test_value_counts_nunique(self): result = series.nunique() assert result == 11 + # GH 18051 + s = pd.Series(pd.Categorical([])) + assert s.nunique() == 0 + s = pd.Series(pd.Categorical([np.nan])) + assert s.nunique() == 0 + def test_unique(self): # 714 also, dtype=float @@ -873,6 +879,14 @@ def test_unique(self): expected = np.array([1, 2, 3, None], dtype=object) tm.assert_numpy_array_equal(result, expected) + # GH 18051 + s = pd.Series(pd.Categorical([])) + tm.assert_categorical_equal(s.unique(), pd.Categorical([]), + check_dtype=False) + s = pd.Series(pd.Categorical([np.nan])) + tm.assert_categorical_equal(s.unique(), pd.Categorical([np.nan]), + check_dtype=False) + @pytest.mark.parametrize( "tc1, tc2", [
In [agreement with @ghasemnaddaf](https://github.com/pandas-dev/pandas/pull/18279#issuecomment-346488176) , I've finished up his PR #18279 (added correct tests). Is it time still to get this into v0.21.1? - [ x] closes #18051 - [ x] tests added / passed - [x ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/18436
2017-11-22T22:41:06Z
2017-11-23T16:13:48Z
2017-11-23T16:13:47Z
2017-12-11T20:22:53Z
DOC: add whatsnew for #17882
diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 558dd14f24b4f..5829481cdb731 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -86,6 +86,8 @@ I/O - Bug in :meth:`DataFrame.to_csv` when the table had ``MultiIndex`` columns, and a list of strings was passed in for ``header`` (:issue:`5539`) - :func:`read_parquet` now allows to specify the columns to read from a parquet file (:issue:`18154`) - :func:`read_parquet` now allows to specify kwargs which are passed to the respective engine (:issue:`18216`) +- Bug in parsing integer datetime-like columns with specified format in ``read_sql`` (:issue:`17855`). + Plotting ^^^^^^^^
Whatsnew for https://github.com/pandas-dev/pandas/pull/17882
https://api.github.com/repos/pandas-dev/pandas/pulls/18433
2017-11-22T19:31:37Z
2017-11-22T19:32:02Z
2017-11-22T19:32:02Z
2017-11-22T19:32:02Z
TST: move melt tests to separate file
diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py new file mode 100644 index 0000000000000..3c38512548c70 --- /dev/null +++ b/pandas/tests/reshape/test_melt.py @@ -0,0 +1,537 @@ +# -*- coding: utf-8 -*- +# pylint: disable-msg=W0612,E1101 + +import pytest + +from pandas import DataFrame +import pandas as pd + +from numpy import nan +import numpy as np + +from pandas import melt, lreshape, wide_to_long +import pandas.util.testing as tm +from pandas.compat import range + + +class TestMelt(object): + + def setup_method(self, method): + self.df = tm.makeTimeDataFrame()[:10] + self.df['id1'] = (self.df['A'] > 0).astype(np.int64) + self.df['id2'] = (self.df['B'] > 0).astype(np.int64) + + self.var_name = 'var' + self.value_name = 'val' + + self.df1 = pd.DataFrame([[1.067683, -1.110463, 0.20867 + ], [-1.321405, 0.368915, -1.055342], + [-0.807333, 0.08298, -0.873361]]) + self.df1.columns = [list('ABC'), list('abc')] + self.df1.columns.names = ['CAP', 'low'] + + def test_top_level_method(self): + result = melt(self.df) + assert result.columns.tolist() == ['variable', 'value'] + + def test_method_signatures(self): + tm.assert_frame_equal(self.df.melt(), + melt(self.df)) + + tm.assert_frame_equal(self.df.melt(id_vars=['id1', 'id2'], + value_vars=['A', 'B']), + melt(self.df, + id_vars=['id1', 'id2'], + value_vars=['A', 'B'])) + + tm.assert_frame_equal(self.df.melt(var_name=self.var_name, + value_name=self.value_name), + melt(self.df, + var_name=self.var_name, + value_name=self.value_name)) + + tm.assert_frame_equal(self.df1.melt(col_level=0), + melt(self.df1, col_level=0)) + + def test_default_col_names(self): + result = self.df.melt() + assert result.columns.tolist() == ['variable', 'value'] + + result1 = self.df.melt(id_vars=['id1']) + assert result1.columns.tolist() == ['id1', 'variable', 'value'] + + result2 = self.df.melt(id_vars=['id1', 'id2']) + assert result2.columns.tolist() == ['id1', 'id2', 'variable', 'value'] + + def test_value_vars(self): + result3 = self.df.melt(id_vars=['id1', 'id2'], value_vars='A') + assert len(result3) == 10 + + result4 = self.df.melt(id_vars=['id1', 'id2'], value_vars=['A', 'B']) + expected4 = DataFrame({'id1': self.df['id1'].tolist() * 2, + 'id2': self.df['id2'].tolist() * 2, + 'variable': ['A'] * 10 + ['B'] * 10, + 'value': (self.df['A'].tolist() + + self.df['B'].tolist())}, + columns=['id1', 'id2', 'variable', 'value']) + tm.assert_frame_equal(result4, expected4) + + def test_value_vars_types(self): + # GH 15348 + expected = DataFrame({'id1': self.df['id1'].tolist() * 2, + 'id2': self.df['id2'].tolist() * 2, + 'variable': ['A'] * 10 + ['B'] * 10, + 'value': (self.df['A'].tolist() + + self.df['B'].tolist())}, + columns=['id1', 'id2', 'variable', 'value']) + + for type_ in (tuple, list, np.array): + result = self.df.melt(id_vars=['id1', 'id2'], + value_vars=type_(('A', 'B'))) + tm.assert_frame_equal(result, expected) + + def test_vars_work_with_multiindex(self): + expected = DataFrame({ + ('A', 'a'): self.df1[('A', 'a')], + 'CAP': ['B'] * len(self.df1), + 'low': ['b'] * len(self.df1), + 'value': self.df1[('B', 'b')], + }, columns=[('A', 'a'), 'CAP', 'low', 'value']) + + result = self.df1.melt(id_vars=[('A', 'a')], value_vars=[('B', 'b')]) + tm.assert_frame_equal(result, expected) + + def test_tuple_vars_fail_with_multiindex(self): + # melt should fail with an informative error message if + # the columns have a MultiIndex and a tuple is passed + # for id_vars or value_vars. + tuple_a = ('A', 'a') + list_a = [tuple_a] + tuple_b = ('B', 'b') + list_b = [tuple_b] + + for id_vars, value_vars in ((tuple_a, list_b), (list_a, tuple_b), + (tuple_a, tuple_b)): + with tm.assert_raises_regex(ValueError, r'MultiIndex'): + self.df1.melt(id_vars=id_vars, value_vars=value_vars) + + def test_custom_var_name(self): + result5 = self.df.melt(var_name=self.var_name) + assert result5.columns.tolist() == ['var', 'value'] + + result6 = self.df.melt(id_vars=['id1'], var_name=self.var_name) + assert result6.columns.tolist() == ['id1', 'var', 'value'] + + result7 = self.df.melt(id_vars=['id1', 'id2'], var_name=self.var_name) + assert result7.columns.tolist() == ['id1', 'id2', 'var', 'value'] + + result8 = self.df.melt(id_vars=['id1', 'id2'], value_vars='A', + var_name=self.var_name) + assert result8.columns.tolist() == ['id1', 'id2', 'var', 'value'] + + result9 = self.df.melt(id_vars=['id1', 'id2'], value_vars=['A', 'B'], + var_name=self.var_name) + expected9 = DataFrame({'id1': self.df['id1'].tolist() * 2, + 'id2': self.df['id2'].tolist() * 2, + self.var_name: ['A'] * 10 + ['B'] * 10, + 'value': (self.df['A'].tolist() + + self.df['B'].tolist())}, + columns=['id1', 'id2', self.var_name, 'value']) + tm.assert_frame_equal(result9, expected9) + + def test_custom_value_name(self): + result10 = self.df.melt(value_name=self.value_name) + assert result10.columns.tolist() == ['variable', 'val'] + + result11 = self.df.melt(id_vars=['id1'], value_name=self.value_name) + assert result11.columns.tolist() == ['id1', 'variable', 'val'] + + result12 = self.df.melt(id_vars=['id1', 'id2'], + value_name=self.value_name) + assert result12.columns.tolist() == ['id1', 'id2', 'variable', 'val'] + + result13 = self.df.melt(id_vars=['id1', 'id2'], value_vars='A', + value_name=self.value_name) + assert result13.columns.tolist() == ['id1', 'id2', 'variable', 'val'] + + result14 = self.df.melt(id_vars=['id1', 'id2'], value_vars=['A', 'B'], + value_name=self.value_name) + expected14 = DataFrame({'id1': self.df['id1'].tolist() * 2, + 'id2': self.df['id2'].tolist() * 2, + 'variable': ['A'] * 10 + ['B'] * 10, + self.value_name: (self.df['A'].tolist() + + self.df['B'].tolist())}, + columns=['id1', 'id2', 'variable', + self.value_name]) + tm.assert_frame_equal(result14, expected14) + + def test_custom_var_and_value_name(self): + + result15 = self.df.melt(var_name=self.var_name, + value_name=self.value_name) + assert result15.columns.tolist() == ['var', 'val'] + + result16 = self.df.melt(id_vars=['id1'], var_name=self.var_name, + value_name=self.value_name) + assert result16.columns.tolist() == ['id1', 'var', 'val'] + + result17 = self.df.melt(id_vars=['id1', 'id2'], + var_name=self.var_name, + value_name=self.value_name) + assert result17.columns.tolist() == ['id1', 'id2', 'var', 'val'] + + result18 = self.df.melt(id_vars=['id1', 'id2'], value_vars='A', + var_name=self.var_name, + value_name=self.value_name) + assert result18.columns.tolist() == ['id1', 'id2', 'var', 'val'] + + result19 = self.df.melt(id_vars=['id1', 'id2'], value_vars=['A', 'B'], + var_name=self.var_name, + value_name=self.value_name) + expected19 = DataFrame({'id1': self.df['id1'].tolist() * 2, + 'id2': self.df['id2'].tolist() * 2, + self.var_name: ['A'] * 10 + ['B'] * 10, + self.value_name: (self.df['A'].tolist() + + self.df['B'].tolist())}, + columns=['id1', 'id2', self.var_name, + self.value_name]) + tm.assert_frame_equal(result19, expected19) + + df20 = self.df.copy() + df20.columns.name = 'foo' + result20 = df20.melt() + assert result20.columns.tolist() == ['foo', 'value'] + + def test_col_level(self): + res1 = self.df1.melt(col_level=0) + res2 = self.df1.melt(col_level='CAP') + assert res1.columns.tolist() == ['CAP', 'value'] + assert res2.columns.tolist() == ['CAP', 'value'] + + def test_multiindex(self): + res = self.df1.melt() + assert res.columns.tolist() == ['CAP', 'low', 'value'] + + +class TestLreshape(object): + + def test_pairs(self): + data = {'birthdt': ['08jan2009', '20dec2008', '30dec2008', '21dec2008', + '11jan2009'], + 'birthwt': [1766, 3301, 1454, 3139, 4133], + 'id': [101, 102, 103, 104, 105], + 'sex': ['Male', 'Female', 'Female', 'Female', 'Female'], + 'visitdt1': ['11jan2009', '22dec2008', '04jan2009', + '29dec2008', '20jan2009'], + 'visitdt2': + ['21jan2009', nan, '22jan2009', '31dec2008', '03feb2009'], + 'visitdt3': ['05feb2009', nan, nan, '02jan2009', '15feb2009'], + 'wt1': [1823, 3338, 1549, 3298, 4306], + 'wt2': [2011.0, nan, 1892.0, 3338.0, 4575.0], + 'wt3': [2293.0, nan, nan, 3377.0, 4805.0]} + + df = DataFrame(data) + + spec = {'visitdt': ['visitdt%d' % i for i in range(1, 4)], + 'wt': ['wt%d' % i for i in range(1, 4)]} + result = lreshape(df, spec) + + exp_data = {'birthdt': + ['08jan2009', '20dec2008', '30dec2008', '21dec2008', + '11jan2009', '08jan2009', '30dec2008', '21dec2008', + '11jan2009', '08jan2009', '21dec2008', '11jan2009'], + 'birthwt': [1766, 3301, 1454, 3139, 4133, 1766, 1454, 3139, + 4133, 1766, 3139, 4133], + 'id': [101, 102, 103, 104, 105, 101, 103, 104, 105, 101, + 104, 105], + 'sex': ['Male', 'Female', 'Female', 'Female', 'Female', + 'Male', 'Female', 'Female', 'Female', 'Male', + 'Female', 'Female'], + 'visitdt': ['11jan2009', '22dec2008', '04jan2009', + '29dec2008', '20jan2009', '21jan2009', + '22jan2009', '31dec2008', '03feb2009', + '05feb2009', '02jan2009', '15feb2009'], + 'wt': [1823.0, 3338.0, 1549.0, 3298.0, 4306.0, 2011.0, + 1892.0, 3338.0, 4575.0, 2293.0, 3377.0, 4805.0]} + exp = DataFrame(exp_data, columns=result.columns) + tm.assert_frame_equal(result, exp) + + result = lreshape(df, spec, dropna=False) + exp_data = {'birthdt': + ['08jan2009', '20dec2008', '30dec2008', '21dec2008', + '11jan2009', '08jan2009', '20dec2008', '30dec2008', + '21dec2008', '11jan2009', '08jan2009', '20dec2008', + '30dec2008', '21dec2008', '11jan2009'], + 'birthwt': [1766, 3301, 1454, 3139, 4133, 1766, 3301, 1454, + 3139, 4133, 1766, 3301, 1454, 3139, 4133], + 'id': [101, 102, 103, 104, 105, 101, 102, 103, 104, 105, + 101, 102, 103, 104, 105], + 'sex': ['Male', 'Female', 'Female', 'Female', 'Female', + 'Male', 'Female', 'Female', 'Female', 'Female', + 'Male', 'Female', 'Female', 'Female', 'Female'], + 'visitdt': ['11jan2009', '22dec2008', '04jan2009', + '29dec2008', '20jan2009', '21jan2009', nan, + '22jan2009', '31dec2008', '03feb2009', + '05feb2009', nan, nan, '02jan2009', + '15feb2009'], + 'wt': [1823.0, 3338.0, 1549.0, 3298.0, 4306.0, 2011.0, nan, + 1892.0, 3338.0, 4575.0, 2293.0, nan, nan, 3377.0, + 4805.0]} + exp = DataFrame(exp_data, columns=result.columns) + tm.assert_frame_equal(result, exp) + + spec = {'visitdt': ['visitdt%d' % i for i in range(1, 3)], + 'wt': ['wt%d' % i for i in range(1, 4)]} + pytest.raises(ValueError, lreshape, df, spec) + + +class TestWideToLong(object): + + def test_simple(self): + np.random.seed(123) + x = np.random.randn(3) + df = pd.DataFrame({"A1970": {0: "a", + 1: "b", + 2: "c"}, + "A1980": {0: "d", + 1: "e", + 2: "f"}, + "B1970": {0: 2.5, + 1: 1.2, + 2: .7}, + "B1980": {0: 3.2, + 1: 1.3, + 2: .1}, + "X": dict(zip( + range(3), x))}) + df["id"] = df.index + exp_data = {"X": x.tolist() + x.tolist(), + "A": ['a', 'b', 'c', 'd', 'e', 'f'], + "B": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1], + "year": ['1970', '1970', '1970', '1980', '1980', '1980'], + "id": [0, 1, 2, 0, 1, 2]} + exp_frame = DataFrame(exp_data) + exp_frame = exp_frame.set_index(['id', 'year'])[["X", "A", "B"]] + long_frame = wide_to_long(df, ["A", "B"], i="id", j="year") + tm.assert_frame_equal(long_frame, exp_frame) + + def test_stubs(self): + # GH9204 + df = pd.DataFrame([[0, 1, 2, 3, 8], [4, 5, 6, 7, 9]]) + df.columns = ['id', 'inc1', 'inc2', 'edu1', 'edu2'] + stubs = ['inc', 'edu'] + + # TODO: unused? + df_long = pd.wide_to_long(df, stubs, i='id', j='age') # noqa + + assert stubs == ['inc', 'edu'] + + def test_separating_character(self): + # GH14779 + np.random.seed(123) + x = np.random.randn(3) + df = pd.DataFrame({"A.1970": {0: "a", + 1: "b", + 2: "c"}, + "A.1980": {0: "d", + 1: "e", + 2: "f"}, + "B.1970": {0: 2.5, + 1: 1.2, + 2: .7}, + "B.1980": {0: 3.2, + 1: 1.3, + 2: .1}, + "X": dict(zip( + range(3), x))}) + df["id"] = df.index + exp_data = {"X": x.tolist() + x.tolist(), + "A": ['a', 'b', 'c', 'd', 'e', 'f'], + "B": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1], + "year": ['1970', '1970', '1970', '1980', '1980', '1980'], + "id": [0, 1, 2, 0, 1, 2]} + exp_frame = DataFrame(exp_data) + exp_frame = exp_frame.set_index(['id', 'year'])[["X", "A", "B"]] + long_frame = wide_to_long(df, ["A", "B"], i="id", j="year", sep=".") + tm.assert_frame_equal(long_frame, exp_frame) + + def test_escapable_characters(self): + np.random.seed(123) + x = np.random.randn(3) + df = pd.DataFrame({"A(quarterly)1970": {0: "a", + 1: "b", + 2: "c"}, + "A(quarterly)1980": {0: "d", + 1: "e", + 2: "f"}, + "B(quarterly)1970": {0: 2.5, + 1: 1.2, + 2: .7}, + "B(quarterly)1980": {0: 3.2, + 1: 1.3, + 2: .1}, + "X": dict(zip( + range(3), x))}) + df["id"] = df.index + exp_data = {"X": x.tolist() + x.tolist(), + "A(quarterly)": ['a', 'b', 'c', 'd', 'e', 'f'], + "B(quarterly)": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1], + "year": ['1970', '1970', '1970', '1980', '1980', '1980'], + "id": [0, 1, 2, 0, 1, 2]} + exp_frame = DataFrame(exp_data) + exp_frame = exp_frame.set_index( + ['id', 'year'])[["X", "A(quarterly)", "B(quarterly)"]] + long_frame = wide_to_long(df, ["A(quarterly)", "B(quarterly)"], + i="id", j="year") + tm.assert_frame_equal(long_frame, exp_frame) + + def test_unbalanced(self): + # test that we can have a varying amount of time variables + df = pd.DataFrame({'A2010': [1.0, 2.0], + 'A2011': [3.0, 4.0], + 'B2010': [5.0, 6.0], + 'X': ['X1', 'X2']}) + df['id'] = df.index + exp_data = {'X': ['X1', 'X1', 'X2', 'X2'], + 'A': [1.0, 3.0, 2.0, 4.0], + 'B': [5.0, np.nan, 6.0, np.nan], + 'id': [0, 0, 1, 1], + 'year': ['2010', '2011', '2010', '2011']} + exp_frame = pd.DataFrame(exp_data) + exp_frame = exp_frame.set_index(['id', 'year'])[["X", "A", "B"]] + long_frame = wide_to_long(df, ['A', 'B'], i='id', j='year') + tm.assert_frame_equal(long_frame, exp_frame) + + def test_character_overlap(self): + # Test we handle overlapping characters in both id_vars and value_vars + df = pd.DataFrame({ + 'A11': ['a11', 'a22', 'a33'], + 'A12': ['a21', 'a22', 'a23'], + 'B11': ['b11', 'b12', 'b13'], + 'B12': ['b21', 'b22', 'b23'], + 'BB11': [1, 2, 3], + 'BB12': [4, 5, 6], + 'BBBX': [91, 92, 93], + 'BBBZ': [91, 92, 93] + }) + df['id'] = df.index + exp_frame = pd.DataFrame({ + 'BBBX': [91, 92, 93, 91, 92, 93], + 'BBBZ': [91, 92, 93, 91, 92, 93], + 'A': ['a11', 'a22', 'a33', 'a21', 'a22', 'a23'], + 'B': ['b11', 'b12', 'b13', 'b21', 'b22', 'b23'], + 'BB': [1, 2, 3, 4, 5, 6], + 'id': [0, 1, 2, 0, 1, 2], + 'year': ['11', '11', '11', '12', '12', '12']}) + exp_frame = exp_frame.set_index(['id', 'year'])[ + ['BBBX', 'BBBZ', 'A', 'B', 'BB']] + long_frame = wide_to_long(df, ['A', 'B', 'BB'], i='id', j='year') + tm.assert_frame_equal(long_frame.sort_index(axis=1), + exp_frame.sort_index(axis=1)) + + def test_invalid_separator(self): + # if an invalid separator is supplied a empty data frame is returned + sep = 'nope!' + df = pd.DataFrame({'A2010': [1.0, 2.0], + 'A2011': [3.0, 4.0], + 'B2010': [5.0, 6.0], + 'X': ['X1', 'X2']}) + df['id'] = df.index + exp_data = {'X': '', + 'A2010': [], + 'A2011': [], + 'B2010': [], + 'id': [], + 'year': [], + 'A': [], + 'B': []} + exp_frame = pd.DataFrame(exp_data) + exp_frame = exp_frame.set_index(['id', 'year'])[[ + 'X', 'A2010', 'A2011', 'B2010', 'A', 'B']] + exp_frame.index.set_levels([[0, 1], []], inplace=True) + long_frame = wide_to_long(df, ['A', 'B'], i='id', j='year', sep=sep) + tm.assert_frame_equal(long_frame.sort_index(axis=1), + exp_frame.sort_index(axis=1)) + + def test_num_string_disambiguation(self): + # Test that we can disambiguate number value_vars from + # string value_vars + df = pd.DataFrame({ + 'A11': ['a11', 'a22', 'a33'], + 'A12': ['a21', 'a22', 'a23'], + 'B11': ['b11', 'b12', 'b13'], + 'B12': ['b21', 'b22', 'b23'], + 'BB11': [1, 2, 3], + 'BB12': [4, 5, 6], + 'Arating': [91, 92, 93], + 'Arating_old': [91, 92, 93] + }) + df['id'] = df.index + exp_frame = pd.DataFrame({ + 'Arating': [91, 92, 93, 91, 92, 93], + 'Arating_old': [91, 92, 93, 91, 92, 93], + 'A': ['a11', 'a22', 'a33', 'a21', 'a22', 'a23'], + 'B': ['b11', 'b12', 'b13', 'b21', 'b22', 'b23'], + 'BB': [1, 2, 3, 4, 5, 6], + 'id': [0, 1, 2, 0, 1, 2], + 'year': ['11', '11', '11', '12', '12', '12']}) + exp_frame = exp_frame.set_index(['id', 'year'])[ + ['Arating', 'Arating_old', 'A', 'B', 'BB']] + long_frame = wide_to_long(df, ['A', 'B', 'BB'], i='id', j='year') + tm.assert_frame_equal(long_frame.sort_index(axis=1), + exp_frame.sort_index(axis=1)) + + def test_invalid_suffixtype(self): + # If all stubs names end with a string, but a numeric suffix is + # assumed, an empty data frame is returned + df = pd.DataFrame({'Aone': [1.0, 2.0], + 'Atwo': [3.0, 4.0], + 'Bone': [5.0, 6.0], + 'X': ['X1', 'X2']}) + df['id'] = df.index + exp_data = {'X': '', + 'Aone': [], + 'Atwo': [], + 'Bone': [], + 'id': [], + 'year': [], + 'A': [], + 'B': []} + exp_frame = pd.DataFrame(exp_data) + exp_frame = exp_frame.set_index(['id', 'year'])[[ + 'X', 'Aone', 'Atwo', 'Bone', 'A', 'B']] + exp_frame.index.set_levels([[0, 1], []], inplace=True) + long_frame = wide_to_long(df, ['A', 'B'], i='id', j='year') + tm.assert_frame_equal(long_frame.sort_index(axis=1), + exp_frame.sort_index(axis=1)) + + def test_multiple_id_columns(self): + # Taken from http://www.ats.ucla.edu/stat/stata/modules/reshapel.htm + df = pd.DataFrame({ + 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], + 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], + 'ht1': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], + 'ht2': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] + }) + exp_frame = pd.DataFrame({ + 'ht': [2.8, 3.4, 2.9, 3.8, 2.2, 2.9, 2.0, 3.2, 1.8, + 2.8, 1.9, 2.4, 2.2, 3.3, 2.3, 3.4, 2.1, 2.9], + 'famid': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3], + 'birth': [1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3], + 'age': ['1', '2', '1', '2', '1', '2', '1', '2', '1', + '2', '1', '2', '1', '2', '1', '2', '1', '2'] + }) + exp_frame = exp_frame.set_index(['famid', 'birth', 'age'])[['ht']] + long_frame = wide_to_long(df, 'ht', i=['famid', 'birth'], j='age') + tm.assert_frame_equal(long_frame, exp_frame) + + def test_non_unique_idvars(self): + # GH16382 + # Raise an error message if non unique id vars (i) are passed + df = pd.DataFrame({ + 'A_A1': [1, 2, 3, 4, 5], + 'B_B1': [1, 2, 3, 4, 5], + 'x': [1, 1, 1, 1, 1] + }) + with pytest.raises(ValueError): + wide_to_long(df, ['A_A', 'B_B'], i='x', j='colname') diff --git a/pandas/tests/reshape/test_reshape.py b/pandas/tests/reshape/test_reshape.py index 59852ee014b92..3e68ff7cf2f59 100644 --- a/pandas/tests/reshape/test_reshape.py +++ b/pandas/tests/reshape/test_reshape.py @@ -11,208 +11,9 @@ from pandas.util.testing import assert_frame_equal -from pandas import melt, lreshape, wide_to_long, get_dummies +from pandas import get_dummies import pandas.util.testing as tm -from pandas.compat import range, u - - -class TestMelt(object): - - def setup_method(self, method): - self.df = tm.makeTimeDataFrame()[:10] - self.df['id1'] = (self.df['A'] > 0).astype(np.int64) - self.df['id2'] = (self.df['B'] > 0).astype(np.int64) - - self.var_name = 'var' - self.value_name = 'val' - - self.df1 = pd.DataFrame([[1.067683, -1.110463, 0.20867 - ], [-1.321405, 0.368915, -1.055342], - [-0.807333, 0.08298, -0.873361]]) - self.df1.columns = [list('ABC'), list('abc')] - self.df1.columns.names = ['CAP', 'low'] - - def test_top_level_method(self): - result = melt(self.df) - assert result.columns.tolist() == ['variable', 'value'] - - def test_method_signatures(self): - tm.assert_frame_equal(self.df.melt(), - melt(self.df)) - - tm.assert_frame_equal(self.df.melt(id_vars=['id1', 'id2'], - value_vars=['A', 'B']), - melt(self.df, - id_vars=['id1', 'id2'], - value_vars=['A', 'B'])) - - tm.assert_frame_equal(self.df.melt(var_name=self.var_name, - value_name=self.value_name), - melt(self.df, - var_name=self.var_name, - value_name=self.value_name)) - - tm.assert_frame_equal(self.df1.melt(col_level=0), - melt(self.df1, col_level=0)) - - def test_default_col_names(self): - result = self.df.melt() - assert result.columns.tolist() == ['variable', 'value'] - - result1 = self.df.melt(id_vars=['id1']) - assert result1.columns.tolist() == ['id1', 'variable', 'value'] - - result2 = self.df.melt(id_vars=['id1', 'id2']) - assert result2.columns.tolist() == ['id1', 'id2', 'variable', 'value'] - - def test_value_vars(self): - result3 = self.df.melt(id_vars=['id1', 'id2'], value_vars='A') - assert len(result3) == 10 - - result4 = self.df.melt(id_vars=['id1', 'id2'], value_vars=['A', 'B']) - expected4 = DataFrame({'id1': self.df['id1'].tolist() * 2, - 'id2': self.df['id2'].tolist() * 2, - 'variable': ['A'] * 10 + ['B'] * 10, - 'value': (self.df['A'].tolist() + - self.df['B'].tolist())}, - columns=['id1', 'id2', 'variable', 'value']) - tm.assert_frame_equal(result4, expected4) - - def test_value_vars_types(self): - # GH 15348 - expected = DataFrame({'id1': self.df['id1'].tolist() * 2, - 'id2': self.df['id2'].tolist() * 2, - 'variable': ['A'] * 10 + ['B'] * 10, - 'value': (self.df['A'].tolist() + - self.df['B'].tolist())}, - columns=['id1', 'id2', 'variable', 'value']) - - for type_ in (tuple, list, np.array): - result = self.df.melt(id_vars=['id1', 'id2'], - value_vars=type_(('A', 'B'))) - tm.assert_frame_equal(result, expected) - - def test_vars_work_with_multiindex(self): - expected = DataFrame({ - ('A', 'a'): self.df1[('A', 'a')], - 'CAP': ['B'] * len(self.df1), - 'low': ['b'] * len(self.df1), - 'value': self.df1[('B', 'b')], - }, columns=[('A', 'a'), 'CAP', 'low', 'value']) - - result = self.df1.melt(id_vars=[('A', 'a')], value_vars=[('B', 'b')]) - tm.assert_frame_equal(result, expected) - - def test_tuple_vars_fail_with_multiindex(self): - # melt should fail with an informative error message if - # the columns have a MultiIndex and a tuple is passed - # for id_vars or value_vars. - tuple_a = ('A', 'a') - list_a = [tuple_a] - tuple_b = ('B', 'b') - list_b = [tuple_b] - - for id_vars, value_vars in ((tuple_a, list_b), (list_a, tuple_b), - (tuple_a, tuple_b)): - with tm.assert_raises_regex(ValueError, r'MultiIndex'): - self.df1.melt(id_vars=id_vars, value_vars=value_vars) - - def test_custom_var_name(self): - result5 = self.df.melt(var_name=self.var_name) - assert result5.columns.tolist() == ['var', 'value'] - - result6 = self.df.melt(id_vars=['id1'], var_name=self.var_name) - assert result6.columns.tolist() == ['id1', 'var', 'value'] - - result7 = self.df.melt(id_vars=['id1', 'id2'], var_name=self.var_name) - assert result7.columns.tolist() == ['id1', 'id2', 'var', 'value'] - - result8 = self.df.melt(id_vars=['id1', 'id2'], value_vars='A', - var_name=self.var_name) - assert result8.columns.tolist() == ['id1', 'id2', 'var', 'value'] - - result9 = self.df.melt(id_vars=['id1', 'id2'], value_vars=['A', 'B'], - var_name=self.var_name) - expected9 = DataFrame({'id1': self.df['id1'].tolist() * 2, - 'id2': self.df['id2'].tolist() * 2, - self.var_name: ['A'] * 10 + ['B'] * 10, - 'value': (self.df['A'].tolist() + - self.df['B'].tolist())}, - columns=['id1', 'id2', self.var_name, 'value']) - tm.assert_frame_equal(result9, expected9) - - def test_custom_value_name(self): - result10 = self.df.melt(value_name=self.value_name) - assert result10.columns.tolist() == ['variable', 'val'] - - result11 = self.df.melt(id_vars=['id1'], value_name=self.value_name) - assert result11.columns.tolist() == ['id1', 'variable', 'val'] - - result12 = self.df.melt(id_vars=['id1', 'id2'], - value_name=self.value_name) - assert result12.columns.tolist() == ['id1', 'id2', 'variable', 'val'] - - result13 = self.df.melt(id_vars=['id1', 'id2'], value_vars='A', - value_name=self.value_name) - assert result13.columns.tolist() == ['id1', 'id2', 'variable', 'val'] - - result14 = self.df.melt(id_vars=['id1', 'id2'], value_vars=['A', 'B'], - value_name=self.value_name) - expected14 = DataFrame({'id1': self.df['id1'].tolist() * 2, - 'id2': self.df['id2'].tolist() * 2, - 'variable': ['A'] * 10 + ['B'] * 10, - self.value_name: (self.df['A'].tolist() + - self.df['B'].tolist())}, - columns=['id1', 'id2', 'variable', - self.value_name]) - tm.assert_frame_equal(result14, expected14) - - def test_custom_var_and_value_name(self): - - result15 = self.df.melt(var_name=self.var_name, - value_name=self.value_name) - assert result15.columns.tolist() == ['var', 'val'] - - result16 = self.df.melt(id_vars=['id1'], var_name=self.var_name, - value_name=self.value_name) - assert result16.columns.tolist() == ['id1', 'var', 'val'] - - result17 = self.df.melt(id_vars=['id1', 'id2'], - var_name=self.var_name, - value_name=self.value_name) - assert result17.columns.tolist() == ['id1', 'id2', 'var', 'val'] - - result18 = self.df.melt(id_vars=['id1', 'id2'], value_vars='A', - var_name=self.var_name, - value_name=self.value_name) - assert result18.columns.tolist() == ['id1', 'id2', 'var', 'val'] - - result19 = self.df.melt(id_vars=['id1', 'id2'], value_vars=['A', 'B'], - var_name=self.var_name, - value_name=self.value_name) - expected19 = DataFrame({'id1': self.df['id1'].tolist() * 2, - 'id2': self.df['id2'].tolist() * 2, - self.var_name: ['A'] * 10 + ['B'] * 10, - self.value_name: (self.df['A'].tolist() + - self.df['B'].tolist())}, - columns=['id1', 'id2', self.var_name, - self.value_name]) - tm.assert_frame_equal(result19, expected19) - - df20 = self.df.copy() - df20.columns.name = 'foo' - result20 = df20.melt() - assert result20.columns.tolist() == ['foo', 'value'] - - def test_col_level(self): - res1 = self.df1.melt(col_level=0) - res2 = self.df1.melt(col_level='CAP') - assert res1.columns.tolist() == ['CAP', 'value'] - assert res2.columns.tolist() == ['CAP', 'value'] - - def test_multiindex(self): - res = self.df1.melt() - assert res.columns.tolist() == ['CAP', 'low', 'value'] +from pandas.compat import u class TestGetDummies(object): @@ -672,327 +473,3 @@ def test_preserve_categorical_dtype(self): result = make_axis_dummies(df, transform=lambda x: x) tm.assert_frame_equal(result, expected) - - -class TestLreshape(object): - - def test_pairs(self): - data = {'birthdt': ['08jan2009', '20dec2008', '30dec2008', '21dec2008', - '11jan2009'], - 'birthwt': [1766, 3301, 1454, 3139, 4133], - 'id': [101, 102, 103, 104, 105], - 'sex': ['Male', 'Female', 'Female', 'Female', 'Female'], - 'visitdt1': ['11jan2009', '22dec2008', '04jan2009', - '29dec2008', '20jan2009'], - 'visitdt2': - ['21jan2009', nan, '22jan2009', '31dec2008', '03feb2009'], - 'visitdt3': ['05feb2009', nan, nan, '02jan2009', '15feb2009'], - 'wt1': [1823, 3338, 1549, 3298, 4306], - 'wt2': [2011.0, nan, 1892.0, 3338.0, 4575.0], - 'wt3': [2293.0, nan, nan, 3377.0, 4805.0]} - - df = DataFrame(data) - - spec = {'visitdt': ['visitdt%d' % i for i in range(1, 4)], - 'wt': ['wt%d' % i for i in range(1, 4)]} - result = lreshape(df, spec) - - exp_data = {'birthdt': - ['08jan2009', '20dec2008', '30dec2008', '21dec2008', - '11jan2009', '08jan2009', '30dec2008', '21dec2008', - '11jan2009', '08jan2009', '21dec2008', '11jan2009'], - 'birthwt': [1766, 3301, 1454, 3139, 4133, 1766, 1454, 3139, - 4133, 1766, 3139, 4133], - 'id': [101, 102, 103, 104, 105, 101, 103, 104, 105, 101, - 104, 105], - 'sex': ['Male', 'Female', 'Female', 'Female', 'Female', - 'Male', 'Female', 'Female', 'Female', 'Male', - 'Female', 'Female'], - 'visitdt': ['11jan2009', '22dec2008', '04jan2009', - '29dec2008', '20jan2009', '21jan2009', - '22jan2009', '31dec2008', '03feb2009', - '05feb2009', '02jan2009', '15feb2009'], - 'wt': [1823.0, 3338.0, 1549.0, 3298.0, 4306.0, 2011.0, - 1892.0, 3338.0, 4575.0, 2293.0, 3377.0, 4805.0]} - exp = DataFrame(exp_data, columns=result.columns) - tm.assert_frame_equal(result, exp) - - result = lreshape(df, spec, dropna=False) - exp_data = {'birthdt': - ['08jan2009', '20dec2008', '30dec2008', '21dec2008', - '11jan2009', '08jan2009', '20dec2008', '30dec2008', - '21dec2008', '11jan2009', '08jan2009', '20dec2008', - '30dec2008', '21dec2008', '11jan2009'], - 'birthwt': [1766, 3301, 1454, 3139, 4133, 1766, 3301, 1454, - 3139, 4133, 1766, 3301, 1454, 3139, 4133], - 'id': [101, 102, 103, 104, 105, 101, 102, 103, 104, 105, - 101, 102, 103, 104, 105], - 'sex': ['Male', 'Female', 'Female', 'Female', 'Female', - 'Male', 'Female', 'Female', 'Female', 'Female', - 'Male', 'Female', 'Female', 'Female', 'Female'], - 'visitdt': ['11jan2009', '22dec2008', '04jan2009', - '29dec2008', '20jan2009', '21jan2009', nan, - '22jan2009', '31dec2008', '03feb2009', - '05feb2009', nan, nan, '02jan2009', - '15feb2009'], - 'wt': [1823.0, 3338.0, 1549.0, 3298.0, 4306.0, 2011.0, nan, - 1892.0, 3338.0, 4575.0, 2293.0, nan, nan, 3377.0, - 4805.0]} - exp = DataFrame(exp_data, columns=result.columns) - tm.assert_frame_equal(result, exp) - - spec = {'visitdt': ['visitdt%d' % i for i in range(1, 3)], - 'wt': ['wt%d' % i for i in range(1, 4)]} - pytest.raises(ValueError, lreshape, df, spec) - - -class TestWideToLong(object): - - def test_simple(self): - np.random.seed(123) - x = np.random.randn(3) - df = pd.DataFrame({"A1970": {0: "a", - 1: "b", - 2: "c"}, - "A1980": {0: "d", - 1: "e", - 2: "f"}, - "B1970": {0: 2.5, - 1: 1.2, - 2: .7}, - "B1980": {0: 3.2, - 1: 1.3, - 2: .1}, - "X": dict(zip( - range(3), x))}) - df["id"] = df.index - exp_data = {"X": x.tolist() + x.tolist(), - "A": ['a', 'b', 'c', 'd', 'e', 'f'], - "B": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1], - "year": ['1970', '1970', '1970', '1980', '1980', '1980'], - "id": [0, 1, 2, 0, 1, 2]} - exp_frame = DataFrame(exp_data) - exp_frame = exp_frame.set_index(['id', 'year'])[["X", "A", "B"]] - long_frame = wide_to_long(df, ["A", "B"], i="id", j="year") - tm.assert_frame_equal(long_frame, exp_frame) - - def test_stubs(self): - # GH9204 - df = pd.DataFrame([[0, 1, 2, 3, 8], [4, 5, 6, 7, 9]]) - df.columns = ['id', 'inc1', 'inc2', 'edu1', 'edu2'] - stubs = ['inc', 'edu'] - - # TODO: unused? - df_long = pd.wide_to_long(df, stubs, i='id', j='age') # noqa - - assert stubs == ['inc', 'edu'] - - def test_separating_character(self): - # GH14779 - np.random.seed(123) - x = np.random.randn(3) - df = pd.DataFrame({"A.1970": {0: "a", - 1: "b", - 2: "c"}, - "A.1980": {0: "d", - 1: "e", - 2: "f"}, - "B.1970": {0: 2.5, - 1: 1.2, - 2: .7}, - "B.1980": {0: 3.2, - 1: 1.3, - 2: .1}, - "X": dict(zip( - range(3), x))}) - df["id"] = df.index - exp_data = {"X": x.tolist() + x.tolist(), - "A": ['a', 'b', 'c', 'd', 'e', 'f'], - "B": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1], - "year": ['1970', '1970', '1970', '1980', '1980', '1980'], - "id": [0, 1, 2, 0, 1, 2]} - exp_frame = DataFrame(exp_data) - exp_frame = exp_frame.set_index(['id', 'year'])[["X", "A", "B"]] - long_frame = wide_to_long(df, ["A", "B"], i="id", j="year", sep=".") - tm.assert_frame_equal(long_frame, exp_frame) - - def test_escapable_characters(self): - np.random.seed(123) - x = np.random.randn(3) - df = pd.DataFrame({"A(quarterly)1970": {0: "a", - 1: "b", - 2: "c"}, - "A(quarterly)1980": {0: "d", - 1: "e", - 2: "f"}, - "B(quarterly)1970": {0: 2.5, - 1: 1.2, - 2: .7}, - "B(quarterly)1980": {0: 3.2, - 1: 1.3, - 2: .1}, - "X": dict(zip( - range(3), x))}) - df["id"] = df.index - exp_data = {"X": x.tolist() + x.tolist(), - "A(quarterly)": ['a', 'b', 'c', 'd', 'e', 'f'], - "B(quarterly)": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1], - "year": ['1970', '1970', '1970', '1980', '1980', '1980'], - "id": [0, 1, 2, 0, 1, 2]} - exp_frame = DataFrame(exp_data) - exp_frame = exp_frame.set_index( - ['id', 'year'])[["X", "A(quarterly)", "B(quarterly)"]] - long_frame = wide_to_long(df, ["A(quarterly)", "B(quarterly)"], - i="id", j="year") - tm.assert_frame_equal(long_frame, exp_frame) - - def test_unbalanced(self): - # test that we can have a varying amount of time variables - df = pd.DataFrame({'A2010': [1.0, 2.0], - 'A2011': [3.0, 4.0], - 'B2010': [5.0, 6.0], - 'X': ['X1', 'X2']}) - df['id'] = df.index - exp_data = {'X': ['X1', 'X1', 'X2', 'X2'], - 'A': [1.0, 3.0, 2.0, 4.0], - 'B': [5.0, np.nan, 6.0, np.nan], - 'id': [0, 0, 1, 1], - 'year': ['2010', '2011', '2010', '2011']} - exp_frame = pd.DataFrame(exp_data) - exp_frame = exp_frame.set_index(['id', 'year'])[["X", "A", "B"]] - long_frame = wide_to_long(df, ['A', 'B'], i='id', j='year') - tm.assert_frame_equal(long_frame, exp_frame) - - def test_character_overlap(self): - # Test we handle overlapping characters in both id_vars and value_vars - df = pd.DataFrame({ - 'A11': ['a11', 'a22', 'a33'], - 'A12': ['a21', 'a22', 'a23'], - 'B11': ['b11', 'b12', 'b13'], - 'B12': ['b21', 'b22', 'b23'], - 'BB11': [1, 2, 3], - 'BB12': [4, 5, 6], - 'BBBX': [91, 92, 93], - 'BBBZ': [91, 92, 93] - }) - df['id'] = df.index - exp_frame = pd.DataFrame({ - 'BBBX': [91, 92, 93, 91, 92, 93], - 'BBBZ': [91, 92, 93, 91, 92, 93], - 'A': ['a11', 'a22', 'a33', 'a21', 'a22', 'a23'], - 'B': ['b11', 'b12', 'b13', 'b21', 'b22', 'b23'], - 'BB': [1, 2, 3, 4, 5, 6], - 'id': [0, 1, 2, 0, 1, 2], - 'year': ['11', '11', '11', '12', '12', '12']}) - exp_frame = exp_frame.set_index(['id', 'year'])[ - ['BBBX', 'BBBZ', 'A', 'B', 'BB']] - long_frame = wide_to_long(df, ['A', 'B', 'BB'], i='id', j='year') - tm.assert_frame_equal(long_frame.sort_index(axis=1), - exp_frame.sort_index(axis=1)) - - def test_invalid_separator(self): - # if an invalid separator is supplied a empty data frame is returned - sep = 'nope!' - df = pd.DataFrame({'A2010': [1.0, 2.0], - 'A2011': [3.0, 4.0], - 'B2010': [5.0, 6.0], - 'X': ['X1', 'X2']}) - df['id'] = df.index - exp_data = {'X': '', - 'A2010': [], - 'A2011': [], - 'B2010': [], - 'id': [], - 'year': [], - 'A': [], - 'B': []} - exp_frame = pd.DataFrame(exp_data) - exp_frame = exp_frame.set_index(['id', 'year'])[[ - 'X', 'A2010', 'A2011', 'B2010', 'A', 'B']] - exp_frame.index.set_levels([[0, 1], []], inplace=True) - long_frame = wide_to_long(df, ['A', 'B'], i='id', j='year', sep=sep) - tm.assert_frame_equal(long_frame.sort_index(axis=1), - exp_frame.sort_index(axis=1)) - - def test_num_string_disambiguation(self): - # Test that we can disambiguate number value_vars from - # string value_vars - df = pd.DataFrame({ - 'A11': ['a11', 'a22', 'a33'], - 'A12': ['a21', 'a22', 'a23'], - 'B11': ['b11', 'b12', 'b13'], - 'B12': ['b21', 'b22', 'b23'], - 'BB11': [1, 2, 3], - 'BB12': [4, 5, 6], - 'Arating': [91, 92, 93], - 'Arating_old': [91, 92, 93] - }) - df['id'] = df.index - exp_frame = pd.DataFrame({ - 'Arating': [91, 92, 93, 91, 92, 93], - 'Arating_old': [91, 92, 93, 91, 92, 93], - 'A': ['a11', 'a22', 'a33', 'a21', 'a22', 'a23'], - 'B': ['b11', 'b12', 'b13', 'b21', 'b22', 'b23'], - 'BB': [1, 2, 3, 4, 5, 6], - 'id': [0, 1, 2, 0, 1, 2], - 'year': ['11', '11', '11', '12', '12', '12']}) - exp_frame = exp_frame.set_index(['id', 'year'])[ - ['Arating', 'Arating_old', 'A', 'B', 'BB']] - long_frame = wide_to_long(df, ['A', 'B', 'BB'], i='id', j='year') - tm.assert_frame_equal(long_frame.sort_index(axis=1), - exp_frame.sort_index(axis=1)) - - def test_invalid_suffixtype(self): - # If all stubs names end with a string, but a numeric suffix is - # assumed, an empty data frame is returned - df = pd.DataFrame({'Aone': [1.0, 2.0], - 'Atwo': [3.0, 4.0], - 'Bone': [5.0, 6.0], - 'X': ['X1', 'X2']}) - df['id'] = df.index - exp_data = {'X': '', - 'Aone': [], - 'Atwo': [], - 'Bone': [], - 'id': [], - 'year': [], - 'A': [], - 'B': []} - exp_frame = pd.DataFrame(exp_data) - exp_frame = exp_frame.set_index(['id', 'year'])[[ - 'X', 'Aone', 'Atwo', 'Bone', 'A', 'B']] - exp_frame.index.set_levels([[0, 1], []], inplace=True) - long_frame = wide_to_long(df, ['A', 'B'], i='id', j='year') - tm.assert_frame_equal(long_frame.sort_index(axis=1), - exp_frame.sort_index(axis=1)) - - def test_multiple_id_columns(self): - # Taken from http://www.ats.ucla.edu/stat/stata/modules/reshapel.htm - df = pd.DataFrame({ - 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], - 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], - 'ht1': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], - 'ht2': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] - }) - exp_frame = pd.DataFrame({ - 'ht': [2.8, 3.4, 2.9, 3.8, 2.2, 2.9, 2.0, 3.2, 1.8, - 2.8, 1.9, 2.4, 2.2, 3.3, 2.3, 3.4, 2.1, 2.9], - 'famid': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3], - 'birth': [1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3], - 'age': ['1', '2', '1', '2', '1', '2', '1', '2', '1', - '2', '1', '2', '1', '2', '1', '2', '1', '2'] - }) - exp_frame = exp_frame.set_index(['famid', 'birth', 'age'])[['ht']] - long_frame = wide_to_long(df, 'ht', i=['famid', 'birth'], j='age') - tm.assert_frame_equal(long_frame, exp_frame) - - def test_non_unique_idvars(self): - # GH16382 - # Raise an error message if non unique id vars (i) are passed - df = pd.DataFrame({ - 'A_A1': [1, 2, 3, 4, 5], - 'B_B1': [1, 2, 3, 4, 5], - 'x': [1, 1, 1, 1, 1] - }) - with pytest.raises(ValueError): - wide_to_long(df, ['A_A', 'B_B'], i='x', j='colname')
- [x] closes #18367 This breaks out melt, lreshape, and wide_to_long tests into their own module.
https://api.github.com/repos/pandas-dev/pandas/pulls/18428
2017-11-22T16:08:28Z
2017-11-23T23:34:43Z
2017-11-23T23:34:43Z
2017-11-24T18:03:48Z
TST: Skipif decorator for matplotlib #18190
diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 0160371dc413d..4b0ca872da326 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -7,6 +7,7 @@ import pandas as pd from pandas import DataFrame import pandas.util.testing as tm +import pandas.util._test_decorators as td jinja2 = pytest.importorskip('jinja2') from pandas.io.formats.style import Styler, _get_level_lengths # noqa @@ -1011,8 +1012,8 @@ def test_hide_columns_mult_levels(self): class TestStylerMatplotlibDep(object): + @td.skip_if_no_mpl def test_background_gradient(self): - tm._skip_if_no_mpl() df = pd.DataFrame([[1, 2], [2, 4]], columns=['A', 'B']) for c_map in [None, 'YlOrRd']: diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index dfab539e9474c..2e62b22b2b69e 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -12,6 +12,7 @@ import pandas.util.testing as tm from pandas.util.testing import (ensure_clean, assert_is_valid_plot_return_object) +import pandas.util._test_decorators as td import numpy as np from numpy import random @@ -23,8 +24,6 @@ This is a common base class used for various plotting tests """ -tm._skip_if_no_mpl() - def _skip_if_no_scipy_gaussian_kde(): try: @@ -43,6 +42,7 @@ def _ok_for_gaussian_kde(kind): return plotting._compat._mpl_ge_1_5_0() +@td.skip_if_no_mpl class TestPlotBase(object): def setup_method(self, method): diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 4b1cb2ccbd3dd..1bc49e9e5f96a 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -8,6 +8,7 @@ from pandas import Series, DataFrame, MultiIndex from pandas.compat import range, lzip import pandas.util.testing as tm +import pandas.util._test_decorators as td import numpy as np from numpy import random @@ -19,8 +20,6 @@ """ Test cases for .boxplot method """ -tm._skip_if_no_mpl() - def _skip_if_mpl_14_or_dev_boxplot(): # GH 8382 @@ -31,6 +30,7 @@ def _skip_if_mpl_14_or_dev_boxplot(): pytest.skip("Matplotlib Regression in 1.4 and current dev.") +@td.skip_if_no_mpl class TestDataFramePlots(TestPlotBase): @pytest.mark.slow @@ -174,6 +174,7 @@ def test_fontsize(self): xlabelsize=16, ylabelsize=16) +@td.skip_if_no_mpl class TestDataFrameGroupByPlots(TestPlotBase): @pytest.mark.slow diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index d66012e2a56a0..f1a478581e730 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -16,13 +16,13 @@ from pandas.util.testing import assert_series_equal, ensure_clean import pandas.util.testing as tm +import pandas.util._test_decorators as td from pandas.tests.plotting.common import (TestPlotBase, _skip_if_no_scipy_gaussian_kde) -tm._skip_if_no_mpl() - +@td.skip_if_no_mpl class TestTSPlot(TestPlotBase): def setup_method(self, method): diff --git a/pandas/tests/plotting/test_deprecated.py b/pandas/tests/plotting/test_deprecated.py index 970de6ff881ab..d2f8e13a2444b 100644 --- a/pandas/tests/plotting/test_deprecated.py +++ b/pandas/tests/plotting/test_deprecated.py @@ -4,6 +4,7 @@ import pandas as pd import pandas.util.testing as tm +import pandas.util._test_decorators as td import pytest from numpy.random import randn @@ -18,9 +19,8 @@ pandas.tools.plotting """ -tm._skip_if_no_mpl() - +@td.skip_if_no_mpl class TestDeprecatedNameSpace(TestPlotBase): @pytest.mark.slow diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 3887271edb2a3..5c72d778a1220 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -15,6 +15,7 @@ from pandas.compat import range, lrange, lmap, lzip, u, zip, PY3 from pandas.io.formats.printing import pprint_thing import pandas.util.testing as tm +import pandas.util._test_decorators as td import numpy as np from numpy.random import rand, randn @@ -24,9 +25,8 @@ _skip_if_no_scipy_gaussian_kde, _ok_for_gaussian_kde) -tm._skip_if_no_mpl() - +@td.skip_if_no_mpl class TestDataFramePlots(TestPlotBase): def setup_method(self, method): diff --git a/pandas/tests/plotting/test_groupby.py b/pandas/tests/plotting/test_groupby.py index de48b58133e9a..a7c99a06c34e9 100644 --- a/pandas/tests/plotting/test_groupby.py +++ b/pandas/tests/plotting/test_groupby.py @@ -5,14 +5,14 @@ from pandas import Series, DataFrame import pandas.util.testing as tm +import pandas.util._test_decorators as td import numpy as np from pandas.tests.plotting.common import TestPlotBase -tm._skip_if_no_mpl() - +@td.skip_if_no_mpl class TestDataFrameGroupByPlots(TestPlotBase): def test_series_groupby_plotting_nominally_works(self): diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index 5f7b2dd2d6ca9..864d39eba29c5 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -6,6 +6,7 @@ from pandas import Series, DataFrame import pandas.util.testing as tm +import pandas.util._test_decorators as td import numpy as np from numpy.random import randn @@ -14,9 +15,7 @@ from pandas.tests.plotting.common import (TestPlotBase, _check_plot_works) -tm._skip_if_no_mpl() - - +@td.skip_if_no_mpl class TestSeriesPlots(TestPlotBase): def setup_method(self, method): @@ -141,6 +140,7 @@ def test_plot_fails_when_ax_differs_from_figure(self): self.ts.hist(ax=ax1, figure=fig2) +@td.skip_if_no_mpl class TestDataFramePlots(TestPlotBase): @pytest.mark.slow @@ -251,6 +251,7 @@ def test_tight_layout(self): tm.close() +@td.skip_if_no_mpl class TestDataFrameGroupByPlots(TestPlotBase): @pytest.mark.slow diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 6f476553091d9..8b0a981760c72 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -7,6 +7,7 @@ from pandas import DataFrame from pandas.compat import lmap import pandas.util.testing as tm +import pandas.util._test_decorators as td import numpy as np from numpy import random @@ -15,9 +16,8 @@ import pandas.plotting as plotting from pandas.tests.plotting.common import TestPlotBase, _check_plot_works -tm._skip_if_no_mpl() - +@td.skip_if_no_mpl class TestSeriesPlots(TestPlotBase): def setup_method(self, method): @@ -49,6 +49,7 @@ def test_bootstrap_plot(self): _check_plot_works(bootstrap_plot, series=self.ts, size=10) +@td.skip_if_no_mpl class TestDataFramePlots(TestPlotBase): def test_scatter_matrix_axis(self): diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index fdfd87d1e898c..6dd7e1e9882b2 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -12,6 +12,7 @@ from pandas import Series, DataFrame, date_range from pandas.compat import range, lrange import pandas.util.testing as tm +import pandas.util._test_decorators as td import numpy as np from numpy.random import randn @@ -21,9 +22,8 @@ _skip_if_no_scipy_gaussian_kde, _ok_for_gaussian_kde) -tm._skip_if_no_mpl() - +@td.skip_if_no_mpl class TestSeriesPlots(TestPlotBase): def setup_method(self, method): diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index bf1cac3112c46..b0154f6db7022 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -13,6 +13,7 @@ import pandas as pd import pandas.tseries.offsets as offsets import pandas.util.testing as tm +import pandas.util._test_decorators as td from pandas import (Series, DataFrame, Panel, Index, isna, notna, Timestamp) @@ -234,9 +235,8 @@ def test_groupby_resample_on_api(self): result = df.groupby('key').resample('D', on='dates').mean() assert_frame_equal(result, expected) + @td.skip_if_no_mpl def test_plot_api(self): - tm._skip_if_no_mpl() - # .resample(....).plot(...) # hitting warnings # GH 12448 diff --git a/pandas/tests/util/test_util.py b/pandas/tests/util/test_util.py index 659ce36de6bab..be4e60c6493c8 100644 --- a/pandas/tests/util/test_util.py +++ b/pandas/tests/util/test_util.py @@ -16,6 +16,7 @@ validate_bool_kwarg) import pandas.util.testing as tm +from pandas.util._test_decorators import safe_import class TestDecorators(object): @@ -482,3 +483,20 @@ def test_make_signature(): assert sig == (['old_arg_name', 'new_arg_name', 'mapping=None', 'stacklevel=2'], ['old_arg_name', 'new_arg_name', 'mapping', 'stacklevel']) + + +def test_safe_import(monkeypatch): + assert not safe_import("foo") + assert not safe_import("pandas", min_version="99.99.99") + + # Create dummy module to be imported + import types + import sys + mod_name = "hello123" + mod = types.ModuleType(mod_name) + mod.__version__ = "1.5" + + assert not safe_import(mod_name) + monkeypatch.setitem(sys.modules, mod_name, mod) + assert not safe_import(mod_name, min_version="2.0") + assert safe_import(mod_name, min_version="1.0") diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py new file mode 100644 index 0000000000000..b592a73e5d758 --- /dev/null +++ b/pandas/util/_test_decorators.py @@ -0,0 +1,71 @@ +""" +This module provides decorator functions which can be applied to test objects +in order to skip those objects when certain conditions occur. A sample use case +is to detect if the platform is missing ``matplotlib``. If so, any test objects +which require ``matplotlib`` and decorated with ``@td.skip_if_no_mpl`` will be +skipped by ``pytest`` during the execution of the test suite. + +To illustrate, after importing this module: + +import pandas.util._test_decorators as td + +The decorators can be applied to classes: + +@td.skip_if_some_reason +class Foo(): + ... + +Or individual functions: + +@td.skip_if_some_reason +def test_foo(): + ... + +For more information, refer to the ``pytest`` documentation on ``skipif``. +""" + +import pytest + + +def safe_import(mod_name, min_version=None): + """ + Parameters: + ----------- + mod_name : str + Name of the module to be imported + min_version : str, default None + Minimum required version of the specified mod_name + + Returns: + -------- + object + The imported module if successful, or False + """ + try: + mod = __import__(mod_name) + except ImportError: + return False + + if not min_version: + return mod + else: + import sys + version = getattr(sys.modules[mod_name], '__version__') + if version: + from distutils.version import LooseVersion + if LooseVersion(version) >= LooseVersion(min_version): + return mod + + return False + + +def _skip_if_no_mpl(): + mod = safe_import("matplotlib") + if mod: + mod.use("Agg", warn=False) + else: + return True + + +skip_if_no_mpl = pytest.mark.skipif(_skip_if_no_mpl(), + reason="Missing matplotlib dependency") diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 0da59ba5f958e..ff6fa8ae717d3 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -325,13 +325,6 @@ def _skip_if_32bit(): pytest.skip("skipping for 32 bit") -def _skip_if_no_mpl(): - import pytest - - mpl = pytest.importorskip("matplotlib") - mpl.use("Agg", warn=False) - - def _skip_if_mpl_1_5(): import matplotlib as mpl
- [X] progress towards #18190 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` The behavior here is slightly different than before when the function was used at the module level. Previously, an entire module being skipped would count as one skip entry. Now with the decorator, each test case within the module gets counted as a skip.
https://api.github.com/repos/pandas-dev/pandas/pulls/18427
2017-11-22T14:33:02Z
2017-11-27T18:17:16Z
2017-11-27T18:17:16Z
2017-11-27T18:18:37Z