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
DOC: Add `Series` type to `to_sql` docstring
diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 437e279e90979..a582d32741ae9 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -404,7 +404,7 @@ def to_sql(frame, name, con, schema=None, if_exists='fail', index=True, Parameters ---------- - frame : DataFrame + frame : DataFrame, Series name : string Name of SQL table. con : SQLAlchemy connectable(engine/connection) or database string URI
https://api.github.com/repos/pandas-dev/pandas/pulls/20004
2018-03-05T21:57:28Z
2018-03-07T14:33:10Z
2018-03-07T14:33:10Z
2018-03-11T16:03:23Z
API & BUG: allow list-like y argument to df.plot & fix integer arg to x,y
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index acbfa2eb3ccac..3cef716069ba2 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -986,6 +986,7 @@ Plotting ^^^^^^^^ - :func:`DataFrame.plot` now raises a ``ValueError`` when the ``x`` or ``y`` argument is improperly formed (:issue:`18671`) +- Bug in :func:`DataFrame.plot` when ``x`` and ``y`` arguments given as positions caused incorrect referenced columns for line, bar and area plots (:issue:`20056`) - Bug in formatting tick labels with ``datetime.time()`` and fractional seconds (:issue:`18478`). - :meth:`Series.plot.kde` has exposed the args ``ind`` and ``bw_method`` in the docstring (:issue:`18461`). The argument ``ind`` may now also be an integer (number of sample points). @@ -1041,3 +1042,4 @@ Other - Improved error message when attempting to use a Python keyword as an identifier in a ``numexpr`` backed query (:issue:`18221`) - Bug in accessing a :func:`pandas.get_option`, which raised ``KeyError`` rather than ``OptionError`` when looking up a non-existant option key in some cases (:issue:`19789`) +- :func:`DataFrame.plot` now supports multiple columns to the ``y`` argument (:issue:`19699`) diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index da7c58428fb54..21b69522523cc 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -1751,22 +1751,22 @@ def _plot(data, x=None, y=None, subplots=False, plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds) else: if isinstance(data, ABCDataFrame): + data_cols = data.columns if x is not None: if is_integer(x) and not data.columns.holds_integer(): - x = data.columns[x] + x = data_cols[x] elif not isinstance(data[x], ABCSeries): raise ValueError("x must be a label or position") data = data.set_index(x) if y is not None: - if is_integer(y) and not data.columns.holds_integer(): - y = data.columns[y] - elif not isinstance(data[y], ABCSeries): - raise ValueError("y must be a label or position") - label = kwds['label'] if 'label' in kwds else y - series = data[y].copy() # Don't modify - series.name = label + # check if we have y as int or list of ints + int_ylist = is_list_like(y) and all(is_integer(c) for c in y) + int_y_arg = is_integer(y) or int_ylist + if int_y_arg and not data.columns.holds_integer(): + y = data_cols[y] + label_kw = kwds['label'] if 'label' in kwds else False for kw in ['xerr', 'yerr']: if (kw in kwds) and \ (isinstance(kwds[kw], string_types) or @@ -1775,7 +1775,22 @@ def _plot(data, x=None, y=None, subplots=False, kwds[kw] = data[kwds[kw]] except (IndexError, KeyError, TypeError): pass - data = series + + # don't overwrite + data = data[y].copy() + + if isinstance(data, ABCSeries): + label_name = label_kw or y + data.name = label_name + else: + match = is_list_like(label_kw) and len(label_kw) == len(y) + if label_kw and not match: + raise ValueError( + "label should be list-like and same length as y" + ) + label_name = label_kw or data.columns + data.columns = label_name + plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds) plot_obj.generate() @@ -1788,7 +1803,7 @@ def _plot(data, x=None, y=None, subplots=False, series_kind = "" df_coord = """x : label or position, default None - y : label or position, default None + y : label, position or list of label, positions, default None Allows plotting of one column versus another""" series_coord = "" diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index b29afcb404ac6..ac02f5f4e4283 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -2170,26 +2170,51 @@ def test_invalid_kind(self): with pytest.raises(ValueError): df.plot(kind='aasdf') - @pytest.mark.parametrize("x,y", [ - (['B', 'C'], 'A'), - ('A', ['B', 'C']) + @pytest.mark.parametrize("x,y,lbl", [ + (['B', 'C'], 'A', 'a'), + (['A'], ['B', 'C'], ['b', 'c']), + ('A', ['B', 'C'], 'badlabel') ]) - def test_invalid_xy_args(self, x, y): - # GH 18671 + def test_invalid_xy_args(self, x, y, lbl): + # GH 18671, 19699 allows y to be list-like but not x df = DataFrame({"A": [1, 2], 'B': [3, 4], 'C': [5, 6]}) with pytest.raises(ValueError): - df.plot(x=x, y=y) + df.plot(x=x, y=y, label=lbl) @pytest.mark.parametrize("x,y", [ ('A', 'B'), - ('B', 'A') + (['A'], 'B') ]) def test_invalid_xy_args_dup_cols(self, x, y): - # GH 18671 + # GH 18671, 19699 allows y to be list-like but not x df = DataFrame([[1, 3, 5], [2, 4, 6]], columns=list('AAB')) with pytest.raises(ValueError): df.plot(x=x, y=y) + @pytest.mark.parametrize("x,y,lbl,colors", [ + ('A', ['B'], ['b'], ['red']), + ('A', ['B', 'C'], ['b', 'c'], ['red', 'blue']), + (0, [1, 2], ['bokeh', 'cython'], ['green', 'yellow']) + ]) + def test_y_listlike(self, x, y, lbl, colors): + # GH 19699: tests list-like y and verifies lbls & colors + df = DataFrame({"A": [1, 2], 'B': [3, 4], 'C': [5, 6]}) + _check_plot_works(df.plot, x='A', y=y, label=lbl) + + ax = df.plot(x=x, y=y, label=lbl, color=colors) + assert len(ax.lines) == len(y) + self._check_colors(ax.get_lines(), linecolors=colors) + + @pytest.mark.parametrize("x,y,colnames", [ + (0, 1, ['A', 'B']), + (1, 0, [0, 1]) + ]) + def test_xy_args_integer(self, x, y, colnames): + # GH 20056: tests integer args for xy and checks col names + df = DataFrame({"A": [1, 2], 'B': [3, 4]}) + df.columns = colnames + _check_plot_works(df.plot, x=x, y=y) + @pytest.mark.slow def test_hexbin_basic(self): df = self.hexbin_df
- [x] closes #19699 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry @TomAugspurger I added support for the user to pass a list-like to y, as discussed in #19699. The API to `df.plot` is relatively complex with lots of args, so lmk with questions / fdbck. Not sure if I covered everything for docs.
https://api.github.com/repos/pandas-dev/pandas/pulls/20000
2018-03-05T20:01:24Z
2018-03-22T14:31:51Z
2018-03-22T14:31:50Z
2018-03-22T14:31:51Z
DOC: Updated kurt docstring (for pandas sprint)
diff --git a/pandas/core/window.py b/pandas/core/window.py index 417888ce80b46..cef012bb33e9f 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -899,7 +899,53 @@ def skew(self, **kwargs): return self._apply('roll_skew', 'skew', check_minp=_require_min_periods(3), **kwargs) - _shared_docs['kurt'] = """Unbiased %(name)s kurtosis""" + _shared_docs['kurt'] = dedent(""" + Calculate unbiased %(name)s kurtosis. + + This function uses Fisher's definition of kurtosis without bias. + + Parameters + ---------- + kwargs : Under Review + + Returns + ------- + Series or DataFrame (matches input) + Like-indexed object containing the result of function application + + See Also + -------- + pandas.Series.%(name)s + pandas.DataFrame.%(name)s + pandas.Series.kurtosis + pandas.DataFrame.kurtosis + scipy.stats.skew + scipy.stats.kurtosis + + Notes + ----- + A minimum of 4 periods is required for the rolling calculation. + + Examples + -------- + The below example will show a rolling calculation with a window size of + four matching the equivalent function call using `scipy.stats`. + + >>> arr = [1, 2, 3, 4, 999] + >>> import scipy.stats + >>> print("{0:.6f}".format(scipy.stats.kurtosis(arr[:-1], bias=False))) + -1.200000 + >>> print("{0:.6f}".format(scipy.stats.kurtosis(arr[1:], bias=False))) + 3.999946 + >>> df = pd.DataFrame(arr) + >>> df.rolling(4).kurt() + 0 + 0 NaN + 1 NaN + 2 NaN + 3 -1.200000 + 4 3.999946 + """) def kurt(self, **kwargs): return self._apply('roll_kurt', 'kurt', @@ -1221,7 +1267,6 @@ def skew(self, **kwargs): return super(Rolling, self).skew(**kwargs) @Substitution(name='rolling') - @Appender(_doc_template) @Appender(_shared_docs['kurt']) def kurt(self, **kwargs): return super(Rolling, self).kurt(**kwargs) @@ -1461,7 +1506,6 @@ def skew(self, **kwargs): return super(Expanding, self).skew(**kwargs) @Substitution(name='expanding') - @Appender(_doc_template) @Appender(_shared_docs['kurt']) def kurt(self, **kwargs): return super(Expanding, self).kurt(**kwargs)
Assigned docstring for pandas documentation sprint Please note that I also removed **kwargs from the call signature here as they were not being used, so I thought it would be strange to document. For what it's worth I started a discussion on the G[oogle groups list ](https://groups.google.com/forum/#!topic/pandas-documentation-sprint/P5_av_VuV6E)to see if that's the best way to handle or if we wanted to go a different path
https://api.github.com/repos/pandas-dev/pandas/pulls/19999
2018-03-05T19:50:58Z
2018-03-07T13:56:16Z
2018-03-07T13:56:16Z
2018-03-07T22:20:48Z
DOC: updating docstring of Index.shift
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 0813c12d573d5..44a63029df0fc 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2211,13 +2211,55 @@ def sortlevel(self, level=None, ascending=True, sort_remaining=None): return self.sort_values(return_indexer=True, ascending=ascending) def shift(self, periods=1, freq=None): - """ - Shift Index containing datetime objects by input number of periods and - DateOffset + """Shift index by desired number of time frequency increments. + + This method is for shifting the values of datetime-like indexes + by a specified time increment a given number of times. + + Parameters + ---------- + periods : int + Number of periods (or increments) to shift by, + can be positive or negative (default is 1). + freq : pandas.DateOffset, pandas.Timedelta or string + Frequency increment to shift by (default is None). + If None, the index is shifted by its own `freq` attribute. + Offset aliases are valid strings, e.g., 'D', 'W', 'M' etc. Returns ------- - shifted : Index + pandas.Index + shifted index + + Examples + -------- + Put the first 5 month starts of 2011 into an index. + + >>> month_starts = pd.date_range('1/1/2011', periods=5, freq='MS') + >>> month_starts + DatetimeIndex(['2011-01-01', '2011-02-01', '2011-03-01', '2011-04-01', + '2011-05-01'], + dtype='datetime64[ns]', freq='MS') + + Shift the index by 10 days. + + >>> month_starts.shift(10, freq='D') + DatetimeIndex(['2011-01-11', '2011-02-11', '2011-03-11', '2011-04-11', + '2011-05-11'], + dtype='datetime64[ns]', freq=None) + + The default value of `freq` is the `freq` attribute of the index, + which is 'MS' (month start) in this example. + + >>> month_starts.shift(10) + DatetimeIndex(['2011-11-01', '2011-12-01', '2012-01-01', '2012-02-01', + '2012-03-01'], + dtype='datetime64[ns]', freq='MS') + + Notes + ----- + This method is only implemented for datetime-like index classes, + i.e., DatetimeIndex, PeriodIndex and TimedeltaIndex. """ raise NotImplementedError("Not supported for type %s" % type(self).__name__)
Docstring assigned to PyData Budapest chapter of the Worldwide Documentation Sprint. As Index.shift is an abstract method, this is more of a docstring for developers implementing a subclass than for end users.
https://api.github.com/repos/pandas-dev/pandas/pulls/19996
2018-03-05T16:35:48Z
2018-03-07T13:56:49Z
2018-03-07T13:56:49Z
2018-03-07T14:09:43Z
DOC: require returns section in validation script
diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py index ce3814a1314c1..8425882f07be1 100755 --- a/scripts/validate_docstrings.py +++ b/scripts/validate_docstrings.py @@ -235,6 +235,10 @@ def see_also(self): def examples(self): return self.doc['Examples'] + @property + def returns(self): + return self.doc['Returns'] + @property def first_line_ends_in_dot(self): if self.doc: @@ -436,6 +440,9 @@ def validate_one(func_name): for param_err in param_errs: errs.append('\t{}'.format(param_err)) + if not doc.returns: + errs.append('No returns section found') + mentioned_errs = doc.mentioned_private_classes if mentioned_errs: errs.append('Private classes ({}) should not be mentioned in public '
Are there cases where do not want a "Returns" section? cc @datapythonista
https://api.github.com/repos/pandas-dev/pandas/pulls/19994
2018-03-05T14:48:57Z
2018-03-08T13:09:13Z
2018-03-08T13:09:13Z
2018-03-08T13:09:16Z
CLN/DOC: cache_readonly: remove allow_setting + preserve docstring
diff --git a/pandas/_libs/properties.pyx b/pandas/_libs/properties.pyx index 4beb24f07c21c..67f58851a9a70 100644 --- a/pandas/_libs/properties.pyx +++ b/pandas/_libs/properties.pyx @@ -6,31 +6,28 @@ from cpython cimport ( PyDict_Contains, PyDict_GetItem, PyDict_SetItem) -cdef class cache_readonly(object): +cdef class CachedProperty(object): cdef readonly: - object func, name, allow_setting + object func, name, __doc__ - def __init__(self, func=None, allow_setting=False): - if func is not None: - self.func = func - self.name = func.__name__ - self.allow_setting = allow_setting - - def __call__(self, func, doc=None): + def __init__(self, func): self.func = func self.name = func.__name__ - return self + self.__doc__ = getattr(func, '__doc__', None) def __get__(self, obj, typ): - # Get the cache or set a default one if needed + if obj is None: + # accessed on the class, not the instance + return self + # Get the cache or set a default one if needed cache = getattr(obj, '_cache', None) if cache is None: try: cache = obj._cache = {} except (AttributeError): - return + return self if PyDict_Contains(cache, self.name): # not necessary to Py_INCREF @@ -40,20 +37,9 @@ cdef class cache_readonly(object): PyDict_SetItem(cache, self.name, val) return val - def __set__(self, obj, value): - - if not self.allow_setting: - raise Exception("cannot set values for [%s]" % self.name) - # Get the cache or set a default one if needed - cache = getattr(obj, '_cache', None) - if cache is None: - try: - cache = obj._cache = {} - except (AttributeError): - return +cache_readonly = CachedProperty - PyDict_SetItem(cache, self.name, value) cdef class AxisProperty(object): cdef: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 0813c12d573d5..d3a8f11a38715 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1401,7 +1401,7 @@ def _is_strictly_monotonic_decreasing(self): def is_lexsorted_for_tuple(self, tup): return True - @cache_readonly(allow_setting=True) + @cache_readonly def is_unique(self): """ return if the index has unique values """ return self._engine.is_unique diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index d7f185853ca45..964a6b14d2b1e 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -519,7 +519,6 @@ def test_is_(self): assert not ind.is_(ind.copy()) assert not ind.is_(ind.copy(deep=False)) assert not ind.is_(ind[:]) - assert not ind.is_(ind.view(np.ndarray).view(Index)) assert not ind.is_(np.array(range(10))) # quasi-implementation dependent diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py index 502f0c3bced61..3e34b48fb6795 100644 --- a/pandas/tests/test_lib.py +++ b/pandas/tests/test_lib.py @@ -3,6 +3,7 @@ import pytest import numpy as np +from pandas import Index from pandas._libs import lib, writers as libwriters import pandas.util.testing as tm @@ -198,3 +199,8 @@ def test_get_reverse_indexer(self): result = lib.get_reverse_indexer(indexer, 5) expected = np.array([4, 2, 3, 6, 7], dtype=np.int64) tm.assert_numpy_array_equal(result, expected) + + +def test_cache_readonly_preserve_docstrings(): + # GH18197 + assert Index.hasnans.__doc__ is not None
Closes https://github.com/pandas-dev/pandas/issues/18197 This kind of 'works' in that `?` or `__doc__` now give the correct docstring, but it's not yet fully ideal as it is now seen as a class (which will probably mess up sphinx' autodoc/autosummary, which I didn't check yet)
https://api.github.com/repos/pandas-dev/pandas/pulls/19991
2018-03-05T10:58:42Z
2018-03-06T21:42:42Z
2018-03-06T21:42:41Z
2018-03-06T21:42:45Z
DOC: update contributing guide regarding updating a pull request (merge master)
diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index 9a5e184884e76..f7fc9575566b7 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -246,16 +246,16 @@ changes in this branch specific to one bug or feature so it is clear what the branch brings to *pandas*. You can have many shiny-new-features and switch in between them using the git checkout command. -To update this branch, you need to retrieve the changes from the master branch:: +When creating this branch, make sure your master branch is up to date with +the latest upstream master version. To update your local master branch, you +can do:: - git fetch upstream - git rebase upstream/master + git checkout master + git pull upstream master --ff-only -This will replay your commits on top of the latest pandas git master. If this -leads to merge conflicts, you must resolve these before submitting your pull -request. If you have uncommitted changes, you will need to ``stash`` them prior -to updating. This will effectively store your changes and they can be reapplied -after updating. +When you want to update the feature branch with changes in master after +you created the branch, check the section on +:ref:`updating a PR <contributing.update-pr>`. .. _contributing.documentation: @@ -964,32 +964,6 @@ Now you can commit your changes in your local repository:: git commit -m -Combining commits ------------------ - -If you have multiple commits, you may want to combine them into one commit, often -referred to as "squashing" or "rebasing". This is a common request by package maintainers -when submitting a pull request as it maintains a more compact commit history. To rebase -your commits:: - - git rebase -i HEAD~# - -Where # is the number of commits you want to combine. Then you can pick the relevant -commit message and discard others. - -To squash to the master branch do:: - - git rebase -i master - -Use the ``s`` option on a commit to ``squash``, meaning to keep the commit messages, -or ``f`` to ``fixup``, meaning to merge the commit messages. - -Then you will need to push the branch (see below) forcefully to replace the current -commits with the new ones:: - - git push origin shiny-new-feature -f - - Pushing your changes -------------------- @@ -1045,15 +1019,51 @@ release. To submit a pull request: #. Click ``Send Pull Request``. This request then goes to the repository maintainers, and they will review -the code. If you need to make more changes, you can make them in -your branch, push them to GitHub, and the pull request will be automatically -updated. Pushing them to GitHub again is done by:: +the code. + +.. _contributing.update-pr: - git push -f origin shiny-new-feature +Updating your pull request +-------------------------- + +Based on the review you get on your pull request, you will probably need to make +some changes to the code. In that case, you can make them in your branch, +add a new commit to that branch, push it to GitHub, and the pull request will be +automatically updated. Pushing them to GitHub again is done by:: + + git push origin shiny-new-feature This will automatically update your pull request with the latest code and restart the :ref:`Continuous Integration <contributing.ci>` tests. +Another reason you might need to update your pull request is to solve conflicts +with changes that have been merged into the master branch since you opened your +pull request. + +To do this, you need to "merge upstream master" in your branch:: + + git checkout shiny-new-feature + git fetch upstream + git merge upstream/master + +If there are no conflicts (or they could be fixed automatically), a file with a +default commit message will open, and you can simply save and quit this file. + +If there are merge conflicts, you need to solve those conflicts. See for +example at https://help.github.com/articles/resolving-a-merge-conflict-using-the-command-line/ +for an explanation on how to do this. +Once the conflicts are merged and the files where the conflicts were solved are +added, you can run ``git commit`` to save those fixes. + +If you have uncommitted changes at the moment you want to update the branch with +master, you will need to ``stash`` them prior to updating (see the +`stash docs <https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning>`__). +This will effectively store your changes and they can be reapplied after updating. + +After the feature branch has been update locally, you can now update your pull +request by pushing to the branch on GitHub:: + + git push origin shiny-new-feature Delete your merged branch (optional) ------------------------------------
Closes https://github.com/pandas-dev/pandas/issues/19412 Reference discussion: https://mail.python.org/pipermail/pandas-dev/2017-November/000632.html cc @datapythonista
https://api.github.com/repos/pandas-dev/pandas/pulls/19990
2018-03-05T10:26:36Z
2018-03-16T12:55:18Z
2018-03-16T12:55:17Z
2018-03-16T12:55:21Z
CLN: Python comprehensions and generators cleanup followup
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 89d2de6de213a..52ca3d1226f79 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -1045,7 +1045,7 @@ cdef class TextReader: usecols = set() if callable(self.usecols): if self.usecols(name): - usecols = set([i]) + usecols = {i} else: usecols = self.usecols if self.has_usecols and not (i in usecols or diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 09aeff852a0f2..2ecd55ea88170 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -57,7 +57,7 @@ _DEFAULT_DATETIME = datetime(1, 1, 1).replace(hour=0, minute=0, cdef object _TIMEPAT = re.compile(r'^([01]?[0-9]|2[0-3]):([0-5][0-9])') -cdef set _not_datelike_strings = set(['a', 'A', 'm', 'M', 'p', 'P', 't', 'T']) +cdef set _not_datelike_strings = {'a', 'A', 'm', 'M', 'p', 'P', 't', 'T'} NAT_SENTINEL = object() # This allows us to reference NaT without having to import it @@ -651,7 +651,7 @@ def _guess_datetime_format(dt_str, dayfirst=False, dt_str_parse=du_parse, break # Only consider it a valid guess if we have a year, month and day - if len(set(['year', 'month', 'day']) & found_attrs) != 3: + if len({'year', 'month', 'day'} & found_attrs) != 3: return None output_format = [] diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py index e444c4002c2c0..c1a9a9fc1ed13 100644 --- a/pandas/compat/pickle_compat.py +++ b/pandas/compat/pickle_compat.py @@ -38,9 +38,9 @@ def load_reduce(self): # try to re-encode the arguments if getattr(self, 'encoding', None) is not None: - args = tuple([arg.encode(self.encoding) - if isinstance(arg, string_types) - else arg for arg in args]) + args = tuple(arg.encode(self.encoding) + if isinstance(arg, string_types) + else arg for arg in args) try: stack[-1] = func(*args) return diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c411e29b5cc02..a45887543dc53 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -212,9 +212,8 @@ def _dir_additions(self): """ 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)]) + additions = {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/core/indexing.py b/pandas/core/indexing.py index 2aa490cd02afb..ec2874b3bae95 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -905,9 +905,8 @@ def _multi_take(self, tup): """ try: o = self.obj - d = dict( - [(a, self._convert_for_reindex(t, axis=o._get_axis_number(a))) - for t, a in zip(tup, o._AXIS_ORDERS)]) + d = {a: self._convert_for_reindex(t, axis=o._get_axis_number(a)) + for t, a in zip(tup, o._AXIS_ORDERS)} return o.reindex(**d) except(KeyError, IndexingError): raise self._exception
xref #18276, #18383 - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Some multiline comprehensions and cleanups I missed in the two passes xref'd above.
https://api.github.com/repos/pandas-dev/pandas/pulls/19989
2018-03-05T06:18:05Z
2018-03-05T11:23:49Z
2018-03-05T11:23:49Z
2018-03-05T17:32:18Z
fixed pytest deprecation warning
diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 6247079e4ac3a..b455073665442 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -1224,10 +1224,11 @@ def test_values_consistent(array, expected_type, dtype): (pd.DatetimeIndex(['2017-01-01T00:00:00'], tz="US/Eastern"), np.array(['2017-01-01T05:00:00'], dtype='M8[ns]')), (pd.TimedeltaIndex([10**10]), np.array([10**10], dtype='m8[ns]')), - pytest.mark.xfail(reason='PeriodArray not implemented')(( + pytest.param( pd.PeriodIndex(['2017', '2018'], freq='D'), np.array([17167, 17532]), - )), + marks=pytest.mark.xfail(reason="Not implemented") + ), ]) def test_ndarray_values(array, expected): l_values = pd.Series(array)._ndarray_values
- closes #19703 fixed pytest deprecation warning
https://api.github.com/repos/pandas-dev/pandas/pulls/19987
2018-03-04T23:52:12Z
2018-03-05T11:35:00Z
2018-03-05T11:35:00Z
2018-03-05T11:35:04Z
DOC: is confusing for ddof parameter of sem, var and std functions
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c411e29b5cc02..3f0cb8a5bfcca 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7767,7 +7767,8 @@ def _doc_parms(cls): If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a %(name1)s ddof : int, default 1 - degrees of freedom + Delta Degrees of Freedom. The divisor used in calculations is N - ddof, + where N represents the number of elements. numeric_only : boolean, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Closes #18903
https://api.github.com/repos/pandas-dev/pandas/pulls/19986
2018-03-04T22:03:37Z
2018-03-06T21:47:46Z
2018-03-06T21:47:46Z
2018-03-07T19:54:00Z
DOC: Improve docstring for pandas.Index.repeat
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 0813c12d573d5..880e283af9186 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -696,12 +696,38 @@ def memory_usage(self, deep=False): @deprecate_kwarg(old_arg_name='n', new_arg_name='repeats') def repeat(self, repeats, *args, **kwargs): """ - Repeat elements of an Index. Refer to `numpy.ndarray.repeat` - for more information about the `repeats` argument. + Repeat elements of an Index. - See also + Returns a new index where each element of the current index + is repeated consecutively a given number of times. + + Parameters + ---------- + repeats : int + The number of repetitions for each element. + **kwargs + Additional keywords have no effect but might be accepted for + compatibility with numpy. + + Returns + ------- + pandas.Index + Newly created Index with repeated elements. + + See Also + -------- + Series.repeat : Equivalent function for Series + numpy.repeat : Underlying implementation + + Examples -------- - numpy.ndarray.repeat + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Int64Index([1, 2, 3], dtype='int64') + >>> idx.repeat(2) + Int64Index([1, 1, 2, 2, 3, 3], dtype='int64') + >>> idx.repeat(3) + Int64Index([1, 1, 1, 2, 2, 2, 3, 3, 3], dtype='int64') """ nv.validate_repeat(args, kwargs) return self._shallow_copy(self._values.repeat(repeats))
String assigned to ChiPy (Chicago Python Users Group) chapter of the Worldwide Documentation Sprint While `Index.repeat` does accept `args` and `kwargs`, it does not pass them through to the underlying `numpy` function. The only additional parameter the numpy function takes is `axis` ([numpy docs](https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html#numpy.repeat)), which is not supported by pandas: ```python >>> pd.Index([1, 2, 3]).repeat(2, axis=2) ValueError: the 'axis' parameter is not supported in the pandas implementation of repeat() ``` Should the *args and **kwargs be removed? Thanks
https://api.github.com/repos/pandas-dev/pandas/pulls/19985
2018-03-04T21:04:26Z
2018-03-09T08:20:00Z
2018-03-09T08:20:00Z
2018-03-09T09:36:58Z
DOC: Update is_sparse docstring
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 94e9b72b001b1..a01266870b8fc 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -150,32 +150,59 @@ def is_object_dtype(arr_or_dtype): def is_sparse(arr): """ - Check whether an array-like is a pandas sparse array. + Check whether an array-like is a 1-D pandas sparse array. + + Check that the one-dimensional array-like is a pandas sparse array. + Returns True if it is a pandas sparse array, not another type of + sparse array. Parameters ---------- arr : array-like - The array-like to check. + Array-like to check. Returns ------- - boolean : Whether or not the array-like is a pandas sparse array. + bool + Whether or not the array-like is a pandas sparse array. + + See Also + -------- + DataFrame.to_sparse : Convert DataFrame to a SparseDataFrame. + Series.to_sparse : Convert Series to SparseSeries. + Series.to_dense : Return dense representation of a Series. Examples -------- - >>> is_sparse(np.array([1, 2, 3])) - False - >>> is_sparse(pd.SparseArray([1, 2, 3])) + Returns `True` if the parameter is a 1-D pandas sparse array. + + >>> is_sparse(pd.SparseArray([0, 0, 1, 0])) True - >>> is_sparse(pd.SparseSeries([1, 2, 3])) + >>> is_sparse(pd.SparseSeries([0, 0, 1, 0])) True - This function checks only for pandas sparse array instances, so - sparse arrays from other libraries will return False. + Returns `False` if the parameter is not sparse. + + >>> is_sparse(np.array([0, 0, 1, 0])) + False + >>> is_sparse(pd.Series([0, 1, 0, 0])) + False + + Returns `False` if the parameter is not a pandas sparse array. >>> from scipy.sparse import bsr_matrix - >>> is_sparse(bsr_matrix([1, 2, 3])) + >>> is_sparse(bsr_matrix([0, 1, 0, 0])) False + + Returns `False` if the parameter has more than one dimension. + + >>> df = pd.SparseDataFrame([389., 24., 80.5, np.nan], + columns=['max_speed'], + index=['falcon', 'parrot', 'lion', 'monkey']) + >>> is_sparse(df) + False + >>> is_sparse(df.max_speed) + True """ from pandas.core.arrays.sparse import SparseDtype
`is_sparse(pd.SparseDataFrame([1,2,3]))` returns `False`. The is_sparse function checks to see if an array-like is spare by checking to see if it is an instance of ABCSparseArray or ABCSparseSeries. This commit adds ABCSparseDataFrame to that list -- so it can detect that a DataFrame (which is an array-like object) is sparse. Added a test for this. - [ ] closes #xxxx - [ ] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/19983
2018-03-04T14:57:49Z
2018-11-13T17:52:42Z
2018-11-13T17:52:42Z
2018-11-13T17:52:59Z
DOC: Improved the docstring of Series.str.findall
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 6b427ed1da834..fac607f4621a8 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -898,23 +898,94 @@ def str_join(arr, sep): def str_findall(arr, pat, flags=0): """ - Find all occurrences of pattern or regular expression in the - Series/Index. Equivalent to :func:`re.findall`. + Find all occurrences of pattern or regular expression in the Series/Index. + + Equivalent to applying :func:`re.findall` to all the elements in the + Series/Index. Parameters ---------- pat : string - Pattern or regular expression - flags : int, default 0 (no flags) - re module flags, e.g. re.IGNORECASE + Pattern or regular expression. + flags : int, default 0 + ``re`` module flags, e.g. `re.IGNORECASE` (default is 0, which means + no flags). Returns ------- - matches : Series/Index of lists + Series/Index of lists of strings + All non-overlapping matches of pattern or regular expression in each + string of this Series/Index. See Also -------- - extractall : returns DataFrame with one column per capture group + count : Count occurrences of pattern or regular expression in each string + of the Series/Index. + extractall : For each string in the Series, extract groups from all matches + of regular expression and return a DataFrame with one row for each + match and one column for each group. + re.findall : The equivalent ``re`` function to all non-overlapping matches + of pattern or regular expression in string, as a list of strings. + + Examples + -------- + + >>> s = pd.Series(['Lion', 'Monkey', 'Rabbit']) + + The search for the pattern 'Monkey' returns one match: + + >>> s.str.findall('Monkey') + 0 [] + 1 [Monkey] + 2 [] + dtype: object + + On the other hand, the search for the pattern 'MONKEY' doesn't return any + match: + + >>> s.str.findall('MONKEY') + 0 [] + 1 [] + 2 [] + dtype: object + + Flags can be added to the pattern or regular expression. For instance, + to find the pattern 'MONKEY' ignoring the case: + + >>> import re + >>> s.str.findall('MONKEY', flags=re.IGNORECASE) + 0 [] + 1 [Monkey] + 2 [] + dtype: object + + When the pattern matches more than one string in the Series, all matches + are returned: + + >>> s.str.findall('on') + 0 [on] + 1 [on] + 2 [] + dtype: object + + Regular expressions are supported too. For instance, the search for all the + strings ending with the word 'on' is shown next: + + >>> s.str.findall('on$') + 0 [on] + 1 [] + 2 [] + dtype: object + + If the pattern is found more than once in the same string, then a list of + multiple strings is returned: + + >>> s.str.findall('b') + 0 [] + 1 [] + 2 [b, b] + dtype: object + """ regex = re.compile(pat, flags=flags) return _na_map(regex.findall, arr)
Docstring assigned to PyData Mallorca in Pandas Documentation Sprint (https://python-sprints.github.io/pandas/). Please, any indication to improve our PR will be appreciated! Happy to contribute :-)
https://api.github.com/repos/pandas-dev/pandas/pulls/19982
2018-03-04T14:52:40Z
2018-03-10T12:24:36Z
2018-03-10T12:24:36Z
2018-03-10T12:24:41Z
CLN: deprecate the pandas.tseries.plotting.tsplot function (GH18627)
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index a976fca66a57a..79d85513efa26 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -731,6 +731,8 @@ Deprecations - The ``order`` parameter of :func:`factorize` is deprecated and will be removed in a future release (:issue:`19727`) - :attr:`Timestamp.weekday_name`, :attr:`DatetimeIndex.weekday_name`, and :attr:`Series.dt.weekday_name` are deprecated in favor of :meth:`Timestamp.day_name`, :meth:`DatetimeIndex.day_name`, and :meth:`Series.dt.day_name` (:issue:`12806`) +- ``pandas.tseries.plotting.tsplot`` is deprecated. Use :func:`Series.plot` instead (:issue:`18627`) + .. _whatsnew_0230.prior_deprecations: Removal of prior version deprecations/changes diff --git a/pandas/plotting/_timeseries.py b/pandas/plotting/_timeseries.py index 56b5311326e98..21a03ea388566 100644 --- a/pandas/plotting/_timeseries.py +++ b/pandas/plotting/_timeseries.py @@ -23,6 +23,7 @@ def tsplot(series, plotf, ax=None, **kwargs): + import warnings """ Plots a Series on the given Matplotlib axes or the current axes @@ -35,7 +36,14 @@ def tsplot(series, plotf, ax=None, **kwargs): _____ Supports same kwargs as Axes.plot + + .. deprecated:: 0.23.0 + Use Series.plot() instead """ + warnings.warn("'tsplot' is deprecated and will be removed in a " + "future version. Please use Series.plot() instead.", + FutureWarning, stacklevel=2) + # Used inferred freq is possible, need a test case for inferred if ax is None: import matplotlib.pyplot as plt diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 08a047a2e7707..92ca68257eabf 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -100,6 +100,15 @@ def test_nonnumeric_exclude(self): pytest.raises(TypeError, df['A'].plot) + def test_tsplot_deprecated(self): + from pandas.tseries.plotting import tsplot + + _, ax = self.plt.subplots() + ts = tm.makeTimeSeries() + + with tm.assert_produces_warning(FutureWarning): + tsplot(ts, self.plt.Axes.plot, ax=ax) + @pytest.mark.slow def test_tsplot(self): from pandas.tseries.plotting import tsplot
- [X] closes #18627 - [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/19980
2018-03-04T02:35:22Z
2018-03-06T08:29:27Z
2018-03-06T08:29:27Z
2018-03-06T08:29:30Z
ENH: Parse %z and %Z directive in format for to_datetime
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 43e513c9d03f5..079766f0bc635 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -12,7 +12,7 @@ New features Other Enhancements ^^^^^^^^^^^^^^^^^^ -- +- :func:`to_datetime` now supports the ``%Z`` and ``%z`` directive when passed into ``format`` (:issue:`13486`) - - diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index e7dabb94f8975..77ce8e4ed4127 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -20,6 +20,7 @@ except: except: from _dummy_thread import allocate_lock as _thread_allocate_lock +import pytz from cython cimport Py_ssize_t from cpython cimport PyFloat_Check @@ -40,6 +41,27 @@ from util cimport is_string_object from nattype cimport checknull_with_nat, NPY_NAT from nattype import nat_strings +cdef dict _parse_code_table = {'y': 0, + 'Y': 1, + 'm': 2, + 'B': 3, + 'b': 4, + 'd': 5, + 'H': 6, + 'I': 7, + 'M': 8, + 'S': 9, + 'f': 10, + 'A': 11, + 'a': 12, + 'w': 13, + 'j': 14, + 'U': 15, + 'W': 16, + 'Z': 17, + 'p': 18, # an additional key, only with I + 'z': 19} + def array_strptime(ndarray[object] values, object fmt, bint exact=True, errors='raise'): @@ -58,15 +80,15 @@ def array_strptime(ndarray[object] values, object fmt, Py_ssize_t i, n = len(values) pandas_datetimestruct dts ndarray[int64_t] iresult - int year, month, day, minute, hour, second, weekday, julian, tz - int week_of_year, week_of_year_start + ndarray[object] result_timezone + int year, month, day, minute, hour, second, weekday, julian + int week_of_year, week_of_year_start, parse_code, ordinal int64_t us, ns - object val, group_key, ampm, found + object val, group_key, ampm, found, timezone dict found_key bint is_raise = errors=='raise' bint is_ignore = errors=='ignore' bint is_coerce = errors=='coerce' - int ordinal assert is_raise or is_ignore or is_coerce @@ -79,6 +101,8 @@ def array_strptime(ndarray[object] values, object fmt, in fmt): raise ValueError("Cannot use '%W' or '%U' without " "day and year") + elif '%Z' in fmt and '%z' in fmt: + raise ValueError("Cannot parse both %Z and %z") global _TimeRE_cache, _regex_cache with _cache_lock: @@ -108,32 +132,10 @@ def array_strptime(ndarray[object] values, object fmt, result = np.empty(n, dtype='M8[ns]') iresult = result.view('i8') + result_timezone = np.empty(n, dtype='object') dts.us = dts.ps = dts.as = 0 - cdef dict _parse_code_table = { - 'y': 0, - 'Y': 1, - 'm': 2, - 'B': 3, - 'b': 4, - 'd': 5, - 'H': 6, - 'I': 7, - 'M': 8, - 'S': 9, - 'f': 10, - 'A': 11, - 'a': 12, - 'w': 13, - 'j': 14, - 'U': 15, - 'W': 16, - 'Z': 17, - 'p': 18 # just an additional key, works only with I - } - cdef int parse_code - for i in range(n): val = values[i] if is_string_object(val): @@ -176,7 +178,7 @@ def array_strptime(ndarray[object] values, object fmt, year = 1900 month = day = 1 hour = minute = second = ns = us = 0 - tz = -1 + timezone = None # Default to -1 to signify that values not known; not critical to have, # though week_of_year = -1 @@ -266,21 +268,10 @@ def array_strptime(ndarray[object] values, object fmt, # W starts week on Monday. week_of_year_start = 0 elif parse_code == 17: - # Since -1 is default value only need to worry about setting tz - # if it can be something other than -1. - found_zone = found_dict['Z'].lower() - for value, tz_values in enumerate(locale_time.timezone): - if found_zone in tz_values: - # Deal w/ bad locale setup where timezone names are the - # same and yet time.daylight is true; too ambiguous to - # be able to tell what timezone has daylight savings - if (time.tzname[0] == time.tzname[1] and - time.daylight and found_zone not in ( - "utc", "gmt")): - break - else: - tz = value - break + timezone = pytz.timezone(found_dict['Z']) + elif parse_code == 19: + timezone = parse_timezone_directive(found_dict['z']) + # If we know the wk of the year and what day of that wk, we can figure # out the Julian day of the year. if julian == -1 and week_of_year != -1 and weekday != -1: @@ -330,7 +321,9 @@ def array_strptime(ndarray[object] values, object fmt, continue raise - return result + result_timezone[i] = timezone + + return result, result_timezone """_getlang, LocaleTime, TimeRE, _calc_julian_from_U_or_W are vendored @@ -538,14 +531,13 @@ class TimeRE(dict): # XXX: Does 'Y' need to worry about having less or more than # 4 digits? 'Y': r"(?P<Y>\d\d\d\d)", + 'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|Z)", 'A': self.__seqToRE(self.locale_time.f_weekday, 'A'), 'a': self.__seqToRE(self.locale_time.a_weekday, 'a'), 'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'), 'b': self.__seqToRE(self.locale_time.a_month[1:], 'b'), 'p': self.__seqToRE(self.locale_time.am_pm, 'p'), - 'Z': self.__seqToRE([tz for tz_names in self.locale_time.timezone - for tz in tz_names], - 'Z'), + 'Z': self.__seqToRE(pytz.all_timezones, 'Z'), '%': '%'}) base.__setitem__('W', base.__getitem__('U').replace('U', 'W')) base.__setitem__('c', self.pattern(self.locale_time.LC_date_time)) @@ -632,3 +624,50 @@ cdef _calc_julian_from_U_or_W(int year, int week_of_year, else: days_to_week = week_0_length + (7 * (week_of_year - 1)) return 1 + days_to_week + day_of_week + +cdef parse_timezone_directive(object z): + """ + Parse the '%z' directive and return a pytz.FixedOffset + + Parameters + ---------- + z : string of the UTC offset + + Returns + ------- + pytz.FixedOffset + + Notes + ----- + This is essentially similar to the cpython implementation + https://github.com/python/cpython/blob/master/Lib/_strptime.py#L457-L479 + """ + + cdef: + int gmtoff_fraction, hours, minutes, seconds, pad_number, microseconds + int total_minutes + object gmtoff_remainder, gmtoff_remainder_padding + + if z == 'Z': + return pytz.FixedOffset(0) + if z[3] == ':': + z = z[:3] + z[4:] + if len(z) > 5: + if z[5] != ':': + msg = "Inconsistent use of : in {0}" + raise ValueError(msg.format(z)) + z = z[:5] + z[6:] + hours = int(z[1:3]) + minutes = int(z[3:5]) + seconds = int(z[5:7] or 0) + + # Pad to always return microseconds. + gmtoff_remainder = z[8:] + pad_number = 6 - len(gmtoff_remainder) + gmtoff_remainder_padding = "0" * pad_number + microseconds = int(gmtoff_remainder + gmtoff_remainder_padding) + + total_minutes = ((hours * 60) + minutes + (seconds / 60) + + (microseconds / 60000000)) + total_minutes = -total_minutes if z.startswith("-") else total_minutes + return pytz.FixedOffset(total_minutes) diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 1de43116d0b49..5da79c7754411 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -1,7 +1,8 @@ from datetime import datetime, timedelta, time -import numpy as np from collections import MutableMapping +import numpy as np + from pandas._libs import tslib from pandas._libs.tslibs.strptime import array_strptime from pandas._libs.tslibs import parsing, conversion @@ -27,6 +28,7 @@ ABCDataFrame) from pandas.core.dtypes.missing import notna from pandas.core import algorithms +from pandas.compat import zip def _guess_datetime_format_for_array(arr, **kwargs): @@ -103,6 +105,41 @@ def _convert_and_box_cache(arg, cache_array, box, errors, name=None): return result.values +def _return_parsed_timezone_results(result, timezones, box, tz): + """ + Return results from array_strptime if a %z or %Z directive was passed. + + Parameters + ---------- + result : ndarray + int64 date representations of the dates + timezones : ndarray + pytz timezone objects + box : boolean + True boxes result as an Index-like, False returns an ndarray + tz : object + None or pytz timezone object + Returns + ------- + tz_result : ndarray of parsed dates with timezone + Returns: + + - Index-like if box=True + - ndarray of Timestamps if box=False + + """ + if tz is not None: + raise ValueError("Cannot pass a tz argument when " + "parsing strings with timezone " + "information.") + tz_results = np.array([tslib.Timestamp(res).tz_localize(zone) for res, zone + in zip(result, timezones)]) + if box: + from pandas import Index + return Index(tz_results) + return tz_results + + def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin='unix', @@ -343,8 +380,11 @@ def _convert_listlike(arg, box, format, name=None, tz=tz): # fallback if result is None: try: - result = array_strptime(arg, format, exact=exact, - errors=errors) + result, timezones = array_strptime( + arg, format, exact=exact, errors=errors) + if '%Z' in format or '%z' in format: + return _return_parsed_timezone_results( + result, timezones, box, tz) except tslib.OutOfBoundsDatetime: if errors == 'raise': raise diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index 8b0514764b0c0..e09c1b3f19d1a 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -179,6 +179,59 @@ def test_to_datetime_format_weeks(self, cache): for s, format, dt in data: assert to_datetime(s, format=format, cache=cache) == dt + @pytest.mark.parametrize("box,const,assert_equal", [ + [True, pd.Index, 'assert_index_equal'], + [False, np.array, 'assert_numpy_array_equal']]) + @pytest.mark.parametrize("fmt,dates,expected_dates", [ + ['%Y-%m-%d %H:%M:%S %Z', + ['2010-01-01 12:00:00 UTC'] * 2, + [pd.Timestamp('2010-01-01 12:00:00', tz='UTC')] * 2], + ['%Y-%m-%d %H:%M:%S %Z', + ['2010-01-01 12:00:00 UTC', + '2010-01-01 12:00:00 GMT', + '2010-01-01 12:00:00 US/Pacific'], + [pd.Timestamp('2010-01-01 12:00:00', tz='UTC'), + pd.Timestamp('2010-01-01 12:00:00', tz='GMT'), + pd.Timestamp('2010-01-01 12:00:00', tz='US/Pacific')]], + ['%Y-%m-%d %H:%M:%S%z', + ['2010-01-01 12:00:00+0100'] * 2, + [pd.Timestamp('2010-01-01 12:00:00', + tzinfo=pytz.FixedOffset(60))] * 2], + ['%Y-%m-%d %H:%M:%S %z', + ['2010-01-01 12:00:00 +0100'] * 2, + [pd.Timestamp('2010-01-01 12:00:00', + tzinfo=pytz.FixedOffset(60))] * 2], + ['%Y-%m-%d %H:%M:%S %z', + ['2010-01-01 12:00:00 +0100', '2010-01-01 12:00:00 -0100'], + [pd.Timestamp('2010-01-01 12:00:00', + tzinfo=pytz.FixedOffset(60)), + pd.Timestamp('2010-01-01 12:00:00', + tzinfo=pytz.FixedOffset(-60))]], + ['%Y-%m-%d %H:%M:%S %z', + ['2010-01-01 12:00:00 Z', '2010-01-01 12:00:00 Z'], + [pd.Timestamp('2010-01-01 12:00:00', + tzinfo=pytz.FixedOffset(0)), # pytz coerces to UTC + pd.Timestamp('2010-01-01 12:00:00', + tzinfo=pytz.FixedOffset(0))]]]) + def test_to_datetime_parse_tzname_or_tzoffset(self, box, const, + assert_equal, fmt, + dates, expected_dates): + # GH 13486 + result = pd.to_datetime(dates, format=fmt, box=box) + expected = const(expected_dates) + getattr(tm, assert_equal)(result, expected) + + with pytest.raises(ValueError): + pd.to_datetime(dates, format=fmt, box=box, utc=True) + + @pytest.mark.parametrize('offset', [ + '+0', '-1foo', 'UTCbar', ':10', '+01:000:01', '']) + def test_to_datetime_parse_timezone_malformed(self, offset): + fmt = '%Y-%m-%d %H:%M:%S %z' + date = '2010-01-01 12:00:00 ' + offset + with pytest.raises(ValueError): + pd.to_datetime([date], format=fmt) + class TestToDatetime(object): def test_to_datetime_pydatetime(self):
- [x] closes #13486 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry The implimentiontion is near identical to https://github.com/python/cpython/blob/master/Lib/_strptime.py an currently works as `datetime.strptime` would: ``` In [3]: f = '%Y-%m-%d %H:%M:%S %Z %z' # datetime will parse the case below even though UTC with +0100 should be bogus In [4]: d = ['2010-01-01 12:00:00 UTC +0100'] * 10 In [5]: pd._libs.tslibs.strptime.array_strptime(np.array(d, dtype='object'), f) Out[5]: (array(['2010-01-01T12:00:00.000000000', '2010-01-01T12:00:00.000000000', '2010-01-01T12:00:00.000000000', '2010-01-01T12:00:00.000000000', '2010-01-01T12:00:00.000000000', '2010-01-01T12:00:00.000000000', '2010-01-01T12:00:00.000000000', '2010-01-01T12:00:00.000000000', '2010-01-01T12:00:00.000000000', '2010-01-01T12:00:00.000000000'], dtype='datetime64[ns]'), array([datetime.timezone(datetime.timedelta(0, 3600), 'UTC'), datetime.timezone(datetime.timedelta(0, 3600), 'UTC'), datetime.timezone(datetime.timedelta(0, 3600), 'UTC'), datetime.timezone(datetime.timedelta(0, 3600), 'UTC'), datetime.timezone(datetime.timedelta(0, 3600), 'UTC'), datetime.timezone(datetime.timedelta(0, 3600), 'UTC'), datetime.timezone(datetime.timedelta(0, 3600), 'UTC'), datetime.timezone(datetime.timedelta(0, 3600), 'UTC'), datetime.timezone(datetime.timedelta(0, 3600), 'UTC'), datetime.timezone(datetime.timedelta(0, 3600), 'UTC')], dtype=object)) In [29]: datetime.strptime('2010-01-01 12:00:00 UTC +0100', '%Y-%m-%d %H:%M:%S %Z %z') Out[29]: datetime.datetime(2010, 1, 1, 12, 0, tzinfo=datetime.timezone(datetime.timedelta(0, 3600), 'UTC')) ``` Currently, an offset needs to get passed (%z) in order for the tzname used be used (%Z). I'd like to get feedback of what this function should return having parsed %z or %Z. It may be difficult to return a normal DatimeIndex/Series/array given the following edge cases: 1. User passes strings with different tz offsets (`[date] +0100, [date]. -0600, [date] +1530`) 2. User passes strings with different tz names (`[date] UTC, [date]. EST, [date] CET`) 3. User passes strings with incompatable tz name and offset (see example above) I suppose the most agnostic thing to is to return an array of Timestamps? ``` In [27]: [pd.Timestamp(val, tzinfo=tz) for val, tz in zip(*pd._libs.tslibs.strptime.array_strptime(np.array(d, dtype='object'), f))] Out[27]: [Timestamp('2010-01-01 13:00:00+0100', tz='UTC'), Timestamp('2010-01-01 13:00:00+0100', tz='UTC'), Timestamp('2010-01-01 13:00:00+0100', tz='UTC'), Timestamp('2010-01-01 13:00:00+0100', tz='UTC'), Timestamp('2010-01-01 13:00:00+0100', tz='UTC'), Timestamp('2010-01-01 13:00:00+0100', tz='UTC'), Timestamp('2010-01-01 13:00:00+0100', tz='UTC'), Timestamp('2010-01-01 13:00:00+0100', tz='UTC'), Timestamp('2010-01-01 13:00:00+0100', tz='UTC'), Timestamp('2010-01-01 13:00:00+0100', tz='UTC')] ```
https://api.github.com/repos/pandas-dev/pandas/pulls/19979
2018-03-03T04:49:33Z
2018-05-29T00:28:41Z
2018-05-29T00:28:41Z
2018-05-29T05:00:19Z
BUG: Fixes to msgpack support.
diff --git a/pandas/io/packers.py b/pandas/io/packers.py index d3e6f0cf4a1bc..f9b1d1574d45c 100644 --- a/pandas/io/packers.py +++ b/pandas/io/packers.py @@ -55,7 +55,8 @@ from pandas import (Timestamp, Period, Series, DataFrame, # noqa Index, MultiIndex, Float64Index, Int64Index, Panel, RangeIndex, PeriodIndex, DatetimeIndex, NaT, - Categorical, CategoricalIndex) + Categorical, CategoricalIndex, IntervalIndex, Interval, + TimedeltaIndex) from pandas.core.sparse.api import SparseSeries, SparseDataFrame from pandas.core.sparse.array import BlockIndex, IntIndex from pandas.core.generic import NDFrame @@ -401,6 +402,13 @@ def encode(obj): u'freq': u_safe(getattr(obj, 'freqstr', None)), u'tz': tz, u'compress': compressor} + elif isinstance(obj, IntervalIndex): + return {u'typ': u'interval_index', + u'klass': u(obj.__class__.__name__), + u'name': getattr(obj, 'name', None), + u'left': getattr(obj, '_left', None), + u'right': getattr(obj, '_right', None), + u'closed': getattr(obj, '_closed', None)} elif isinstance(obj, MultiIndex): return {u'typ': u'multi_index', u'klass': u(obj.__class__.__name__), @@ -513,7 +521,12 @@ def encode(obj): elif isinstance(obj, Period): return {u'typ': u'period', u'ordinal': obj.ordinal, - u'freq': u(obj.freq)} + u'freq': u_safe(obj.freqstr)} + elif isinstance(obj, Interval): + return {u'typ': u'interval', + u'left': obj.left, + u'right': obj.right, + u'closed': obj.closed} elif isinstance(obj, BlockIndex): return {u'typ': u'block_index', u'klass': u(obj.__class__.__name__), @@ -597,12 +610,19 @@ def decode(obj): result = result.tz_localize('UTC').tz_convert(tz) return result + elif typ == u'interval_index': + return globals()[obj[u'klass']].from_arrays(obj[u'left'], + obj[u'right'], + obj[u'closed'], + name=obj[u'name']) elif typ == u'category': from_codes = globals()[obj[u'klass']].from_codes return from_codes(codes=obj[u'codes'], categories=obj[u'categories'], ordered=obj[u'ordered']) + elif typ == u'interval': + return Interval(obj[u'left'], obj[u'right'], obj[u'closed']) elif typ == u'series': dtype = dtype_for(obj[u'dtype']) pd_dtype = pandas_dtype(dtype) diff --git a/pandas/tests/io/generate_legacy_storage_files.py b/pandas/tests/io/generate_legacy_storage_files.py index 31e2033b23d87..9f1ac8b1e677b 100755 --- a/pandas/tests/io/generate_legacy_storage_files.py +++ b/pandas/tests/io/generate_legacy_storage_files.py @@ -287,7 +287,8 @@ def create_msgpack_data(): del data['frame']['cat_onecol'] del data['frame']['cat_and_float'] del data['scalars']['period'] - del data['index']['interval'] + if _loose_version < LooseVersion('0.23.0'): + del data['index']['interval'] del data['offsets'] return _u(data) diff --git a/pandas/tests/io/test_packers.py b/pandas/tests/io/test_packers.py index c343e0105eb4f..919b34dc09f6f 100644 --- a/pandas/tests/io/test_packers.py +++ b/pandas/tests/io/test_packers.py @@ -10,7 +10,8 @@ from pandas import compat from pandas.compat import u, PY3 from pandas import (Series, DataFrame, Panel, MultiIndex, bdate_range, - date_range, period_range, Index, Categorical) + date_range, period_range, Index, Categorical, + Period, Interval) from pandas.errors import PerformanceWarning from pandas.io.packers import to_msgpack, read_msgpack import pandas.util.testing as tm @@ -317,6 +318,19 @@ def test_timedeltas(self): i_rec = self.encode_decode(i) assert i == i_rec + def test_periods(self): + # 13463 + for i in [Period('2010-09', 'M'), Period('2014-Q1', 'Q')]: + i_rec = self.encode_decode(i) + assert i == i_rec + + def test_intervals(self): + # 19967 + for i in [Interval(0, 1), Interval(0, 1, 'left'), + Interval(10, 25., 'right')]: + i_rec = self.encode_decode(i) + assert i == i_rec + class TestIndex(TestPackers): @@ -334,7 +348,9 @@ def setup_method(self, method): 'period': Index(period_range('2012-1-1', freq='M', periods=3)), 'date2': Index(date_range('2013-01-1', periods=10)), 'bdate': Index(bdate_range('2013-01-02', periods=10)), - 'cat': tm.makeCategoricalIndex(100) + 'cat': tm.makeCategoricalIndex(100), + 'interval': tm.makeIntervalIndex(100), + 'timedelta': tm.makeTimedeltaIndex(100, 'H') } self.mi = {
Adds support for IntervalIndex and Interval; fixes Period and TimedeltaIndex. Closes #19967 and #13463. - [ ] closes #19967 - [ ] closes #13463 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/19975
2018-03-02T21:27:20Z
2018-03-07T18:04:24Z
2018-03-07T18:04:23Z
2018-03-07T18:04:25Z
fix: scalar timestamp assignment (#19843)
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 3cff1522274ef..9fc087dce752f 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -559,6 +559,7 @@ Timezones - Bug in :class:`DatetimeIndex` where constructing with an integer and tz would not localize correctly (:issue:`12619`) - Fixed bug where :meth:`DataFrame.describe` and :meth:`Series.describe` on tz-aware datetimes did not show `first` and `last` result (:issue:`21328`) - Bug in :class:`DatetimeIndex` comparisons failing to raise ``TypeError`` when comparing timezone-aware ``DatetimeIndex`` against ``np.datetime64`` (:issue:`22074`) +- Bug in ``DataFrame`` assignment with a timezone-aware scalar (:issue:`19843`) Offsets ^^^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ebd35cb1a6a1a..b7894881feb40 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -27,6 +27,7 @@ maybe_upcast, cast_scalar_to_array, construct_1d_arraylike_from_scalar, + infer_dtype_from_scalar, maybe_cast_to_datetime, maybe_infer_to_datetimelike, maybe_convert_platform, @@ -3507,9 +3508,13 @@ def reindexer(value): value = maybe_infer_to_datetimelike(value) else: - # upcast the scalar + # cast ignores pandas dtypes. so save the dtype first + infer_dtype, _ = infer_dtype_from_scalar( + value, pandas_dtype=True) + + # upcast value = cast_scalar_to_array(len(self.index), value) - value = maybe_cast_to_datetime(value, value.dtype) + value = maybe_cast_to_datetime(value, infer_dtype) # return internal types directly if is_extension_type(value) or is_extension_array_dtype(value): diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 5f229aca5c25b..d885df76967b8 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -3135,6 +3135,14 @@ def test_transpose(self): expected.index = ['A', 'B'] assert_frame_equal(result, expected) + def test_scalar_assignment(self): + # issue #19843 + df = pd.DataFrame(index=(0, 1, 2)) + df['now'] = pd.Timestamp('20130101', tz='UTC') + expected = pd.DataFrame( + {'now': pd.Timestamp('20130101', tz='UTC')}, index=[0, 1, 2]) + tm.assert_frame_equal(df, expected) + class TestDataFrameIndexingUInt64(TestData):
- [x] closes #19843 - [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/19973
2018-03-02T20:36:25Z
2018-08-02T17:27:23Z
2018-08-02T17:27:23Z
2018-08-02T17:27:23Z
Small ops cleanups
diff --git a/pandas/core/ops.py b/pandas/core/ops.py index 931e91b941a7e..83879cdaaa63c 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -971,9 +971,9 @@ def _arith_method_SERIES(cls, op, special): code duplication. """ str_rep = _get_opstr(op, cls) - name = _get_op_name(op, special) - eval_kwargs = _gen_eval_kwargs(name) - fill_zeros = _gen_fill_zeros(name) + op_name = _get_op_name(op, special) + eval_kwargs = _gen_eval_kwargs(op_name) + fill_zeros = _gen_fill_zeros(op_name) construct_result = (_construct_divmod_result if op is divmod else _construct_result) @@ -996,7 +996,7 @@ def na_op(x, y): result, changed = maybe_upcast_putmask(result, ~mask, np.nan) - result = missing.fill_zeros(result, x, y, name, fill_zeros) + result = missing.fill_zeros(result, x, y, op_name, fill_zeros) return result def safe_na_op(lvalues, rvalues): @@ -1009,7 +1009,7 @@ def safe_na_op(lvalues, rvalues): lambda x: op(x, rvalues)) raise - def wrapper(left, right, name=name, na_op=na_op): + def wrapper(left, right): if isinstance(right, ABCDataFrame): return NotImplemented @@ -1100,8 +1100,8 @@ def _comp_method_SERIES(cls, op, special): Wrapper function for Series arithmetic operations, to avoid code duplication. """ - name = _get_op_name(op, special) - masker = _gen_eval_kwargs(name).get('masker', False) + op_name = _get_op_name(op, special) + masker = _gen_eval_kwargs(op_name).get('masker', False) def na_op(x, y): @@ -1133,7 +1133,7 @@ def na_op(x, y): y = y.view('i8') x = x.view('i8') - method = getattr(x, name, None) + method = getattr(x, op_name, None) if method is not None: with np.errstate(all='ignore'): result = method(y) @@ -1217,7 +1217,7 @@ def wrapper(self, other, axis=None): else: res_values = np.zeros(len(self), dtype=bool) return self._constructor(res_values, index=self.index, - name=self.name, dtype='bool') + name=res_name, dtype='bool') else: values = self.get_values() @@ -1232,8 +1232,8 @@ def wrapper(self, other, axis=None): # always return a full value series here res_values = com._values_from_object(res) - return pd.Series(res_values, index=self.index, - name=res_name, dtype='bool') + return self._constructor(res_values, index=self.index, + name=res_name, dtype='bool') return wrapper @@ -1430,10 +1430,10 @@ def to_series(right): def _arith_method_FRAME(cls, op, special): str_rep = _get_opstr(op, cls) - name = _get_op_name(op, special) - eval_kwargs = _gen_eval_kwargs(name) - fill_zeros = _gen_fill_zeros(name) - default_axis = _get_frame_op_default_axis(name) + op_name = _get_op_name(op, special) + eval_kwargs = _gen_eval_kwargs(op_name) + fill_zeros = _gen_fill_zeros(op_name) + default_axis = _get_frame_op_default_axis(op_name) def na_op(x, y): import pandas.core.computation.expressions as expressions @@ -1443,7 +1443,7 @@ def na_op(x, y): except TypeError: xrav = x.ravel() if isinstance(y, (np.ndarray, ABCSeries)): - dtype = np.find_common_type([x.dtype, y.dtype], []) + dtype = find_common_type([x.dtype, y.dtype]) result = np.empty(x.size, dtype=dtype) yrav = y.ravel() mask = notna(xrav) & notna(yrav) @@ -1471,20 +1471,20 @@ def na_op(x, y): else: raise TypeError("cannot perform operation {op} between " "objects of type {x} and {y}" - .format(op=name, x=type(x), y=type(y))) + .format(op=op_name, x=type(x), y=type(y))) result, changed = maybe_upcast_putmask(result, ~mask, np.nan) result = result.reshape(x.shape) - result = missing.fill_zeros(result, x, y, name, fill_zeros) + result = missing.fill_zeros(result, x, y, op_name, fill_zeros) return result - if name in _op_descriptions: + if op_name in _op_descriptions: # i.e. include "add" but not "__add__" - doc = _make_flex_doc(name, 'dataframe') + doc = _make_flex_doc(op_name, 'dataframe') else: - doc = _arith_doc_FRAME % name + doc = _arith_doc_FRAME % op_name @Appender(doc) def f(self, other, axis=default_axis, level=None, fill_value=None): @@ -1503,15 +1503,15 @@ def f(self, other, axis=default_axis, level=None, fill_value=None): return self._combine_const(other, na_op, try_cast=True) - f.__name__ = name + f.__name__ = op_name return f def _flex_comp_method_FRAME(cls, op, special): str_rep = _get_opstr(op, cls) - name = _get_op_name(op, special) - default_axis = _get_frame_op_default_axis(name) + op_name = _get_op_name(op, special) + default_axis = _get_frame_op_default_axis(op_name) def na_op(x, y): try: @@ -1522,7 +1522,7 @@ def na_op(x, y): return result @Appender('Wrapper for flexible comparison methods {name}' - .format(name=name)) + .format(name=op_name)) def f(self, other, axis=default_axis, level=None): other = _align_method_FRAME(self, other, axis) @@ -1541,16 +1541,16 @@ def f(self, other, axis=default_axis, level=None): else: return self._combine_const(other, na_op, try_cast=False) - f.__name__ = name + f.__name__ = op_name return f def _comp_method_FRAME(cls, func, special): str_rep = _get_opstr(func, cls) - name = _get_op_name(func, special) + op_name = _get_op_name(func, special) - @Appender('Wrapper for comparison method {name}'.format(name=name)) + @Appender('Wrapper for comparison method {name}'.format(name=op_name)) def f(self, other): if isinstance(other, ABCDataFrame): # Another DataFrame @@ -1572,7 +1572,7 @@ def f(self, other): try_cast=False) return res.fillna(True).astype(bool) - f.__name__ = name + f.__name__ = op_name return f @@ -1582,7 +1582,7 @@ def f(self, other): def _arith_method_PANEL(cls, op, special): # work only for scalars - name = _get_op_name(op, special) + op_name = _get_op_name(op, special) def f(self, other): if not is_scalar(other): @@ -1592,13 +1592,13 @@ def f(self, other): return self._combine(other, op) - f.__name__ = name + f.__name__ = op_name return f def _comp_method_PANEL(cls, op, special): str_rep = _get_opstr(op, cls) - name = _get_op_name(op, special) + op_name = _get_op_name(op, special) def na_op(x, y): import pandas.core.computation.expressions as expressions @@ -1609,7 +1609,7 @@ def na_op(x, y): result = mask_cmp_op(x, y, op, np.ndarray) return result - @Appender('Wrapper for comparison method {name}'.format(name=name)) + @Appender('Wrapper for comparison method {name}'.format(name=op_name)) def f(self, other, axis=None): # Validate the axis parameter if axis is not None: @@ -1624,16 +1624,16 @@ def f(self, other, axis=None): else: return self._combine_const(other, na_op, try_cast=False) - f.__name__ = name + f.__name__ = op_name return f def _flex_method_PANEL(cls, op, special): str_rep = _get_opstr(op, cls) - name = _get_op_name(op, special) - eval_kwargs = _gen_eval_kwargs(name) - fill_zeros = _gen_fill_zeros(name) + op_name = _get_op_name(op, special) + eval_kwargs = _gen_eval_kwargs(op_name) + fill_zeros = _gen_fill_zeros(op_name) def na_op(x, y): import pandas.core.computation.expressions as expressions @@ -1648,20 +1648,20 @@ def na_op(x, y): # handles discrepancy between numpy and numexpr on division/mod # by 0 though, given that these are generally (always?) # non-scalars, I'm not sure whether it's worth it at the moment - result = missing.fill_zeros(result, x, y, name, fill_zeros) + result = missing.fill_zeros(result, x, y, op_name, fill_zeros) return result - if name in _op_descriptions: - doc = _make_flex_doc(name, 'panel') + if op_name in _op_descriptions: + doc = _make_flex_doc(op_name, 'panel') else: # doc strings substitors - doc = _agg_doc_PANEL.format(op_name=name) + doc = _agg_doc_PANEL.format(op_name=op_name) @Appender(doc) def f(self, other, axis=0): return self._combine(other, na_op, axis=axis) - f.__name__ = name + f.__name__ = op_name return f @@ -1703,7 +1703,7 @@ def _arith_method_SPARSE_SERIES(cls, op, special): Wrapper function for Series arithmetic operations, to avoid code duplication. """ - name = _get_op_name(op, special) + op_name = _get_op_name(op, special) def wrapper(self, other): if isinstance(other, ABCDataFrame): @@ -1711,7 +1711,7 @@ def wrapper(self, other): elif isinstance(other, ABCSeries): if not isinstance(other, ABCSparseSeries): other = other.to_sparse(fill_value=self.fill_value) - return _sparse_series_op(self, other, op, name) + return _sparse_series_op(self, other, op, op_name) elif is_scalar(other): with np.errstate(all='ignore'): new_values = op(self.values, other) @@ -1722,7 +1722,7 @@ def wrapper(self, other): raise TypeError('operation with {other} not supported' .format(other=type(other))) - wrapper.__name__ = name + wrapper.__name__ = op_name return wrapper @@ -1742,7 +1742,7 @@ def _arith_method_SPARSE_ARRAY(cls, op, special): Wrapper function for Series arithmetic operations, to avoid code duplication. """ - name = _get_op_name(op, special) + op_name = _get_op_name(op, special) def wrapper(self, other): from pandas.core.sparse.array import ( @@ -1755,16 +1755,16 @@ def wrapper(self, other): dtype = getattr(other, 'dtype', None) other = SparseArray(other, fill_value=self.fill_value, dtype=dtype) - return _sparse_array_op(self, other, op, name) + return _sparse_array_op(self, other, op, op_name) elif is_scalar(other): with np.errstate(all='ignore'): fill = op(_get_fill(self), np.asarray(other)) result = op(self.sp_values, other) - return _wrap_result(name, result, self.sp_index, fill) + return _wrap_result(op_name, result, self.sp_index, fill) else: # pragma: no cover raise TypeError('operation with {other} not supported' .format(other=type(other))) - wrapper.__name__ = name + wrapper.__name__ = op_name return wrapper
Consistently use `op_name` and `res_name` and avoid `name` Use find_common_type instead of np.find_common_type, moving towards de-duping Series/Frame code.
https://api.github.com/repos/pandas-dev/pandas/pulls/19972
2018-03-02T19:45:30Z
2018-03-07T14:19:22Z
2018-03-07T14:19:22Z
2018-06-22T03:32:10Z
DOC: clarify version of ActivePython that includes pandas
diff --git a/doc/source/install.rst b/doc/source/install.rst index e3667221e5166..07f57dbd65709 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -137,7 +137,10 @@ pandas can be installed via pip from Installing with ActivePython ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Installation instructions for `ActivePython <https://www.activestate.com/activepython>`__ can be found `here <https://www.activestate.com/activepython/downloads>`__. +Installation instructions for +`ActivePython <https://www.activestate.com/activepython>`__ can be found +`here <https://www.activestate.com/activepython/downloads>`__. Versions +2.7 and 3.5 include pandas. Installing using your Linux distribution's package manager. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -303,5 +306,5 @@ Optional Dependencies Without the optional dependencies, many useful features will not work. Hence, it is highly recommended that you install these. A packaged - distribution like `Anaconda <http://docs.continuum.io/anaconda/>`__, `ActivePython <https://www.activestate.com/activepython/downloads>`__, or `Enthought Canopy + distribution like `Anaconda <http://docs.continuum.io/anaconda/>`__, `ActivePython <https://www.activestate.com/activepython/downloads>`__ (version 2.7 or 3.5), or `Enthought Canopy <http://enthought.com/products/canopy>`__ may be worth considering.
Follow-up on https://github.com/pandas-dev/pandas/pull/19908 cc @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/19964
2018-03-02T12:42:21Z
2018-03-02T12:50:00Z
2018-03-02T12:50:00Z
2018-03-02T12:50:52Z
DOC: fix some sphinx syntax warnings
diff --git a/doc/source/merging.rst b/doc/source/merging.rst index 4d9746eed0f0b..cfd3f9e88e4ea 100644 --- a/doc/source/merging.rst +++ b/doc/source/merging.rst @@ -152,7 +152,7 @@ functionality below. Set logic on the other axes ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -When gluing together multiple ``DataFrame``s, you have a choice of how to handle +When gluing together multiple DataFrames, you have a choice of how to handle the other axes (other than the one being concatenated). This can be done in the following three ways: @@ -636,7 +636,7 @@ key combination: Here is a more complicated example with multiple join keys. Only the keys appearing in ``left`` and ``right`` are present (the intersection), since -``how='inner'```by default. +``how='inner'`` by default. .. ipython:: python @@ -721,7 +721,7 @@ either the left or right tables, the values in the joined table will be labels=['left', 'right'], vertical=False); plt.close('all'); -Here is another example with duplicate join keys in ``DataFrame``s: +Here is another example with duplicate join keys in DataFrames: .. ipython:: python diff --git a/doc/source/tutorials.rst b/doc/source/tutorials.rst index 0398e2892cef5..85e455de7d246 100644 --- a/doc/source/tutorials.rst +++ b/doc/source/tutorials.rst @@ -180,13 +180,13 @@ Video Tutorials - `Pandas From The Ground Up <https://www.youtube.com/watch?v=5JnMutdy6Fw>`_ (2015) (2:24) - `GitHub repo <https://github.com/brandon-rhodes/pycon-pandas-tutorial>`_ + `GitHub repo <https://github.com/brandon-rhodes/pycon-pandas-tutorial>`__ - `Introduction Into Pandas <https://www.youtube.com/watch?v=-NR-ynQg0YM>`_ (2016) (1:28) - `GitHub repo <https://github.com/chendaniely/2016-pydata-carolinas-pandas>`_ + `GitHub repo <https://github.com/chendaniely/2016-pydata-carolinas-pandas>`__ - `Pandas: .head() to .tail() <https://www.youtube.com/watch?v=7vuO9QXDN50>`_ (2016) (1:26) - `GitHub repo <https://github.com/TomAugspurger/pydata-chi-h2t>`_ + `GitHub repo <https://github.com/TomAugspurger/pydata-chi-h2t>`__ Various Tutorials diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst index ee93f06fbc958..09a52ee527cb5 100644 --- a/doc/source/visualization.rst +++ b/doc/source/visualization.rst @@ -870,7 +870,7 @@ Andrews Curves Andrews curves allow one to plot multivariate data as a large number of curves that are created using the attributes of samples as coefficients -for Fourier series, see the `Wikipedia entry<https://en.wikipedia.org/wiki/Andrews_plot>`_ +for Fourier series, see the `Wikipedia entry <https://en.wikipedia.org/wiki/Andrews_plot>`__ for more information. By coloring these curves differently for each class it is possible to visualize data clustering. Curves belonging to samples of the same class will usually be closer together and form larger structures. @@ -894,7 +894,7 @@ Parallel Coordinates ~~~~~~~~~~~~~~~~~~~~ Parallel coordinates is a plotting technique for plotting multivariate data, -see the `Wikipedia entry<https://en.wikipedia.org/wiki/Parallel_coordinates>`_ +see the `Wikipedia entry <https://en.wikipedia.org/wiki/Parallel_coordinates>`__ for an introduction. Parallel coordinates allows one to see clusters in data and to estimate other statistics visually. Using parallel coordinates points are represented as connected line segments. @@ -962,7 +962,7 @@ all time-lag separations. If time series is non-random then one or more of the autocorrelations will be significantly non-zero. The horizontal lines displayed in the plot correspond to 95% and 99% confidence bands. The dashed line is 99% confidence band. See the -`Wikipedia entry<https://en.wikipedia.org/wiki/Correlogram>`_ for more about +`Wikipedia entry <https://en.wikipedia.org/wiki/Correlogram>`__ for more about autocorrelation plots. .. ipython:: python @@ -1032,7 +1032,7 @@ unit interval). The point in the plane, where our sample settles to (where the forces acting on our sample are at an equilibrium) is where a dot representing our sample will be drawn. Depending on which class that sample belongs it will be colored differently. -See the R package `Radviz<https://cran.r-project.org/web/packages/Radviz/>`_ +See the R package `Radviz <https://cran.r-project.org/web/packages/Radviz/>`__ for more information. **Note**: The "Iris" dataset is available `here <https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/iris.csv>`__. diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 7a19f87051746..c3927a796a625 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -117,7 +117,7 @@ resetting indexes. See the :ref:`Sorting by Indexes and Values # Sort by 'second' (index) and 'A' (column) df_multi.sort_values(by=['second', 'A']) -.. _whatsnew_0230.enhancements.timedelta_mod +.. _whatsnew_0230.enhancements.timedelta_mod: Timedelta mod method ^^^^^^^^^^^^^^^^^^^^ @@ -705,7 +705,7 @@ Removal of prior version deprecations/changes - The ``Panel4D`` and ``PanelND`` classes have been removed (:issue:`13776`) - The ``Panel`` class has dropped the ``to_long`` and ``toLong`` methods (:issue:`19077`) - The options ``display.line_with`` and ``display.height`` are removed in favor of ``display.width`` and ``display.max_rows`` respectively (:issue:`4391`, :issue:`19107`) -- The ``labels`` attribute of the ``Categorical`` class has been removed in favor of :attribute:`Categorical.codes` (:issue:`7768`) +- The ``labels`` attribute of the ``Categorical`` class has been removed in favor of :attr:`Categorical.codes` (:issue:`7768`) - The ``flavor`` parameter have been removed from func:`to_sql` method (:issue:`13611`) - The modules ``pandas.tools.hashing`` and ``pandas.util.hashing`` have been removed (:issue:`16223`) - The top-level functions ``pd.rolling_*``, ``pd.expanding_*`` and ``pd.ewm*`` have been removed (Deprecated since v0.18). diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ae8fb48a61fce..b42343bbd8077 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -116,8 +116,8 @@ - if `axis` is 1 or `'columns'` then `by` may contain column levels and/or index labels - .. versionchanged:: 0.23.0 - Allow specifying index or column level names.""", + .. versionchanged:: 0.23.0 + Allow specifying index or column level names.""", versionadded_to_excel='', optional_labels="""labels : array-like, optional New labels / index to conform the axis specified by 'axis' to.""", diff --git a/pandas/core/window.py b/pandas/core/window.py index a3f19ef50459d..417888ce80b46 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -416,11 +416,11 @@ class Window(_Window): A ragged (meaning not-a-regular frequency), time-indexed DataFrame >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}, - ....: index = [pd.Timestamp('20130101 09:00:00'), - ....: pd.Timestamp('20130101 09:00:02'), - ....: pd.Timestamp('20130101 09:00:03'), - ....: pd.Timestamp('20130101 09:00:05'), - ....: pd.Timestamp('20130101 09:00:06')]) + ... index = [pd.Timestamp('20130101 09:00:00'), + ... pd.Timestamp('20130101 09:00:02'), + ... pd.Timestamp('20130101 09:00:03'), + ... pd.Timestamp('20130101 09:00:05'), + ... pd.Timestamp('20130101 09:00:06')]) >>> df B diff --git a/pandas/io/json/json.py b/pandas/io/json/json.py index 24364fe07405e..1627b2f4d3ec3 100644 --- a/pandas/io/json/json.py +++ b/pandas/io/json/json.py @@ -348,7 +348,7 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True, to denote a missing :class:`Index` name, and the subsequent :func:`read_json` operation cannot distinguish between the two. The same limitation is encountered with a :class:`MultiIndex` and any names - beginning with 'level_'. + beginning with ``'level_'``. See Also --------
https://api.github.com/repos/pandas-dev/pandas/pulls/19962
2018-03-02T10:44:29Z
2018-03-02T21:33:49Z
2018-03-02T21:33:49Z
2018-03-02T21:33:54Z
DOC: update docstring validation script
diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py index 7807785c24751..a90a55c6ce1ab 100755 --- a/scripts/validate_docstrings.py +++ b/scripts/validate_docstrings.py @@ -23,7 +23,7 @@ import inspect import importlib import doctest -import textwrap +import pydoc try: from io import StringIO except ImportError: @@ -39,6 +39,9 @@ from numpydoc.docscrape import NumpyDocString +PRIVATE_CLASSES = ['NDFrame', 'IndexOpsMixin'] + + def _to_original_callable(obj): while True: if inspect.isfunction(obj) or inspect.isclass(obj): @@ -72,8 +75,7 @@ class Docstring: def __init__(self, method_name, method_obj): self.method_name = method_name self.method_obj = method_obj - self.raw_doc = method_obj.__doc__ or '' - self.raw_doc = textwrap.dedent(self.raw_doc) + self.raw_doc = pydoc.getdoc(method_obj) self.doc = NumpyDocString(self.raw_doc) def __len__(self): @@ -127,7 +129,12 @@ def doc_parameters(self): @property def signature_parameters(self): - if not inspect.isfunction(self.method_obj): + if not (inspect.isfunction(self.method_obj) + or inspect.isclass(self.method_obj)): + return tuple() + if (inspect.isclass(self.method_obj) + and self.method_name.split('.')[-1] in {'dt', 'str', 'cat'}): + # accessor classes have a signature, but don't want to show this return tuple() params = tuple(inspect.signature(self.method_obj).parameters.keys()) if params and params[0] in ('self', 'cls'): @@ -149,7 +156,8 @@ def parameter_mismatches(self): extra = set(doc_params) - set(signature_params) if extra: errs.append('Unknown parameters {!r}'.format(extra)) - if not missing and not extra and signature_params != doc_params: + if (not missing and not extra and signature_params != doc_params + and not (not signature_params and not doc_params)): errs.append('Wrong parameters order. ' + 'Actual: {!r}. '.format(signature_params) + 'Documented: {!r}'.format(doc_params)) @@ -180,6 +188,10 @@ def deprecated(self): bool(pattern.search(self.summary)) or bool(pattern.search(self.extended_summary))) + @property + def mentioned_private_classes(self): + return [klass for klass in PRIVATE_CLASSES if klass in self.raw_doc] + @property def examples_errors(self): flags = doctest.NORMALIZE_WHITESPACE | doctest.IGNORE_EXCEPTION_DETAIL @@ -311,6 +323,11 @@ def validate_one(func_name): for param_err in param_errs: errs.append('\t{}'.format(param_err)) + mentioned_errs = doc.mentioned_private_classes + if mentioned_errs: + errs.append('Private classes ({}) should not be mentioned in public ' + 'docstring.'.format(mentioned_errs)) + examples_errs = '' if not doc.examples: errs.append('No examples section found')
Follow-up on https://github.com/pandas-dev/pandas/pull/19898 cc @datapythonista
https://api.github.com/repos/pandas-dev/pandas/pulls/19960
2018-03-02T10:32:57Z
2018-03-02T21:18:10Z
2018-03-02T21:18:10Z
2018-03-02T21:18:24Z
Implement integer array add/sub for datetimelike indexes
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index b94377af770f4..58dee1c20ee57 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -22,6 +22,13 @@ Other Enhancements Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. _whatsnew_0240.api.datetimelike: + +Datetimelike API Changes +^^^^^^^^^^^^^^^^^^^^^^^^ + +- For :class:`DatetimeIndex` and :class:`TimedeltaIndex` with non-``None`` ``freq`` attribute, addition or subtraction of integer-dtyped array or ``Index`` will return an object of the same class (:issue:`19959`) + .. _whatsnew_0240.api.other: Other API Changes diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 158b272384ae8..c7cb245263df8 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -12,7 +12,7 @@ import numpy as np -from pandas._libs import lib, iNaT, NaT +from pandas._libs import lib, iNaT, NaT, Timedelta from pandas._libs.tslibs.period import Period from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds from pandas._libs.tslibs.timestamps import round_ns @@ -34,6 +34,7 @@ is_string_dtype, is_datetime64_dtype, is_datetime64tz_dtype, + is_datetime64_any_dtype, is_period_dtype, is_timedelta64_dtype) from pandas.core.dtypes.generic import ( @@ -814,6 +815,46 @@ def _addsub_offset_array(self, other, op): kwargs['freq'] = 'infer' return self._constructor(res_values, **kwargs) + def _addsub_int_array(self, other, op): + """ + Add or subtract array-like of integers equivalent to applying + `shift` pointwise. + + Parameters + ---------- + other : Index, np.ndarray + integer-dtype + op : {operator.add, operator.sub} + + Returns + ------- + result : same class as self + """ + assert op in [operator.add, operator.sub] + if is_period_dtype(self): + # easy case for PeriodIndex + if op is operator.sub: + other = -other + res_values = checked_add_with_arr(self.asi8, other, + arr_mask=self._isnan) + res_values = res_values.view('i8') + res_values[self._isnan] = iNaT + return self._from_ordinals(res_values, freq=self.freq) + + elif self.freq is None: + # GH#19123 + raise NullFrequencyError("Cannot shift with no freq") + + elif isinstance(self.freq, Tick): + # easy case where we can convert to timedelta64 operation + td = Timedelta(self.freq) + return op(self, td * other) + + # We should only get here with DatetimeIndex; dispatch + # to _addsub_offset_array + assert not is_timedelta64_dtype(self) + return op(self, np.array(other) * self.freq) + @classmethod def _add_datetimelike_methods(cls): """ @@ -822,8 +863,6 @@ def _add_datetimelike_methods(cls): """ def __add__(self, other): - from pandas import DateOffset - other = lib.item_from_zerodim(other) if isinstance(other, (ABCSeries, ABCDataFrame)): return NotImplemented @@ -853,9 +892,8 @@ def __add__(self, other): elif is_datetime64_dtype(other) or is_datetime64tz_dtype(other): # DatetimeIndex, ndarray[datetime64] return self._add_datelike(other) - elif is_integer_dtype(other) and self.freq is None: - # GH#19123 - raise NullFrequencyError("Cannot shift with no freq") + elif is_integer_dtype(other): + result = self._addsub_int_array(other, operator.add) elif is_float_dtype(other): # Explicitly catch invalid dtypes raise TypeError("cannot add {dtype}-dtype to {cls}" @@ -915,14 +953,12 @@ def __sub__(self, other): elif is_datetime64_dtype(other) or is_datetime64tz_dtype(other): # DatetimeIndex, ndarray[datetime64] result = self._sub_datelike(other) + elif is_integer_dtype(other): + result = self._addsub_int_array(other, operator.sub) elif isinstance(other, Index): raise TypeError("cannot subtract {cls} and {typ}" .format(cls=type(self).__name__, typ=type(other).__name__)) - elif is_integer_dtype(other) and self.freq is None: - # GH#19123 - raise NullFrequencyError("Cannot shift with no freq") - elif is_float_dtype(other): # Explicitly catch invalid dtypes raise TypeError("cannot subtract {dtype}-dtype from {cls}" @@ -948,6 +984,13 @@ def __rsub__(self, other): # we need to wrap in DatetimeIndex and flip the operation from pandas import DatetimeIndex return DatetimeIndex(other) - self + elif (is_datetime64_any_dtype(self) and hasattr(other, 'dtype') and + not is_datetime64_any_dtype(other)): + # GH#19959 datetime - datetime is well-defined as timedelta, + # but any other type - datetime is not well-defined. + raise TypeError("cannot subtract {cls} from {typ}" + .format(cls=type(self).__name__, + typ=type(other).__name__)) return -(self - other) cls.__rsub__ = __rsub__ diff --git a/pandas/tests/indexes/datetimes/test_arithmetic.py b/pandas/tests/indexes/datetimes/test_arithmetic.py index 4ef7997a53b85..eff2872a1cff3 100644 --- a/pandas/tests/indexes/datetimes/test_arithmetic.py +++ b/pandas/tests/indexes/datetimes/test_arithmetic.py @@ -367,6 +367,49 @@ def test_dti_isub_int(self, tz, one): rng -= one tm.assert_index_equal(rng, expected) + # ------------------------------------------------------------- + # __add__/__sub__ with integer arrays + + @pytest.mark.parametrize('freq', ['H', 'D']) + @pytest.mark.parametrize('box', [np.array, pd.Index]) + def test_dti_add_intarray_tick(self, box, freq): + # GH#19959 + dti = pd.date_range('2016-01-01', periods=2, freq=freq) + other = box([4, -1]) + expected = DatetimeIndex([dti[n] + other[n] for n in range(len(dti))]) + result = dti + other + tm.assert_index_equal(result, expected) + result = other + dti + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize('freq', ['W', 'M', 'MS', 'Q']) + @pytest.mark.parametrize('box', [np.array, pd.Index]) + def test_dti_add_intarray_non_tick(self, box, freq): + # GH#19959 + dti = pd.date_range('2016-01-01', periods=2, freq=freq) + other = box([4, -1]) + expected = DatetimeIndex([dti[n] + other[n] for n in range(len(dti))]) + with tm.assert_produces_warning(PerformanceWarning): + result = dti + other + tm.assert_index_equal(result, expected) + with tm.assert_produces_warning(PerformanceWarning): + result = other + dti + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize('box', [np.array, pd.Index]) + def test_dti_add_intarray_no_freq(self, box): + # GH#19959 + dti = pd.DatetimeIndex(['2016-01-01', 'NaT', '2017-04-05 06:07:08']) + other = box([9, 4, -1]) + with pytest.raises(NullFrequencyError): + dti + other + with pytest.raises(NullFrequencyError): + other + dti + with pytest.raises(NullFrequencyError): + dti - other + with pytest.raises(TypeError): + other - dti + # ------------------------------------------------------------- # DatetimeIndex.shift is used in integer addition @@ -528,7 +571,7 @@ def test_dti_sub_tdi(self, tz): result = dti - tdi.values tm.assert_index_equal(result, expected) - msg = 'cannot perform __neg__ with this index type:' + msg = 'cannot subtract DatetimeIndex from' with tm.assert_raises_regex(TypeError, msg): tdi.values - dti @@ -553,7 +596,8 @@ def test_dti_isub_tdi(self, tz): tm.assert_index_equal(result, expected) msg = '|'.join(['cannot perform __neg__ with this index type:', - 'ufunc subtract cannot use operands with types']) + 'ufunc subtract cannot use operands with types', + 'cannot subtract DatetimeIndex from']) with tm.assert_raises_regex(TypeError, msg): tdi.values -= dti diff --git a/pandas/tests/indexes/period/test_arithmetic.py b/pandas/tests/indexes/period/test_arithmetic.py index c75fdd35a974c..aea019d910fe0 100644 --- a/pandas/tests/indexes/period/test_arithmetic.py +++ b/pandas/tests/indexes/period/test_arithmetic.py @@ -449,6 +449,31 @@ def test_pi_sub_isub_offset(self): rng -= pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected) + # --------------------------------------------------------------- + # __add__/__sub__ with integer arrays + + @pytest.mark.parametrize('box', [np.array, pd.Index]) + @pytest.mark.parametrize('op', [operator.add, ops.radd]) + def test_pi_add_intarray(self, box, op): + # GH#19959 + pi = pd.PeriodIndex([pd.Period('2015Q1'), pd.Period('NaT')]) + other = box([4, -1]) + result = op(pi, other) + expected = pd.PeriodIndex([pd.Period('2016Q1'), pd.Period('NaT')]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize('box', [np.array, pd.Index]) + def test_pi_sub_intarray(self, box): + # GH#19959 + pi = pd.PeriodIndex([pd.Period('2015Q1'), pd.Period('NaT')]) + other = box([4, -1]) + result = pi - other + expected = pd.PeriodIndex([pd.Period('2014Q1'), pd.Period('NaT')]) + tm.assert_index_equal(result, expected) + + with pytest.raises(TypeError): + other - pi + # --------------------------------------------------------------- # Timedelta-like (timedelta, timedelta64, Timedelta, Tick) # TODO: Some of these are misnomers because of non-Tick DateOffsets diff --git a/pandas/tests/indexes/timedeltas/test_arithmetic.py b/pandas/tests/indexes/timedeltas/test_arithmetic.py index 9035434046ccb..786ff5cde1806 100644 --- a/pandas/tests/indexes/timedeltas/test_arithmetic.py +++ b/pandas/tests/indexes/timedeltas/test_arithmetic.py @@ -542,6 +542,45 @@ def test_tdi_isub_int(self, one): rng -= one tm.assert_index_equal(rng, expected) + # ------------------------------------------------------------- + # __add__/__sub__ with integer arrays + + @pytest.mark.parametrize('box', [np.array, pd.Index]) + def test_tdi_add_integer_array(self, box): + # GH#19959 + rng = timedelta_range('1 days 09:00:00', freq='H', periods=3) + other = box([4, 3, 2]) + expected = TimedeltaIndex(['1 day 13:00:00'] * 3) + result = rng + other + tm.assert_index_equal(result, expected) + result = other + rng + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize('box', [np.array, pd.Index]) + def test_tdi_sub_integer_array(self, box): + # GH#19959 + rng = timedelta_range('9H', freq='H', periods=3) + other = box([4, 3, 2]) + expected = TimedeltaIndex(['5H', '7H', '9H']) + result = rng - other + tm.assert_index_equal(result, expected) + result = other - rng + tm.assert_index_equal(result, -expected) + + @pytest.mark.parametrize('box', [np.array, pd.Index]) + def test_tdi_addsub_integer_array_no_freq(self, box): + # GH#19959 + tdi = TimedeltaIndex(['1 Day', 'NaT', '3 Hours']) + other = box([14, -1, 16]) + with pytest.raises(NullFrequencyError): + tdi + other + with pytest.raises(NullFrequencyError): + other + tdi + with pytest.raises(NullFrequencyError): + tdi - other + with pytest.raises(NullFrequencyError): + other - tdi + # ------------------------------------------------------------- # Binary operations TimedeltaIndex and timedelta-like
AFAICT this is the next-to-last non-raising case for these operations. After this is just object-dtype, and for that we already have the correct implementation in addsub_offset_array, just need to make the condition less strict and add appropriate tests. - [ ] closes #xxxx - [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/19959
2018-03-02T05:55:58Z
2018-05-29T01:42:55Z
2018-05-29T01:42:55Z
2018-05-29T03:47:37Z
ENH: Sorting of ExtensionArrays
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index fa565aa802faf..f4c77263bf21b 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -2,6 +2,7 @@ import numpy as np from pandas.errors import AbstractMethodError +from pandas.compat.numpy import function as nv _not_implemented_message = "{} does not implement {}." @@ -236,6 +237,57 @@ def isna(self): """ raise AbstractMethodError(self) + def _values_for_argsort(self): + # type: () -> ndarray + """Return values for sorting. + + Returns + ------- + ndarray + The transformed values should maintain the ordering between values + within the array. + + See Also + -------- + ExtensionArray.argsort + """ + # Note: this is used in `ExtensionArray.argsort`. + return np.array(self) + + def argsort(self, ascending=True, kind='quicksort', *args, **kwargs): + """ + Return the indices that would sort this array. + + Parameters + ---------- + ascending : bool, default True + Whether the indices should result in an ascending + or descending sort. + kind : {'quicksort', 'mergesort', 'heapsort'}, optional + Sorting algorithm. + *args, **kwargs: + passed through to :func:`numpy.argsort`. + + Returns + ------- + index_array : ndarray + Array of indices that sort ``self``. + + See Also + -------- + numpy.argsort : Sorting implementation used internally. + """ + # Implementor note: You have two places to override the behavior of + # argsort. + # 1. _values_for_argsort : construct the values passed to np.argsort + # 2. argsort : total control over sorting. + ascending = nv.validate_argsort_with_ascending(ascending, args, kwargs) + values = self._values_for_argsort() + result = np.argsort(values, kind=kind, **kwargs) + if not ascending: + result = result[::-1] + return result + def fillna(self, value=None, method=None, limit=None): """ Fill NA/NaN values using the specified method. diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index e7d414f9de544..13384dd56a9c1 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1378,17 +1378,24 @@ def check_for_ordered(self, op): "you can use .as_ordered() to change the " "Categorical to an ordered one\n".format(op=op)) - def argsort(self, ascending=True, kind='quicksort', *args, **kwargs): - """ - Returns the indices that would sort the Categorical instance if - 'sort_values' was called. This function is implemented to provide - compatibility with numpy ndarray objects. + def _values_for_argsort(self): + return self._codes.copy() - While an ordering is applied to the category values, arg-sorting - in this context refers more to organizing and grouping together - based on matching category values. Thus, this function can be - called on an unordered Categorical instance unlike the functions - 'Categorical.min' and 'Categorical.max'. + def argsort(self, *args, **kwargs): + # TODO(PY2): use correct signature + # We have to do *args, **kwargs to avoid a a py2-only signature + # issue since np.argsort differs from argsort. + """Return the indicies that would sort the Categorical. + + Parameters + ---------- + ascending : bool, default True + Whether the indices should result in an ascending + or descending sort. + kind : {'quicksort', 'mergesort', 'heapsort'}, optional + Sorting algorithm. + *args, **kwargs: + passed through to :func:`numpy.argsort`. Returns ------- @@ -1397,12 +1404,28 @@ def argsort(self, ascending=True, kind='quicksort', *args, **kwargs): See also -------- numpy.ndarray.argsort + + Notes + ----- + While an ordering is applied to the category values, arg-sorting + in this context refers more to organizing and grouping together + based on matching category values. Thus, this function can be + called on an unordered Categorical instance unlike the functions + 'Categorical.min' and 'Categorical.max'. + + Examples + -------- + >>> pd.Categorical(['b', 'b', 'a', 'c']).argsort() + array([2, 0, 1, 3]) + + >>> cat = pd.Categorical(['b', 'b', 'a', 'c'], + ... categories=['c', 'b', 'a'], + ... ordered=True) + >>> cat.argsort() + array([3, 0, 1, 2]) """ - ascending = nv.validate_argsort_with_ascending(ascending, args, kwargs) - result = np.argsort(self._codes.copy(), kind=kind, **kwargs) - if not ascending: - result = result[::-1] - return result + # Keep the implementation here just for the docstring. + return super(Categorical, self).argsort(*args, **kwargs) def sort_values(self, inplace=False, ascending=True, na_position='last'): """ Sorts the Categorical by category value returning a new diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index 7ce80e25d8cf6..4d467d62d0a56 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -32,6 +32,46 @@ def test_apply_simple_series(self, data): result = pd.Series(data).apply(id) assert isinstance(result, pd.Series) + def test_argsort(self, data_for_sorting): + result = pd.Series(data_for_sorting).argsort() + expected = pd.Series(np.array([2, 0, 1], dtype=np.int64)) + self.assert_series_equal(result, expected) + + def test_argsort_missing(self, data_missing_for_sorting): + result = pd.Series(data_missing_for_sorting).argsort() + expected = pd.Series(np.array([1, -1, 0], dtype=np.int64)) + self.assert_series_equal(result, expected) + + @pytest.mark.parametrize('ascending', [True, False]) + def test_sort_values(self, data_for_sorting, ascending): + ser = pd.Series(data_for_sorting) + result = ser.sort_values(ascending=ascending) + expected = ser.iloc[[2, 0, 1]] + if not ascending: + expected = expected[::-1] + + self.assert_series_equal(result, expected) + + @pytest.mark.parametrize('ascending', [True, False]) + def test_sort_values_missing(self, data_missing_for_sorting, ascending): + ser = pd.Series(data_missing_for_sorting) + result = ser.sort_values(ascending=ascending) + if ascending: + expected = ser.iloc[[2, 0, 1]] + else: + expected = ser.iloc[[0, 2, 1]] + self.assert_series_equal(result, expected) + + @pytest.mark.parametrize('ascending', [True, False]) + def test_sort_values_frame(self, data_for_sorting, ascending): + df = pd.DataFrame({"A": [1, 2, 1], + "B": data_for_sorting}) + result = df.sort_values(['A', 'B']) + expected = pd.DataFrame({"A": [1, 1, 2], + 'B': data_for_sorting.take([2, 0, 1])}, + index=[2, 0, 1]) + self.assert_frame_equal(result, expected) + @pytest.mark.parametrize('box', [pd.Series, lambda x: x]) @pytest.mark.parametrize('method', [lambda x: x.unique(), pd.unique]) def test_unique(self, data, box, method): diff --git a/pandas/tests/extension/category/test_categorical.py b/pandas/tests/extension/category/test_categorical.py index b6dd181c1d8f3..b602d9ee78e2a 100644 --- a/pandas/tests/extension/category/test_categorical.py +++ b/pandas/tests/extension/category/test_categorical.py @@ -29,6 +29,18 @@ def data_missing(): return Categorical([np.nan, 'A']) +@pytest.fixture +def data_for_sorting(): + return Categorical(['A', 'B', 'C'], categories=['C', 'A', 'B'], + ordered=True) + + +@pytest.fixture +def data_missing_for_sorting(): + return Categorical(['A', None, 'B'], categories=['B', 'A'], + ordered=True) + + @pytest.fixture def na_value(): return np.nan diff --git a/pandas/tests/extension/conftest.py b/pandas/tests/extension/conftest.py index 21ed8894e8ebb..04dfb408fc378 100644 --- a/pandas/tests/extension/conftest.py +++ b/pandas/tests/extension/conftest.py @@ -30,6 +30,26 @@ def all_data(request, data, data_missing): return data_missing +@pytest.fixture +def data_for_sorting(): + """Length-3 array with a known sort order. + + This should be three items [B, C, A] with + A < B < C + """ + raise NotImplementedError + + +@pytest.fixture +def data_missing_for_sorting(): + """Length-3 array with a known sort order. + + This should be three items [B, NA, A] with + A < B and NA missing. + """ + raise NotImplementedError + + @pytest.fixture def na_cmp(): """Binary operator for comparing NA values. diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 4c6ef9b4d38c8..7d959ea4fcd84 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -25,6 +25,20 @@ def data_missing(): return DecimalArray([decimal.Decimal('NaN'), decimal.Decimal(1)]) +@pytest.fixture +def data_for_sorting(): + return DecimalArray([decimal.Decimal('1'), + decimal.Decimal('2'), + decimal.Decimal('0')]) + + +@pytest.fixture +def data_missing_for_sorting(): + return DecimalArray([decimal.Decimal('1'), + decimal.Decimal('NaN'), + decimal.Decimal('0')]) + + @pytest.fixture def na_cmp(): return lambda x, y: x.is_nan() and y.is_nan() @@ -48,11 +62,17 @@ def assert_series_equal(self, left, right, *args, **kwargs): *args, **kwargs) def assert_frame_equal(self, left, right, *args, **kwargs): - self.assert_series_equal(left.dtypes, right.dtypes) - for col in left.columns: + # TODO(EA): select_dtypes + decimals = (left.dtypes == 'decimal').index + + for col in decimals: self.assert_series_equal(left[col], right[col], *args, **kwargs) + left = left.drop(columns=decimals) + right = right.drop(columns=decimals) + tm.assert_frame_equal(left, right, *args, **kwargs) + class TestDtype(BaseDecimal, base.BaseDtypeTests): pass diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 322944129146a..ee0951812b8f0 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -44,7 +44,11 @@ def __getitem__(self, item): return self._constructor_from_sequence([ x for x, m in zip(self, item) if m ]) + elif isinstance(item, collections.Iterable): + # fancy indexing + return type(self)([self.data[i] for i in item]) else: + # slice return type(self)(self.data[item]) def __setitem__(self, key, value): @@ -104,6 +108,13 @@ def _concat_same_type(cls, to_concat): data = list(itertools.chain.from_iterable([x.data for x in to_concat])) return cls(data) + def _values_for_argsort(self): + # Disable NumPy's shape inference by including an empty tuple... + # If all the elemnts of self are the same size P, NumPy will + # cast them to an (N, P) array, instead of an (N,) array of tuples. + frozen = [()] + list(tuple(x.items()) for x in self) + return np.array(frozen, dtype=object)[1:] + def make_data(): # TODO: Use a regular dict. See _NDFrameIndexer._setitem_with_indexer diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 16d5e4415a79f..aec561ece8573 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -29,6 +29,16 @@ def data_missing(): return JSONArray([{}, {'a': 10}]) +@pytest.fixture +def data_for_sorting(): + return JSONArray([{'b': 1}, {'c': 4}, {'a': 2, 'c': 3}]) + + +@pytest.fixture +def data_missing_for_sorting(): + return JSONArray([{'b': 1}, {}, {'a': 4}]) + + @pytest.fixture def na_value(): return {} @@ -70,10 +80,39 @@ def test_fillna_frame(self): class TestMethods(base.BaseMethodsTests): - @pytest.mark.skip(reason="Unhashable") + unhashable = pytest.mark.skip(reason="Unhashable") + unstable = pytest.mark.skipif(sys.version_info <= (3, 5), + reason="Dictionary order unstable") + + @unhashable def test_value_counts(self, all_data, dropna): pass + @unhashable + def test_sort_values_frame(self): + # TODO (EA.factorize): see if _values_for_factorize allows this. + pass + + @unstable + def test_argsort(self, data_for_sorting): + super(TestMethods, self).test_argsort(data_for_sorting) + + @unstable + def test_argsort_missing(self, data_missing_for_sorting): + super(TestMethods, self).test_argsort_missing( + data_missing_for_sorting) + + @unstable + @pytest.mark.parametrize('ascending', [True, False]) + def test_sort_values(self, data_for_sorting, ascending): + super(TestMethods, self).test_sort_values( + data_for_sorting, ascending) + + @pytest.mark.parametrize('ascending', [True, False]) + def test_sort_values_missing(self, data_missing_for_sorting, ascending): + super(TestMethods, self).test_sort_values_missing( + data_missing_for_sorting, ascending) + class TestCasting(base.BaseCastingTests): pass
This enables {Series,DataFrame}.sort_values and {Series,DataFrame}.argsort. These are required for `factorize`, which is required for `groupby` (my end goal). I haven't implemented `ExtensionArray.sort_values` yet because it hasn't become necessary. But I can if needed / desired.
https://api.github.com/repos/pandas-dev/pandas/pulls/19957
2018-03-01T20:48:41Z
2018-03-22T23:20:06Z
2018-03-22T23:20:06Z
2018-03-23T12:43:22Z
DOC/CI: run doctests on travis
diff --git a/.travis.yml b/.travis.yml index 2d2a0bc019c80..32e6d2eae90a7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -56,7 +56,7 @@ matrix: - python-gtk2 - dist: trusty env: - - JOB="3.6, coverage" ENV_FILE="ci/travis-36.yaml" TEST_ARGS="--skip-slow --skip-network" PANDAS_TESTING_MODE="deprecate" COVERAGE=true + - JOB="3.6, coverage" ENV_FILE="ci/travis-36.yaml" TEST_ARGS="--skip-slow --skip-network" PANDAS_TESTING_MODE="deprecate" COVERAGE=true DOCTEST=true # In allow_failures - dist: trusty env: @@ -119,6 +119,7 @@ script: - ci/script_single.sh - ci/script_multi.sh - ci/lint.sh + - ci/doctests.sh - echo "checking imports" - source activate pandas && python ci/check_imports.py - echo "script done" diff --git a/ci/build_docs.sh b/ci/build_docs.sh index 90a666dc34ed7..f445447e3565c 100755 --- a/ci/build_docs.sh +++ b/ci/build_docs.sh @@ -8,15 +8,6 @@ fi cd "$TRAVIS_BUILD_DIR" echo "inside $0" -git show --pretty="format:" --name-only HEAD~5.. --first-parent | grep -P "rst|txt|doc" - -# if [ "$?" != "0" ]; then -# echo "Skipping doc build, none were modified" -# # nope, skip docs build -# exit 0 -# fi - - if [ "$DOC" ]; then echo "Will build docs" @@ -60,15 +51,6 @@ 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/ci/doctests.sh b/ci/doctests.sh new file mode 100755 index 0000000000000..04b3e14a7120a --- /dev/null +++ b/ci/doctests.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +echo "inside $0" + + +source activate pandas +cd "$TRAVIS_BUILD_DIR" + +RET=0 + +if [ "$DOCTEST" ]; then + + echo "Running doctests" + + # running all doctests is not yet working + # pytest --doctest-modules --ignore=pandas/tests -v pandas + + # if [ $? -ne "0" ]; then + # RET=1 + # fi + + # DataFrame / Series docstrings + pytest --doctest-modules -v pandas/core/frame.py \ + -k"-assign -axes -combine -isin -itertuples -join -nlargest -nsmallest -nunique -pivot_table -quantile -query -reindex -reindex_axis -replace -round -set_index -stack -to_dict -to_records -to_stata -transform" + + if [ $? -ne "0" ]; then + RET=1 + fi + + pytest --doctest-modules -v pandas/core/series.py \ + -k"-agg -map -nlargest -nonzero -nsmallest -reindex -searchsorted -to_dict" + + if [ $? -ne "0" ]; then + RET=1 + fi + + pytest --doctest-modules -v pandas/core/generic.py \ + -k"-_set_axis_name -_xs -describe -droplevel -groupby -interpolate -pct_change -pipe -reindex -reindex_axis -resample -sample -to_json -to_xarray -transform -transpose -values -xs" + + if [ $? -ne "0" ]; then + RET=1 + fi + + # top-level reshaping functions + pytest --doctest-modules -v \ + pandas/core/reshape/concat.py \ + pandas/core/reshape/pivot.py \ + pandas/core/reshape/reshape.py \ + pandas/core/reshape/tile.py \ + -k"-crosstab -pivot_table -cut" + + if [ $? -ne "0" ]; then + RET=1 + fi + +else + echo "NOT running doctests" +fi + +exit $RET diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index ff06d024740bf..f3880902d744d 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -365,6 +365,31 @@ This will identify methods documented in ``doc/source/api.rst`` that are not act class methods, and existing methods that are not documented in ``doc/source/api.rst``. +Updating a *pandas* docstring +----------------------------- + +When improving a single function or method's docstring, it is not necessarily +needed to build the full documentation (see next section). +However, there is a script that checks a docstring (for example for the ``DataFrame.mean`` method):: + + python scripts/validate_docstrings.py pandas.DataFrame.mean + +This script will indicate some formatting errors if present, and will also +run and test the examples included in the docstring. +Check the :ref:`pandas docstring guide <docstring>` for a detailed guide +on how to format the docstring. + +The examples in the docstring ('doctests') must be valid Python code, +that in a deterministic way returns the presented output, and that can be +copied and run by users. This can be checked with the script above, and is +also tested on Travis. A failing doctest will be a blocker for merging a PR. +Check the :ref:`examples <docstring.examples>` section in the docstring guide +for some tips and tricks to get the doctests passing. + +When doing a PR with a docstring update, it is good to post the +output of the validation script in a comment on github. + + How to build the *pandas* documentation --------------------------------------- diff --git a/pandas/core/config.py b/pandas/core/config.py index abcdbfa12e4e9..f178600b74626 100644 --- a/pandas/core/config.py +++ b/pandas/core/config.py @@ -384,7 +384,7 @@ class option_context(object): -------- >>> with option_context('display.max_rows', 10, 'display.max_columns', 5): - ... + ... ... """ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 78ad9728800d6..411e3d970ebf5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -314,15 +314,13 @@ class DataFrame(NDFrame): 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 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), + ... columns=['a', 'b', 'c']) >>> 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 + a b c + 0 1 2 3 + 1 4 5 6 + 2 7 8 9 See also -------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2245abd780edd..fd372ce2fd78e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -738,14 +738,14 @@ def droplevel(self, level, axis=0): Examples -------- >>> df = pd.DataFrame([ - ...: [1, 2, 3, 4], - ...: [5, 6, 7, 8], - ...: [9, 10, 11, 12] - ...: ]).set_index([0, 1]).rename_axis(['a', 'b']) + ... [1, 2, 3, 4], + ... [5, 6, 7, 8], + ... [9, 10, 11, 12] + ... ]).set_index([0, 1]).rename_axis(['a', 'b']) >>> df.columns = pd.MultiIndex.from_tuples([ - ...: ('c', 'e'), ('d', 'f') - ...:], names=['level_1', 'level_2']) + ... ('c', 'e'), ('d', 'f') + ... ], names=['level_1', 'level_2']) >>> df level_1 c d diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 39ab498d080bf..1eedb9e2a8274 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -591,7 +591,7 @@ def set_defaultencoding(encoding): def capture_stdout(f): - """ + r""" Decorator to capture stdout in a buffer so that it can be checked (or suppressed) during testing. @@ -609,7 +609,6 @@ def capture_stdout(f): -------- >>> from pandas.util.testing import capture_stdout - >>> >>> import sys >>> >>> @capture_stdout @@ -639,7 +638,7 @@ def wrapper(*args, **kwargs): def capture_stderr(f): - """ + r""" Decorator to capture stderr in a buffer so that it can be checked (or suppressed) during testing. @@ -657,7 +656,6 @@ def capture_stderr(f): -------- >>> from pandas.util.testing import capture_stderr - >>> >>> import sys >>> >>> @capture_stderr @@ -2370,7 +2368,7 @@ def wrapper(*args, **kwargs): def assert_raises_regex(_exception, _regexp, _callable=None, *args, **kwargs): - r""" + """ 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 @@ -2396,6 +2394,7 @@ def assert_raises_regex(_exception, _regexp, _callable=None, AssertionError: "pear" does not match "'apple'" You can also use this in a with statement. + >>> with assert_raises_regex(TypeError, 'unsupported operand type\(s\)'): ... 1 + {} >>> with assert_raises_regex(TypeError, 'banana'): diff --git a/setup.cfg b/setup.cfg index d00d527da49e2..fbbe7c10aa921 100644 --- a/setup.cfg +++ b/setup.cfg @@ -37,5 +37,5 @@ markers = slow: mark a test as slow network: mark a test as network high_memory: mark a test as a high-memory only +doctest_optionflags = NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL addopts = --strict-data-files -doctest_optionflags= NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL \ No newline at end of file
Trying to see if we can check the doctests on travis. We were already running them, but at this point they were not failing travis if they failed. Closes https://github.com/pandas-dev/pandas/issues/19934 Closes https://github.com/pandas-dev/pandas/issues/3439
https://api.github.com/repos/pandas-dev/pandas/pulls/19952
2018-03-01T13:48:26Z
2018-08-17T07:20:12Z
2018-08-17T07:20:12Z
2018-08-17T07:20:15Z
DOC: small updates to make.py script
diff --git a/doc/make.py b/doc/make.py index 2819a62347627..53635498f2adb 100755 --- a/doc/make.py +++ b/doc/make.py @@ -78,9 +78,11 @@ class DocBuilder: All public methods of this class can be called as parameters of the script. """ - def __init__(self, num_jobs=1, include_api=True, single_doc=None): + def __init__(self, num_jobs=1, include_api=True, single_doc=None, + verbosity=0): self.num_jobs = num_jobs self.include_api = include_api + self.verbosity = verbosity self.single_doc = None self.single_doc_type = None if single_doc is not None: @@ -120,7 +122,7 @@ def _process_single_doc(self, single_doc): """ self.include_api = False - if single_doc == 'api.rst': + if single_doc == 'api.rst' or single_doc == 'api': self.single_doc_type = 'api' self.single_doc = 'api' elif os.path.exists(os.path.join(SOURCE_PATH, single_doc)): @@ -229,6 +231,8 @@ def _sphinx_build(self, kind): self._run_os('sphinx-build', '-j{}'.format(self.num_jobs), '-b{}'.format(kind), + '-{}'.format( + 'v' * self.verbosity) if self.verbosity else '', '-d{}'.format(os.path.join(BUILD_PATH, 'doctrees')), '-Dexclude_patterns={}'.format(self.exclude_patterns), SOURCE_PATH, @@ -330,6 +334,9 @@ def main(): type=str, default=os.path.join(DOC_PATH, '..'), help='path') + argparser.add_argument('-v', action='count', dest='verbosity', default=0, + help=('increase verbosity (can be repeated), ' + 'passed to the sphinx build command')) args = argparser.parse_args() if args.command not in cmds: @@ -338,9 +345,9 @@ def main(): os.environ['PYTHONPATH'] = args.python_path - getattr(DocBuilder(args.num_jobs, - not args.no_api, - args.single), args.command)() + builder = DocBuilder(args.num_jobs, not args.no_api, args.single, + args.verbosity) + getattr(builder, args.command)() if __name__ == '__main__':
- alias `python make.py --single api` to `api.rst` (like is done for the other .rst pages) - pass through verbose flag to sphinx
https://api.github.com/repos/pandas-dev/pandas/pulls/19951
2018-03-01T12:57:37Z
2018-03-02T21:35:46Z
2018-03-02T21:35:46Z
2018-03-02T21:35:52Z
DOC: remove empty attribute/method lists from class docstrings html page
diff --git a/doc/source/conf.py b/doc/source/conf.py index 835127e5094e4..c81d38db05cca 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -552,6 +552,45 @@ def remove_flags_docstring(app, what, name, obj, options, lines): del lines[:] +def process_class_docstrings(app, what, name, obj, options, lines): + """ + For those classes for which we use :: + + :template: autosummary/class_without_autosummary.rst + + the documented attributes/methods have to be listed in the class + docstring. However, if one of those lists is empty, we use 'None', + which then generates warnings in sphinx / ugly html output. + This "autodoc-process-docstring" event connector removes that part + from the processed docstring. + + """ + if what == "class": + joined = '\n'.join(lines) + + templates = [ + """.. rubric:: Attributes + +.. autosummary:: + :toctree: + + None +""", + """.. rubric:: Methods + +.. autosummary:: + :toctree: + + None +""" + ] + + for template in templates: + if template in joined: + joined = joined.replace(template, '') + lines[:] = joined.split('\n') + + suppress_warnings = [ # We "overwrite" autosummary with our PandasAutosummary, but # still want the regular autosummary setup to run. So we just @@ -562,6 +601,7 @@ def remove_flags_docstring(app, what, name, obj, options, lines): def setup(app): app.connect("autodoc-process-docstring", remove_flags_docstring) + app.connect("autodoc-process-docstring", process_class_docstrings) app.add_autodocumenter(AccessorDocumenter) app.add_autodocumenter(AccessorAttributeDocumenter) app.add_autodocumenter(AccessorMethodDocumenter) diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index a4558116bfa63..1fe0c8fa289e6 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -131,7 +131,7 @@ def is_all_dates(self): Attributes ---------- - inferred_type + None Methods ------- diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 9d770cffb0059..7c266dc889368 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -53,6 +53,10 @@ class RangeIndex(Int64Index): Index : The base pandas Index type Int64Index : Index of int64 data + Attributes + ---------- + None + Methods ------- from_range
Follow-up on https://github.com/pandas-dev/pandas/pull/18202 (RangeIndex was forgotten) This is not really ideal, as we then get warnings about None not being a method. Maybe we could somehow connect with the numpydoc process and after its processing remove it ..
https://api.github.com/repos/pandas-dev/pandas/pulls/19949
2018-03-01T10:06:01Z
2018-03-01T21:48:39Z
2018-03-01T21:48:39Z
2018-03-01T21:48:52Z
BUG: Preserve column metadata with DataFrame.astype
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 90ce6b47728fb..fb19fd81fe7c7 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -954,6 +954,7 @@ Reshaping - Bug in :func:`qcut` where datetime and timedelta data with ``NaT`` present raised a ``ValueError`` (:issue:`19768`) - Bug in :func:`DataFrame.iterrows`, which would infers strings not compliant to `ISO8601 <https://en.wikipedia.org/wiki/ISO_8601>`_ to datetimes (:issue:`19671`) - Bug in :class:`Series` constructor with ``Categorical`` where a ```ValueError`` is not raised when an index of different length is given (:issue:`19342`) +- Bug in :meth:`DataFrame.astype` where column metadata is lost when converting to categorical or a dictionary of dtypes (:issue:`19920`) Other ^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c4eb7dd7e7a7e..43f7b673c7cbd 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4436,17 +4436,21 @@ def astype(self, dtype, copy=True, errors='raise', **kwargs): results.append(col.astype(dtype[col_name], copy=copy)) else: results.append(results.append(col.copy() if copy else col)) - return pd.concat(results, axis=1, copy=False) elif is_categorical_dtype(dtype) and self.ndim > 1: # GH 18099: columnwise conversion to categorical results = (self[col].astype(dtype, copy=copy) for col in self) - return pd.concat(results, axis=1, copy=False) - # else, only a single dtype is given - new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors, - **kwargs) - return self._constructor(new_data).__finalize__(self) + else: + # else, only a single dtype is given + new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors, + **kwargs) + return self._constructor(new_data).__finalize__(self) + + # GH 19920: retain column metadata after concat + result = pd.concat(results, axis=1, copy=False) + result.columns = self.columns + return result def copy(self, deep=True): """ diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 430d43019afc2..90daa9aa882c8 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -649,6 +649,15 @@ def test_astype_categoricaldtype_class_raises(self, cls): with tm.assert_raises_regex(TypeError, xpr): df['A'].astype(cls) + @pytest.mark.parametrize('dtype', [ + {100: 'float64', 200: 'uint64'}, 'category', 'float64']) + def test_astype_column_metadata(self, dtype): + # GH 19920 + columns = pd.UInt64Index([100, 200, 300], name='foo') + df = DataFrame(np.arange(15).reshape(5, 3), columns=columns) + df = df.astype(dtype) + tm.assert_index_equal(df.columns, columns) + @pytest.mark.parametrize("dtype", ["M8", "m8"]) @pytest.mark.parametrize("unit", ['ns', 'us', 'ms', 's', 'h', 'm', 'D']) def test_astype_from_datetimelike_to_objectt(self, dtype, unit):
- [X] closes #19920 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry Follow-up to #18099
https://api.github.com/repos/pandas-dev/pandas/pulls/19948
2018-03-01T08:40:54Z
2018-03-01T11:14:20Z
2018-03-01T11:14:19Z
2018-03-01T16:15:02Z
CLN: remove redundant clean_fill_method calls
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c4eb7dd7e7a7e..79c783040dc97 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4711,7 +4711,7 @@ def fillna(self, value=None, method=None, axis=None, inplace=False, if axis is None: axis = 0 axis = self._get_axis_number(axis) - method = missing.clean_fill_method(method) + from pandas import DataFrame if value is None: @@ -4732,7 +4732,6 @@ def fillna(self, value=None, method=None, axis=None, inplace=False, # 3d elif self.ndim == 3: - # fill in 2d chunks result = {col: s.fillna(method=method, value=value) for col, s in self.iteritems()} @@ -4742,7 +4741,6 @@ def fillna(self, value=None, method=None, axis=None, inplace=False, else: # 2d or less - method = missing.clean_fill_method(method) new_data = self._data.interpolate(method=method, axis=axis, limit=limit, inplace=inplace, coerce=True,
The ` method = missing.clean_fill_method(method)` is already called in `value, method = validate_fillna_kwargs(value, method)`
https://api.github.com/repos/pandas-dev/pandas/pulls/19947
2018-03-01T08:32:07Z
2018-03-01T11:12:36Z
2018-03-01T11:12:36Z
2018-03-01T11:12:39Z
DOC: Add comparison with Stata page to documentation
diff --git a/doc/source/comparison_with_stata.rst b/doc/source/comparison_with_stata.rst new file mode 100644 index 0000000000000..6c518983d5904 --- /dev/null +++ b/doc/source/comparison_with_stata.rst @@ -0,0 +1,680 @@ +.. currentmodule:: pandas +.. _compare_with_stata: + +Comparison with Stata +********************* +For potential users coming from `Stata <https://en.wikipedia.org/wiki/Stata>`__ +this page is meant to demonstrate how different Stata operations would be +performed in pandas. + +If you're new to pandas, you might want to first read through :ref:`10 Minutes to pandas<10min>` +to familiarize yourself with the library. + +As is customary, we import pandas and NumPy as follows. This means that we can refer to the +libraries as ``pd`` and ``np``, respectively, for the rest of the document. + +.. ipython:: python + + import pandas as pd + import numpy as np + + +.. note:: + + Throughout this tutorial, the pandas ``DataFrame`` will be displayed by calling + ``df.head()``, which displays the first N (default 5) rows of the ``DataFrame``. + This is often used in interactive work (e.g. `Jupyter notebook + <https://jupyter.org/>`_ or terminal) -- the equivalent in Stata would be: + + .. code-block:: stata + + list in 1/5 + +Data Structures +--------------- + +General Terminology Translation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. csv-table:: + :header: "pandas", "Stata" + :widths: 20, 20 + + ``DataFrame``, data set + column, variable + row, observation + groupby, bysort + ``NaN``, ``.`` + + +``DataFrame`` / ``Series`` +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A ``DataFrame`` in pandas is analogous to a Stata data set -- a two-dimensional +data source with labeled columns that can be of different types. As will be +shown in this document, almost any operation that can be applied to a data set +in Stata can also be accomplished in pandas. + +A ``Series`` is the data structure that represents one column of a +``DataFrame``. Stata doesn't have a separate data structure for a single column, +but in general, working with a ``Series`` is analogous to referencing a column +of a data set in Stata. + +``Index`` +~~~~~~~~~ + +Every ``DataFrame`` and ``Series`` has an ``Index`` -- labels on the +*rows* of the data. Stata does not have an exactly analogous concept. In Stata, a data set's +rows are essentially unlabeled, other than an implicit integer index that can be +accessed with ``_n``. + +In pandas, if no index is specified, an integer index is also used by default +(first row = 0, second row = 1, and so on). While using a labeled ``Index`` or +``MultiIndex`` can enable sophisticated analyses and is ultimately an important +part of pandas to understand, for this comparison we will essentially ignore the +``Index`` and just treat the ``DataFrame`` as a collection of columns. Please +see the :ref:`indexing documentation<indexing>` for much more on how to use an +``Index`` effectively. + + +Data Input / Output +------------------- + +Constructing a DataFrame from Values +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A Stata data set can be built from specified values by +placing the data after an ``input`` statement and +specifying the column names. + +.. code-block:: stata + + input x y + 1 2 + 3 4 + 5 6 + end + +A pandas ``DataFrame`` can be constructed in many different ways, +but for a small number of values, it is often convenient to specify it as +a Python dictionary, where the keys are the column names +and the values are the data. + +.. ipython:: python + + df = pd.DataFrame({ + 'x': [1, 3, 5], + 'y': [2, 4, 6]}) + df + + +Reading External Data +~~~~~~~~~~~~~~~~~~~~~ + +Like Stata, pandas provides utilities for reading in data from +many formats. The ``tips`` data set, found within the pandas +tests (`csv <https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/tips.csv>`_) +will be used in many of the following examples. + +Stata provides ``import delimited`` to read csv data into a data set in memory. +If the ``tips.csv`` file is in the current working directory, we can import it as follows. + +.. code-block:: stata + + import delimited tips.csv + +The pandas method is :func:`read_csv`, which works similarly. Additionally, it will automatically download +the data set if presented with a url. + +.. ipython:: python + + url = 'https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/tips.csv' + tips = pd.read_csv(url) + tips.head() + +Like ``import delimited``, :func:`read_csv` can take a number of parameters to specify +how the data should be parsed. For example, if the data were instead tab delimited, +did not have column names, and existed in the current working directory, +the pandas command would be: + +.. code-block:: python + + tips = pd.read_csv('tips.csv', sep='\t', header=None) + + # alternatively, read_table is an alias to read_csv with tab delimiter + tips = pd.read_table('tips.csv', header=None) + +Pandas can also read Stata data sets in ``.dta`` format with the :func:`read_stata` function. + +.. code-block:: python + + df = pd.read_stata('data.dta') + +In addition to text/csv and Stata files, pandas supports a variety of other data formats +such as Excel, SAS, HDF5, Parquet, and SQL databases. These are all read via a ``pd.read_*`` +function. See the :ref:`IO documentation<io>` for more details. + + +Exporting Data +~~~~~~~~~~~~~~ + +The inverse of ``import delimited`` in Stata is ``export delimited`` + +.. code-block:: stata + + export delimited tips2.csv + +Similarly in pandas, the opposite of ``read_csv`` is :meth:`DataFrame.to_csv`. + +.. code-block:: python + + tips.to_csv('tips2.csv') + +Pandas can also export to Stata file format with the :meth:`DataFrame.to_stata` method. + +.. code-block:: python + + tips.to_stata('tips2.dta') + + +Data Operations +--------------- + +Operations on Columns +~~~~~~~~~~~~~~~~~~~~~ + +In Stata, arbitrary math expressions can be used with the ``generate`` and +``replace`` commands on new or existing columns. The ``drop`` command drops +the column from the data set. + +.. code-block:: stata + + replace total_bill = total_bill - 2 + generate new_bill = total_bill / 2 + drop new_bill + +pandas provides similar vectorized operations by +specifying the individual ``Series`` in the ``DataFrame``. +New columns can be assigned in the same way. The :meth:`DataFrame.drop` method +drops a column from the ``DataFrame``. + +.. ipython:: python + + tips['total_bill'] = tips['total_bill'] - 2 + tips['new_bill'] = tips['total_bill'] / 2 + tips.head() + + tips = tips.drop('new_bill', axis=1) + +Filtering +~~~~~~~~~ + +Filtering in Stata is done with an ``if`` clause on one or more columns. + +.. code-block:: stata + + list if total_bill > 10 + +DataFrames can be filtered in multiple ways; the most intuitive of which is using +:ref:`boolean indexing <indexing.boolean>`. + +.. ipython:: python + + tips[tips['total_bill'] > 10].head() + +If/Then Logic +~~~~~~~~~~~~~ + +In Stata, an ``if`` clause can also be used to create new columns. + +.. code-block:: stata + + generate bucket = "low" if total_bill < 10 + replace bucket = "high" if total_bill >= 10 + +The same operation in pandas can be accomplished using +the ``where`` method from ``numpy``. + +.. ipython:: python + + tips['bucket'] = np.where(tips['total_bill'] < 10, 'low', 'high') + tips.head() + +.. ipython:: python + :suppress: + + tips = tips.drop('bucket', axis=1) + +Date Functionality +~~~~~~~~~~~~~~~~~~ + +Stata provides a variety of functions to do operations on +date/datetime columns. + +.. code-block:: stata + + generate date1 = mdy(1, 15, 2013) + generate date2 = date("Feb152015", "MDY") + + generate date1_year = year(date1) + generate date2_month = month(date2) + + * shift date to beginning of next month + generate date1_next = mdy(month(date1) + 1, 1, year(date1)) if month(date1) != 12 + replace date1_next = mdy(1, 1, year(date1) + 1) if month(date1) == 12 + generate months_between = mofd(date2) - mofd(date1) + + list date1 date2 date1_year date2_month date1_next months_between + +The equivalent pandas operations are shown below. In addition to these +functions, pandas supports other Time Series features +not available in Stata (such as time zone handling and custom offsets) -- +see the :ref:`timeseries documentation<timeseries>` for more details. + +.. ipython:: python + + tips['date1'] = pd.Timestamp('2013-01-15') + tips['date2'] = pd.Timestamp('2015-02-15') + tips['date1_year'] = tips['date1'].dt.year + tips['date2_month'] = tips['date2'].dt.month + tips['date1_next'] = tips['date1'] + pd.offsets.MonthBegin() + tips['months_between'] = (tips['date2'].dt.to_period('M') - + tips['date1'].dt.to_period('M')) + + tips[['date1','date2','date1_year','date2_month', + 'date1_next','months_between']].head() + +.. ipython:: python + :suppress: + + tips = tips.drop(['date1','date2','date1_year', + 'date2_month','date1_next','months_between'], axis=1) + +Selection of Columns +~~~~~~~~~~~~~~~~~~~~ + +Stata provides keywords to select, drop, and rename columns. + +.. code-block:: stata + + keep sex total_bill tip + + drop sex + + rename total_bill total_bill_2 + +The same operations are expressed in pandas below. Note that in contrast to Stata, these +operations do not happen in place. To make these changes persist, assign the operation back +to a variable. + +.. ipython:: python + + # keep + tips[['sex', 'total_bill', 'tip']].head() + + # drop + tips.drop('sex', axis=1).head() + + # rename + tips.rename(columns={'total_bill': 'total_bill_2'}).head() + + +Sorting by Values +~~~~~~~~~~~~~~~~~ + +Sorting in Stata is accomplished via ``sort`` + +.. code-block:: stata + + sort sex total_bill + +pandas objects have a :meth:`DataFrame.sort_values` method, which +takes a list of columns to sort by. + +.. ipython:: python + + tips = tips.sort_values(['sex', 'total_bill']) + tips.head() + + +String Processing +----------------- + +Finding Length of String +~~~~~~~~~~~~~~~~~~~~~~~~ + +Stata determines the length of a character string with the :func:`strlen` and +:func:`ustrlen` functions for ASCII and Unicode strings, respectively. + +.. code-block:: stata + + generate strlen_time = strlen(time) + generate ustrlen_time = ustrlen(time) + +Python determines the length of a character string with the ``len`` function. +In Python 3, all strings are Unicode strings. ``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() + + +Finding Position of Substring +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Stata determines the position of a character in a string with the :func:`strpos` function. +This 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:: stata + + generate str_position = strpos(sex, "ale") + +Python determines the position of a character in a string with the +:func:`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() + + +Extracting Substring by Position +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Stata extracts a substring from a string based on its position with the :func:`substr` function. + +.. code-block:: stata + + generate short_sex = substr(sex, 1, 1) + +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() + + +Extracting nth Word +~~~~~~~~~~~~~~~~~~~ + +The Stata :func:`word` 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:: stata + + clear + input str20 string + "John Smith" + "Jane Cook" + end + + generate first_name = word(name, 1) + generate last_name = word(name, -1) + +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 + + +Changing Case +~~~~~~~~~~~~~ + +The Stata :func:`strupper`, :func:`strlower`, :func:`strproper`, +:func:`ustrupper`, :func:`ustrlower`, and :func:`ustrtitle` functions +change the case of ASCII and Unicode strings, respectively. + +.. code-block:: stata + + clear + input str20 string + "John Smith" + "Jane Cook" + end + + generate upper = strupper(string) + generate lower = strlower(string) + generate title = strproper(string) + list + +The equivalent Python functions are ``upper``, ``lower``, and ``title``. + +.. ipython:: python + + firstlast = pd.DataFrame({'string': ['John Smith', 'Jane Cook']}) + firstlast['upper'] = firstlast['string'].str.upper() + firstlast['lower'] = firstlast['string'].str.lower() + firstlast['title'] = firstlast['string'].str.title() + firstlast + +Merging +------- + +The following tables will be used in the merge examples + +.. ipython:: python + + df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], + 'value': np.random.randn(4)}) + df1 + df2 = pd.DataFrame({'key': ['B', 'D', 'D', 'E'], + 'value': np.random.randn(4)}) + df2 + +In Stata, to perform a merge, one data set must be in memory +and the other must be referenced as a file name on disk. In +contrast, Python must have both ``DataFrames`` already in memory. + +By default, Stata performs an outer join, where all observations +from both data sets are left in memory after the merge. One can +keep only observations from the initial data set, the merged data set, +or the intersection of the two by using the values created in the +``_merge`` variable. + +.. code-block:: stata + + * First create df2 and save to disk + clear + input str1 key + B + D + D + E + end + generate value = rnormal() + save df2.dta + + * Now create df1 in memory + clear + input str1 key + A + B + C + D + end + generate value = rnormal() + + preserve + + * Left join + merge 1:n key using df2.dta + keep if _merge == 1 + + * Right join + restore, preserve + merge 1:n key using df2.dta + keep if _merge == 2 + + * Inner join + restore, preserve + merge 1:n key using df2.dta + keep if _merge == 3 + + * Outer join + restore + merge 1:n key using df2.dta + +pandas DataFrames have a :meth:`DataFrame.merge` method, which provides +similar functionality. Note that different join +types are accomplished via the ``how`` keyword. + +.. ipython:: python + + inner_join = df1.merge(df2, on=['key'], how='inner') + inner_join + + left_join = df1.merge(df2, on=['key'], how='left') + left_join + + right_join = df1.merge(df2, on=['key'], how='right') + right_join + + outer_join = df1.merge(df2, on=['key'], how='outer') + outer_join + + +Missing Data +------------ + +Like Stata, pandas has a representation for missing data -- the +special float value ``NaN`` (not a number). Many of the semantics +are the same; for example missing data propagates through numeric +operations, and is ignored by default for aggregations. + +.. ipython:: python + + outer_join + outer_join['value_x'] + outer_join['value_y'] + outer_join['value_x'].sum() + +One difference is that missing data cannot be compared to its sentinel value. +For example, in Stata you could do this to filter missing values. + +.. code-block:: stata + + * Keep missing values + list if value_x == . + * Keep non-missing values + list if value_x != . + +This doesn't work in pandas. Instead, the :func:`pd.isna` or :func:`pd.notna` functions +should be used for comparisons. + +.. ipython:: python + + outer_join[pd.isna(outer_join['value_x'])] + outer_join[pd.notna(outer_join['value_x'])] + +Pandas also provides a variety of methods to work with missing data -- some of +which would be challenging to express in Stata. For example, there are methods to +drop all rows with any missing values, replacing missing values with a specified +value, like the mean, or forward filling from previous rows. See the +:ref:`missing data documentation<missing_data>` for more. + +.. ipython:: python + + # Drop rows with any missing value + outer_join.dropna() + + # Fill forwards + outer_join.fillna(method='ffill') + + # Impute missing values with the mean + outer_join['value_x'].fillna(outer_join['value_x'].mean()) + + +GroupBy +------- + +Aggregation +~~~~~~~~~~~ + +Stata's ``collapse`` can be used to group by one or +more key variables and compute aggregations on +numeric columns. + +.. code-block:: stata + + collapse (sum) total_bill tip, by(sex smoker) + +pandas provides a flexible ``groupby`` mechanism that +allows similar aggregations. See the :ref:`groupby documentation<groupby>` +for more details and examples. + +.. ipython:: python + + tips_summed = tips.groupby(['sex', 'smoker'])['total_bill', 'tip'].sum() + tips_summed.head() + + +Transformation +~~~~~~~~~~~~~~ + +In Stata, if the group aggregations need to be used with the +original data set, one would usually use ``bysort`` with :func:`egen`. +For example, to subtract the mean for each observation by smoker group. + +.. code-block:: stata + + bysort sex smoker: egen group_bill = mean(total_bill) + generate adj_total_bill = total_bill - group_bill + + +pandas ``groubpy`` provides a ``transform`` mechanism that allows +these type of operations to be succinctly expressed in one +operation. + +.. ipython:: python + + gb = tips.groupby('smoker')['total_bill'] + tips['adj_total_bill'] = tips['total_bill'] - gb.transform('mean') + tips.head() + + +By Group Processing +~~~~~~~~~~~~~~~~~~~ + +In addition to aggregation, pandas ``groupby`` can be used to +replicate most other ``bysort`` processing from Stata. For example, +the following example lists the first observation in the current +sort order by sex/smoker group. + +.. code-block:: stata + + bysort sex smoker: list if _n == 1 + +In pandas this would be written as: + +.. ipython:: python + + tips.groupby(['sex','smoker']).first() + + +Other Considerations +-------------------- + +Disk vs Memory +~~~~~~~~~~~~~~ + +Pandas and Stata both operate exclusively in memory. This means that the size of +data able to be loaded in pandas is limited by your machine's memory. +If out of core processing is needed, one possibility is the +`dask.dataframe <http://dask.pydata.org/en/latest/dataframe.html>`_ +library, which provides a subset of pandas functionality for an +on-disk ``DataFrame``. + + diff --git a/doc/source/index.rst.template b/doc/source/index.rst.template index 1ef88a524732f..82ed5e36b6c82 100644 --- a/doc/source/index.rst.template +++ b/doc/source/index.rst.template @@ -150,6 +150,7 @@ See the package overview for more detail about what's in the library. comparison_with_r comparison_with_sql comparison_with_sas + comparison_with_stata {% endif -%} {% if include_api -%} api
- [ ] closes ##### - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry I noticed that the pandas documentation has pages for [Comparison with SAS](https://pandas.pydata.org/pandas-docs/stable/comparison_with_sas.html), [Comparison with R](https://pandas.pydata.org/pandas-docs/stable/comparison_with_r.html) and [Comparison with SQL](https://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html), but nothing for newcomers from Stata. This is heavily based off of the "Comparison with SAS" page, with all the examples and discussion fixed for Stata.
https://api.github.com/repos/pandas-dev/pandas/pulls/19945
2018-03-01T05:10:48Z
2018-03-29T14:39:09Z
2018-03-29T14:39:09Z
2018-03-29T14:39:14Z
BUG: Compat for pre-0.20 TimedeltaIndex and Float64Index pickles #19939
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index cf2a5de583878..08ac6f491793b 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -957,6 +957,7 @@ I/O - :class:`Interval` now supported in :func:`DataFrame.to_excel` for all Excel file types (:issue:`19242`) - :class:`Timedelta` now supported in :func:`DataFrame.to_excel` for all Excel file types (:issue:`19242`, :issue:`9155`, :issue:`19900`) - Bug in :meth:`pandas.io.stata.StataReader.value_labels` raising an ``AttributeError`` when called on very old files. Now returns an empty dict (:issue:`19417`) +- Bug in :func:`read_pickle` when unpickling objects with :class:`TimedeltaIndex` or :class:`Float64Index` created with pandas prior to version 0.20 (:issue:`19939`) Plotting ^^^^^^^^ diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py index f651fbbf56316..e444c4002c2c0 100644 --- a/pandas/compat/pickle_compat.py +++ b/pandas/compat/pickle_compat.py @@ -113,6 +113,12 @@ def load_reduce(self): # 19269, arrays moving ('pandas.core.categorical', 'Categorical'): ('pandas.core.arrays', 'Categorical'), + + # 19939, add timedeltaindex, float64index compat from 15998 move + ('pandas.tseries.tdi', 'TimedeltaIndex'): + ('pandas.core.indexes.timedeltas', 'TimedeltaIndex'), + ('pandas.indexes.numeric', 'Float64Index'): + ('pandas.core.indexes.numeric', 'Float64Index'), } diff --git a/pandas/tests/io/data/legacy_pickle/0.16.2/0.16.2_AMD64_windows_2.7.14.pickle b/pandas/tests/io/data/legacy_pickle/0.16.2/0.16.2_AMD64_windows_2.7.14.pickle new file mode 100644 index 0000000000000..6341fa26d1f25 Binary files /dev/null and b/pandas/tests/io/data/legacy_pickle/0.16.2/0.16.2_AMD64_windows_2.7.14.pickle differ diff --git a/pandas/tests/io/data/legacy_pickle/0.19.2/0.19.2_AMD64_windows_2.7.14.pickle b/pandas/tests/io/data/legacy_pickle/0.19.2/0.19.2_AMD64_windows_2.7.14.pickle new file mode 100644 index 0000000000000..ddd88f77aa2a4 Binary files /dev/null and b/pandas/tests/io/data/legacy_pickle/0.19.2/0.19.2_AMD64_windows_2.7.14.pickle differ diff --git a/pandas/tests/io/generate_legacy_storage_files.py b/pandas/tests/io/generate_legacy_storage_files.py index 67f95c828c80e..31e2033b23d87 100755 --- a/pandas/tests/io/generate_legacy_storage_files.py +++ b/pandas/tests/io/generate_legacy_storage_files.py @@ -40,7 +40,7 @@ from pandas import (Series, DataFrame, Panel, SparseSeries, SparseDataFrame, Index, MultiIndex, bdate_range, to_msgpack, - date_range, period_range, + date_range, period_range, timedelta_range, Timestamp, NaT, Categorical, Period) from pandas.tseries.offsets import ( DateOffset, Hour, Minute, Day, @@ -116,7 +116,18 @@ def create_data(): index = dict(int=Index(np.arange(10)), date=date_range('20130101', periods=10), - period=period_range('2013-01-01', freq='M', periods=10)) + period=period_range('2013-01-01', freq='M', periods=10), + float=Index(np.arange(10, dtype=np.float64)), + uint=Index(np.arange(10, dtype=np.uint64)), + timedelta=timedelta_range('00:00:00', freq='30T', periods=10)) + + if _loose_version >= LooseVersion('0.18'): + from pandas import RangeIndex + index['range'] = RangeIndex(10) + + if _loose_version >= LooseVersion('0.21'): + from pandas import interval_range + index['interval'] = interval_range(0, periods=10) mi = dict(reg2=MultiIndex.from_tuples( tuple(zip(*[[u'bar', u'bar', u'baz', u'baz', u'foo', @@ -276,6 +287,8 @@ def create_msgpack_data(): del data['frame']['cat_onecol'] del data['frame']['cat_and_float'] del data['scalars']['period'] + del data['index']['interval'] + del data['offsets'] return _u(data)
- [x] closes #19939 - [x] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Added pre-0.20 locations of TimedeltaIndex and Float64Index to pickle_compat.py.
https://api.github.com/repos/pandas-dev/pandas/pulls/19943
2018-03-01T00:36:35Z
2018-03-04T19:58:23Z
2018-03-04T19:58:22Z
2018-03-05T19:46:46Z
REF/BUG/API: factorizing categorical data
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index c08e22af295f4..e838afdbbd083 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -843,6 +843,8 @@ Categorical - Bug in :meth:`Series.astype` and ``Categorical.astype()`` where an existing categorical data does not get updated (:issue:`10696`, :issue:`18593`) - Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`) - Bug in :class:`Series` constructor with scalar and ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19565`) +- Bug in :func:`pandas.factorize` returning the unique codes for the ``uniques``. This now returns a ``Categorical`` with the same dtype as the input (:issue:`19721`) +- Bug in :func:`pandas.factorize` including an item for missing values in the ``uniques`` return value (:issue:`19721`) Datetimelike ^^^^^^^^^^^^ diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 9101fca58d5fa..de2e638265f1e 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -435,6 +435,35 @@ def isin(comps, values): return f(comps, values) +def _factorize_array(values, check_nulls, na_sentinel=-1, size_hint=None): + """Factorize an array-like to labels and uniques. + + This doesn't do any coercion of types or unboxing before factorization. + + Parameters + ---------- + values : ndarray + check_nulls : bool + Whether to check for nulls in the hashtable's 'get_labels' method. + na_sentinel : int, default -1 + size_hint : int, optional + Passsed through to the hashtable's 'get_labels' method + + Returns + ------- + labels, uniques : ndarray + """ + (hash_klass, vec_klass), values = _get_data_algo(values, _hashtables) + + table = hash_klass(size_hint or len(values)) + uniques = vec_klass() + labels = table.get_labels(values, uniques, 0, na_sentinel, check_nulls) + + labels = _ensure_platform_int(labels) + uniques = uniques.to_array() + return labels, uniques + + @deprecate_kwarg(old_arg_name='order', new_arg_name=None) def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None): """ @@ -442,8 +471,9 @@ def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None): Parameters ---------- - values : ndarray (1-d) - Sequence + values : Sequence + ndarrays must be 1-D. Sequences that aren't pandas objects are + coereced to ndarrays before factorization. sort : boolean, default False Sort by values na_sentinel : int, default -1 @@ -458,26 +488,43 @@ def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None): Series note: an array of Periods will ignore sort as it returns an always sorted - PeriodIndex + PeriodIndex. """ + # Implementation notes: This method is responsible for 3 things + # 1.) coercing data to array-like (ndarray, Index, extension array) + # 2.) factorizing labels and uniques + # 3.) Maybe boxing the output in an Index + # + # Step 2 is dispatched to extension types (like Categorical). They are + # responsible only for factorization. All data coercion, sorting and boxing + # should happen here. values = _ensure_arraylike(values) original = values - values, dtype, _ = _ensure_data(values) - (hash_klass, vec_klass), values = _get_data_algo(values, _hashtables) - - table = hash_klass(size_hint or len(values)) - uniques = vec_klass() - check_nulls = not is_integer_dtype(original) - labels = table.get_labels(values, uniques, 0, na_sentinel, check_nulls) - labels = _ensure_platform_int(labels) - uniques = uniques.to_array() + if is_categorical_dtype(values): + values = getattr(values, '_values', values) + labels, uniques = values.factorize() + dtype = original.dtype + else: + values, dtype, _ = _ensure_data(values) + check_nulls = not is_integer_dtype(original) + labels, uniques = _factorize_array(values, check_nulls, + na_sentinel=na_sentinel, + size_hint=size_hint) if sort and len(uniques) > 0: from pandas.core.sorting import safe_sort - uniques, labels = safe_sort(uniques, labels, na_sentinel=na_sentinel, - assume_unique=True) + try: + order = uniques.argsort() + order2 = order.argsort() + labels = take_1d(order2, labels, fill_value=na_sentinel) + uniques = uniques.take(order) + except TypeError: + # Mixed types, where uniques.argsort fails. + uniques, labels = safe_sort(uniques, labels, + na_sentinel=na_sentinel, + assume_unique=True) uniques = _reconstruct_data(uniques, dtype, original) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index e23dc3b3e5b89..b37f88d8bfdce 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -7,6 +7,7 @@ from pandas import compat from pandas.compat import u, lzip from pandas._libs import lib, algos as libalgos +from pandas._libs.tslib import iNaT from pandas.core.dtypes.generic import ( ABCSeries, ABCIndexClass, ABCCategoricalIndex) @@ -364,10 +365,6 @@ def __init__(self, values, categories=None, ordered=None, dtype=None, self._dtype = self._dtype.update_dtype(dtype) self._codes = coerce_indexer_dtype(codes, dtype.categories) - @classmethod - def _constructor_from_sequence(cls, scalars): - return cls(scalars) - @property def categories(self): """The categories of this categorical. @@ -425,6 +422,10 @@ def _ndarray_values(self): def _constructor(self): return Categorical + @classmethod + def _constructor_from_sequence(cls, scalars): + return Categorical(scalars) + def copy(self): """ Copy constructor. """ return self._constructor(values=self._codes.copy(), @@ -2072,6 +2073,60 @@ def unique(self): take_codes = sorted(take_codes) return cat.set_categories(cat.categories.take(take_codes)) + def factorize(self, na_sentinel=-1): + """Encode the Categorical as an enumerated type. + + Parameters + ---------- + sort : boolean, default False + Sort by values + na_sentinel: int, default -1 + Value to mark "not found" + + Returns + ------- + labels : ndarray + An integer NumPy array that's an indexer into the original + Categorical + uniques : Categorical + A Categorical whose values are the unique values and + whose dtype matches the original CategoricalDtype. Note that if + there any unobserved categories in ``self`` will not be present + in ``uniques.values``. They will be present in + ``uniques.categories`` + + Examples + -------- + >>> cat = pd.Categorical(['a', 'a', 'c'], categories=['a', 'b', 'c']) + >>> labels, uniques = cat.factorize() + >>> labels + (array([0, 0, 1]), + >>> uniques + [a, c] + Categories (3, object): [a, b, c]) + + Missing values are handled + + >>> labels, uniques = pd.factorize(pd.Categorical(['a', 'b', None])) + >>> labels + array([ 0, 1, -1]) + >>> uniques + [a, b] + Categories (2, object): [a, b] + """ + from pandas.core.algorithms import _factorize_array + + codes = self.codes.astype('int64') + codes[codes == -1] = iNaT + # We set missing codes, normally -1, to iNaT so that the + # Int64HashTable treats them as missing values. + labels, uniques = _factorize_array(codes, check_nulls=True, + na_sentinel=na_sentinel) + uniques = self._constructor(self.categories.take(uniques), + categories=self.categories, + ordered=self.ordered) + return labels, uniques + def equals(self, other): """ Returns True if categorical arrays are equal. diff --git a/pandas/tests/categorical/test_algos.py b/pandas/tests/categorical/test_algos.py new file mode 100644 index 0000000000000..61764ec0ff632 --- /dev/null +++ b/pandas/tests/categorical/test_algos.py @@ -0,0 +1,49 @@ +import pytest +import numpy as np + +import pandas as pd +import pandas.util.testing as tm + + +@pytest.mark.parametrize('ordered', [True, False]) +@pytest.mark.parametrize('categories', [ + ['b', 'a', 'c'], + ['a', 'b', 'c', 'd'], +]) +def test_factorize(categories, ordered): + cat = pd.Categorical(['b', 'b', 'a', 'c', None], + categories=categories, + ordered=ordered) + labels, uniques = pd.factorize(cat) + expected_labels = np.array([0, 0, 1, 2, -1], dtype='int64') + expected_uniques = pd.Categorical(['b', 'a', 'c'], + categories=categories, + ordered=ordered) + + tm.assert_numpy_array_equal(labels, expected_labels) + tm.assert_categorical_equal(uniques, expected_uniques) + + +def test_factorized_sort(): + cat = pd.Categorical(['b', 'b', None, 'a']) + labels, uniques = pd.factorize(cat, sort=True) + expected_labels = np.array([1, 1, -1, 0], dtype='int64') + expected_uniques = pd.Categorical(['a', 'b']) + + tm.assert_numpy_array_equal(labels, expected_labels) + tm.assert_categorical_equal(uniques, expected_uniques) + + +def test_factorized_sort_ordered(): + cat = pd.Categorical(['b', 'b', None, 'a'], + categories=['c', 'b', 'a'], + ordered=True) + + labels, uniques = pd.factorize(cat, sort=True) + expected_labels = np.array([0, 0, -1, 1], dtype='int64') + expected_uniques = pd.Categorical(['b', 'a'], + categories=['c', 'b', 'a'], + ordered=True) + + tm.assert_numpy_array_equal(labels, expected_labels) + tm.assert_categorical_equal(uniques, expected_uniques)
This changes / fixes how Categorical data are factorized. The return value of a factorized categorical is now `Tuple[ndarray[int], Categorical]`. Before ```python In [2]: l, u = pd.factorize(pd.Categorical(['a', 'a', 'b'])) In [3]: l Out[3]: array([0, 0, 1]) In [4]: u Out[4]: array([0, 1]) ``` after ```python In [2]: l, u = pd.factorize(pd.Categorical(['a', 'a', 'b'])) In [3]: l Out[3]: array([0, 0, 1]) In [4]: u Out[4]: [a, b] Categories (2, object): [a, b] ``` The implementation is similar to `.unique`. 1. The algo (`pd.factorize`, `pd.unique`) handles unboxing / dtype coercion 2. The algo dispatches the actual array factorization for extension types 3. The algo boxes the output if necessary, depending on the input. I've implemented this as a new public method on ``Categorical``, mainly since this is what we do for unique, and I think it's a useful method to have. This fixes a bug in factorizing categoricals with missing values. Previously, we included -1 in the uniques. Before ```python In [2]: l, u = pd.factorize(pd.Categorical(['a', 'a', 'b', None])) In [3]: u Out[3]: array([ 0, 1, -1]) ``` After ```python In [2]: l, u = pd.factorize(pd.Categorical(['a', 'a', 'b', None])) In [3]: u Out[3]: [a, b] Categories (2, object): [a, b] ``` xref #19721. This doesn't close it, as I haven't addressed the issue of what `factorize(Series[EA])` should return. Just fixing the categorical bugs.
https://api.github.com/repos/pandas-dev/pandas/pulls/19938
2018-02-28T15:19:15Z
2018-03-15T10:40:59Z
2018-03-15T10:40:59Z
2018-05-02T13:10:14Z
Making to_datetime('today') and Timestamp('today') consistent
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 1ede0310aa902..08363cd54c606 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -652,6 +652,7 @@ Other API Changes - Set operations (union, difference...) on :class:`IntervalIndex` with incompatible index types will now raise a ``TypeError`` rather than a ``ValueError`` (:issue:`19329`) - :class:`DateOffset` objects render more simply, e.g. ``<DateOffset: days=1>`` instead of ``<DateOffset: kwds={'days': 1}>`` (:issue:`19403`) - ``Categorical.fillna`` now validates its ``value`` and ``method`` keyword arguments. It now raises when both or none are specified, matching the behavior of :meth:`Series.fillna` (:issue:`19682`) +- ``pd.to_datetime('today')`` now returns a datetime, consistent with ``pd.Timestamp('today')``; previously ``pd.to_datetime('today')`` returned a ``.normalized()`` datetime (:issue:`19935`) - :func:`Series.str.replace` now takes an optional `regex` keyword which, when set to ``False``, uses literal string replacement rather than regex replacement (:issue:`16808`) .. _whatsnew_0230.deprecations: diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index fec7f21d6e6eb..17453d8af1297 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -755,8 +755,7 @@ cdef inline bint _parse_today_now(str val, int64_t* iresult): iresult[0] = Timestamp.utcnow().value return True elif val == 'today': - # Note: this is *not* the same as Timestamp('today') - iresult[0] = Timestamp.now().normalize().value + iresult[0] = Timestamp.today().value return True return False diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index fbf0977a04d82..0d42b6e9692fe 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -224,27 +224,34 @@ def test_to_datetime_today(self): # this both of these timezones _and_ UTC will all be in the same day, # so this test will not detect the regression introduced in #18666. with tm.set_timezone('Pacific/Auckland'): # 12-13 hours ahead of UTC - nptoday = np.datetime64('today').astype('datetime64[ns]') + nptoday = np.datetime64('today')\ + .astype('datetime64[ns]').astype(np.int64) pdtoday = pd.to_datetime('today') pdtoday2 = pd.to_datetime(['today'])[0] + tstoday = pd.Timestamp('today') + tstoday2 = pd.Timestamp.today() + # These should all be equal with infinite perf; this gives # a generous margin of 10 seconds - assert abs(pdtoday.value - nptoday.astype(np.int64)) < 1e10 - assert abs(pdtoday2.value - nptoday.astype(np.int64)) < 1e10 + assert abs(pdtoday.normalize().value - nptoday) < 1e10 + assert abs(pdtoday2.normalize().value - nptoday) < 1e10 + assert abs(pdtoday.value - tstoday.value) < 1e10 + assert abs(pdtoday.value - tstoday2.value) < 1e10 assert pdtoday.tzinfo is None assert pdtoday2.tzinfo is None with tm.set_timezone('US/Samoa'): # 11 hours behind UTC - nptoday = np.datetime64('today').astype('datetime64[ns]') + nptoday = np.datetime64('today')\ + .astype('datetime64[ns]').astype(np.int64) pdtoday = pd.to_datetime('today') pdtoday2 = pd.to_datetime(['today'])[0] # These should all be equal with infinite perf; this gives # a generous margin of 10 seconds - assert abs(pdtoday.value - nptoday.astype(np.int64)) < 1e10 - assert abs(pdtoday2.value - nptoday.astype(np.int64)) < 1e10 + assert abs(pdtoday.normalize().value - nptoday) < 1e10 + assert abs(pdtoday2.normalize().value - nptoday) < 1e10 assert pdtoday.tzinfo is None assert pdtoday2.tzinfo is None
This PR changes `pd.to_datetime` to be consistent with `Timestamp('today')`. - [x] closes #19935 - [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/19937
2018-02-28T15:09:56Z
2018-03-01T23:02:32Z
2018-03-01T23:02:32Z
2018-03-01T23:02:35Z
DOC: add doc on ExtensionArray and extending pandas
diff --git a/doc/source/developer.rst b/doc/source/developer.rst index 0ef097da090f2..b8bb2b2fcbe2f 100644 --- a/doc/source/developer.rst +++ b/doc/source/developer.rst @@ -140,46 +140,3 @@ As an example of fully-formed metadata: 'metadata': None} ], 'pandas_version': '0.20.0'} - -.. _developer.register-accessors: - -Registering Custom Accessors ----------------------------- - -Libraries can use the decorators -:func:`pandas.api.extensions.register_dataframe_accessor`, -:func:`pandas.api.extensions.register_series_accessor`, and -:func:`pandas.api.extensions.register_index_accessor`, to add additional "namespaces" to -pandas objects. All of these follow a similar convention: you decorate a class, providing the name of attribute to add. The -class's `__init__` method gets the object being decorated. For example: - -.. code-block:: python - - @pd.api.extensions.register_dataframe_accessor("geo") - class GeoAccessor(object): - def __init__(self, pandas_obj): - self._obj = pandas_obj - - @property - def center(self): - # return the geographic center point of this DataFarme - lon = self._obj.latitude - lat = self._obj.longitude - return (float(lon.mean()), float(lat.mean())) - - def plot(self): - # plot this array's data on a map, e.g., using Cartopy - pass - -Now users can access your methods using the `geo` namespace: - - >>> ds = pd.DataFrame({'longitude': np.linspace(0, 10), - ... 'latitude': np.linspace(0, 20)}) - >>> ds.geo.center - (5.0, 10.0) - >>> ds.geo.plot() - # plots data on a map - -This can be a convenient way to extend pandas objects without subclassing them. -If you write a custom accessor, make a pull request adding it to our -:ref:`ecosystem` page. diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index c770bf2851643..30cdb06b28487 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -262,3 +262,38 @@ Data validation Engarde is a lightweight library used to explicitly state your assumptions abour your datasets and check that they're *actually* true. + +.. _ecosystem.extensions: + +Extension Data Types +-------------------- + +Pandas provides an interface for defining +:ref:`extension types <extending.extension-types>` to extend NumPy's type +system. The following libraries implement that interface to provide types not +found in NumPy or pandas, which work well with pandas' data containers. + +`cyberpandas`_ +~~~~~~~~~~~~~~ + +Cyberpandas provides an extension type for storing arrays of IP Addresses. These +arrays can be stored inside pandas' Series and DataFrame. + +.. _ecosystem.accessors: + +Accessors +--------- + +A directory of projects providing +:ref:`extension accessors <extending.register-accessors>`. This is for users to +discover new accessors and for library authors to coordinate on the namespace. + +============== ========== ========================= +Library Accessor Classes +============== ========== ========================= +`cyberpandas`_ ``ip`` ``Series`` +`pdvega`_ ``vgplot`` ``Series``, ``DataFrame`` +============== ========== ========================= + +.. _cyberpandas: https://cyberpandas.readthedocs.io/en/latest +.. _pdvega: https://jakevdp.github.io/pdvega/ diff --git a/doc/source/extending.rst b/doc/source/extending.rst new file mode 100644 index 0000000000000..25c4ba4a4a2a3 --- /dev/null +++ b/doc/source/extending.rst @@ -0,0 +1,269 @@ +.. _extending: + +**************** +Extending Pandas +**************** + +While pandas provides a rich set of methods, containers, and data types, your +needs may not be fully satisfied. Pandas offers a few options for extending +pandas. + +.. _extending.register-accessors: + +Registering Custom Accessors +---------------------------- + +Libraries can use the decorators +:func:`pandas.api.extensions.register_dataframe_accessor`, +:func:`pandas.api.extensions.register_series_accessor`, and +:func:`pandas.api.extensions.register_index_accessor`, to add additional +"namespaces" to pandas objects. All of these follow a similar convention: you +decorate a class, providing the name of attribute to add. The class's +``__init__`` method gets the object being decorated. For example: + +.. code-block:: python + + @pd.api.extensions.register_dataframe_accessor("geo") + class GeoAccessor(object): + def __init__(self, pandas_obj): + self._obj = pandas_obj + + @property + def center(self): + # return the geographic center point of this DataFrame + lat = self._obj.latitude + lon = self._obj.longitude + return (float(lon.mean()), float(lat.mean())) + + def plot(self): + # plot this array's data on a map, e.g., using Cartopy + pass + +Now users can access your methods using the ``geo`` namespace: + + >>> ds = pd.DataFrame({'longitude': np.linspace(0, 10), + ... 'latitude': np.linspace(0, 20)}) + >>> ds.geo.center + (5.0, 10.0) + >>> ds.geo.plot() + # plots data on a map + +This can be a convenient way to extend pandas objects without subclassing them. +If you write a custom accessor, make a pull request adding it to our +:ref:`ecosystem` page. + +.. _extending.extension-types: + +Extension Types +--------------- + +Pandas defines an interface for implementing data types and arrays that *extend* +NumPy's type system. Pandas itself uses the extension system for some types +that aren't built into NumPy (categorical, period, interval, datetime with +timezone). + +Libraries can define a custom array and data type. When pandas encounters these +objects, they will be handled properly (i.e. not converted to an ndarray of +objects). Many methods like :func:`pandas.isna` will dispatch to the extension +type's implementation. + +If you're building a library that implements the interface, please publicize it +on :ref:`ecosystem.extensions`. + +The interface consists of two classes. + +``ExtensionDtype`` +^^^^^^^^^^^^^^^^^^ + +An ``ExtensionDtype`` is similar to a ``numpy.dtype`` object. It describes the +data type. Implementors are responsible for a few unique items like the name. + +One particularly important item is the ``type`` property. This should be the +class that is the scalar type for your data. For example, if you were writing an +extension array for IP Address data, this might be ``ipaddress.IPv4Address``. + +See the `extension dtype source`_ for interface definition. + +``ExtensionArray`` +^^^^^^^^^^^^^^^^^^ + +This class provides all the array-like functionality. ExtensionArrays are +limited to 1 dimension. An ExtensionArray is linked to an ExtensionDtype via the +``dtype`` attribute. + +Pandas makes no restrictions on how an extension array is created via its +``__new__`` or ``__init__``, and puts no restrictions on how you store your +data. We do require that your array be convertible to a NumPy array, even if +this is relatively expensive (as it is for ``Categorical``). + +They may be backed by none, one, or many NumPy arrays. For example, +``pandas.Categorical`` is an extension array backed by two arrays, +one for codes and one for categories. An array of IPv6 addresses may +be backed by a NumPy structured array with two fields, one for the +lower 64 bits and one for the upper 64 bits. Or they may be backed +by some other storage type, like Python lists. + +See the `extension array source`_ for the interface definition. The docstrings +and comments contain guidance for properly implementing the interface. + +.. _extension dtype source: https://github.com/pandas-dev/pandas/blob/master/pandas/core/dtypes/base.py +.. _extension array source: https://github.com/pandas-dev/pandas/blob/master/pandas/core/arrays/base.py + +.. _extending.subclassing-pandas: + +Subclassing pandas Data Structures +---------------------------------- + +.. warning:: There are some easier alternatives before considering subclassing ``pandas`` data structures. + + 1. Extensible method chains with :ref:`pipe <basics.pipe>` + + 2. Use *composition*. See `here <http://en.wikipedia.org/wiki/Composition_over_inheritance>`_. + + 3. Extending by :ref:`registering an accessor <extending.register-accessors>` + + 4. Extending by :ref:`extension type <extending.extension-types>` + +This section describes how to subclass ``pandas`` data structures to meet more specific needs. There are two points that need attention: + +1. Override constructor properties. +2. Define original properties + +.. note:: + + You can find a nice example in `geopandas <https://github.com/geopandas/geopandas>`_ project. + +Override Constructor Properties +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Each data structure has several *constructor properties* for returning a new +data structure as the result of an operation. By overriding these properties, +you can retain subclasses through ``pandas`` data manipulations. + +There are 3 constructor properties to be defined: + +- ``_constructor``: Used when a manipulation result has the same dimesions as the original. +- ``_constructor_sliced``: Used when a manipulation result has one lower dimension(s) as the original, such as ``DataFrame`` single columns slicing. +- ``_constructor_expanddim``: Used when a manipulation result has one higher dimension as the original, such as ``Series.to_frame()`` and ``DataFrame.to_panel()``. + +Following table shows how ``pandas`` data structures define constructor properties by default. + +=========================== ======================= ============= +Property Attributes ``Series`` ``DataFrame`` +=========================== ======================= ============= +``_constructor`` ``Series`` ``DataFrame`` +``_constructor_sliced`` ``NotImplementedError`` ``Series`` +``_constructor_expanddim`` ``DataFrame`` ``Panel`` +=========================== ======================= ============= + +Below example shows how to define ``SubclassedSeries`` and ``SubclassedDataFrame`` overriding constructor properties. + +.. code-block:: python + + class SubclassedSeries(Series): + + @property + def _constructor(self): + return SubclassedSeries + + @property + def _constructor_expanddim(self): + return SubclassedDataFrame + + class SubclassedDataFrame(DataFrame): + + @property + def _constructor(self): + return SubclassedDataFrame + + @property + def _constructor_sliced(self): + return SubclassedSeries + +.. code-block:: python + + >>> s = SubclassedSeries([1, 2, 3]) + >>> type(s) + <class '__main__.SubclassedSeries'> + + >>> to_framed = s.to_frame() + >>> type(to_framed) + <class '__main__.SubclassedDataFrame'> + + >>> df = SubclassedDataFrame({'A', [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) + >>> df + A B C + 0 1 4 7 + 1 2 5 8 + 2 3 6 9 + + >>> type(df) + <class '__main__.SubclassedDataFrame'> + + >>> sliced1 = df[['A', 'B']] + >>> sliced1 + A B + 0 1 4 + 1 2 5 + 2 3 6 + >>> type(sliced1) + <class '__main__.SubclassedDataFrame'> + + >>> sliced2 = df['A'] + >>> sliced2 + 0 1 + 1 2 + 2 3 + Name: A, dtype: int64 + >>> type(sliced2) + <class '__main__.SubclassedSeries'> + +Define Original Properties +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To let original data structures have additional properties, you should let ``pandas`` know what properties are added. ``pandas`` maps unknown properties to data names overriding ``__getattribute__``. Defining original properties can be done in one of 2 ways: + +1. Define ``_internal_names`` and ``_internal_names_set`` for temporary properties which WILL NOT be passed to manipulation results. +2. Define ``_metadata`` for normal properties which will be passed to manipulation results. + +Below is an example to define two original properties, "internal_cache" as a temporary property and "added_property" as a normal property + +.. code-block:: python + + class SubclassedDataFrame2(DataFrame): + + # temporary properties + _internal_names = pd.DataFrame._internal_names + ['internal_cache'] + _internal_names_set = set(_internal_names) + + # normal properties + _metadata = ['added_property'] + + @property + def _constructor(self): + return SubclassedDataFrame2 + +.. code-block:: python + + >>> df = SubclassedDataFrame2({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) + >>> df + A B C + 0 1 4 7 + 1 2 5 8 + 2 3 6 9 + + >>> df.internal_cache = 'cached' + >>> df.added_property = 'property' + + >>> df.internal_cache + cached + >>> df.added_property + property + + # properties defined in _internal_names is reset after manipulation + >>> df[['A', 'B']].internal_cache + AttributeError: 'SubclassedDataFrame2' object has no attribute 'internal_cache' + + # properties defined in _metadata are retained + >>> df[['A', 'B']].added_property + property diff --git a/doc/source/index.rst.template b/doc/source/index.rst.template index eff1227e98994..6e70fcd903f05 100644 --- a/doc/source/index.rst.template +++ b/doc/source/index.rst.template @@ -152,5 +152,6 @@ See the package overview for more detail about what's in the library. {% if not single_doc -%} developer internals + extending release {% endif -%} diff --git a/doc/source/internals.rst b/doc/source/internals.rst index 957f82fd9eba7..b120e3a98db7f 100644 --- a/doc/source/internals.rst +++ b/doc/source/internals.rst @@ -15,7 +15,8 @@ Internals ********* -This section will provide a look into some of pandas internals. +This section will provide a look into some of pandas internals. It's primarily +intended for developers of pandas itself. Indexing -------- @@ -107,156 +108,9 @@ containers (``Index`` classes and ``Series``) we have the following convention: So, for example, ``Series[category]._values`` is a ``Categorical``, while ``Series[category]._ndarray_values`` is the underlying codes. - .. _ref-subclassing-pandas: Subclassing pandas Data Structures ---------------------------------- -.. warning:: There are some easier alternatives before considering subclassing ``pandas`` data structures. - - 1. Extensible method chains with :ref:`pipe <basics.pipe>` - - 2. Use *composition*. See `here <http://en.wikipedia.org/wiki/Composition_over_inheritance>`_. - - 3. Extending by :ref:`registering an accessor <internals.register-accessors>` - -This section describes how to subclass ``pandas`` data structures to meet more specific needs. There are 2 points which need attention: - -1. Override constructor properties. -2. Define original properties - -.. note:: You can find a nice example in `geopandas <https://github.com/geopandas/geopandas>`_ project. - -Override Constructor Properties -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Each data structure has constructor properties to specifying data constructors. By overriding these properties, you can retain defined-classes through ``pandas`` data manipulations. - -There are 3 constructors to be defined: - -- ``_constructor``: Used when a manipulation result has the same dimesions as the original. -- ``_constructor_sliced``: Used when a manipulation result has one lower dimension(s) as the original, such as ``DataFrame`` single columns slicing. -- ``_constructor_expanddim``: Used when a manipulation result has one higher dimension as the original, such as ``Series.to_frame()`` and ``DataFrame.to_panel()``. - -Following table shows how ``pandas`` data structures define constructor properties by default. - -=========================== ======================= =================== ======================= -Property Attributes ``Series`` ``DataFrame`` ``Panel`` -=========================== ======================= =================== ======================= -``_constructor`` ``Series`` ``DataFrame`` ``Panel`` -``_constructor_sliced`` ``NotImplementedError`` ``Series`` ``DataFrame`` -``_constructor_expanddim`` ``DataFrame`` ``Panel`` ``NotImplementedError`` -=========================== ======================= =================== ======================= - -Below example shows how to define ``SubclassedSeries`` and ``SubclassedDataFrame`` overriding constructor properties. - -.. code-block:: python - - class SubclassedSeries(Series): - - @property - def _constructor(self): - return SubclassedSeries - - @property - def _constructor_expanddim(self): - return SubclassedDataFrame - - class SubclassedDataFrame(DataFrame): - - @property - def _constructor(self): - return SubclassedDataFrame - - @property - def _constructor_sliced(self): - return SubclassedSeries - -.. code-block:: python - - >>> s = SubclassedSeries([1, 2, 3]) - >>> type(s) - <class '__main__.SubclassedSeries'> - - >>> to_framed = s.to_frame() - >>> type(to_framed) - <class '__main__.SubclassedDataFrame'> - - >>> df = SubclassedDataFrame({'A', [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) - >>> df - A B C - 0 1 4 7 - 1 2 5 8 - 2 3 6 9 - - >>> type(df) - <class '__main__.SubclassedDataFrame'> - - >>> sliced1 = df[['A', 'B']] - >>> sliced1 - A B - 0 1 4 - 1 2 5 - 2 3 6 - >>> type(sliced1) - <class '__main__.SubclassedDataFrame'> - - >>> sliced2 = df['A'] - >>> sliced2 - 0 1 - 1 2 - 2 3 - Name: A, dtype: int64 - >>> type(sliced2) - <class '__main__.SubclassedSeries'> - -Define Original Properties -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To let original data structures have additional properties, you should let ``pandas`` know what properties are added. ``pandas`` maps unknown properties to data names overriding ``__getattribute__``. Defining original properties can be done in one of 2 ways: - -1. Define ``_internal_names`` and ``_internal_names_set`` for temporary properties which WILL NOT be passed to manipulation results. -2. Define ``_metadata`` for normal properties which will be passed to manipulation results. - -Below is an example to define 2 original properties, "internal_cache" as a temporary property and "added_property" as a normal property - -.. code-block:: python - - class SubclassedDataFrame2(DataFrame): - - # temporary properties - _internal_names = pd.DataFrame._internal_names + ['internal_cache'] - _internal_names_set = set(_internal_names) - - # normal properties - _metadata = ['added_property'] - - @property - def _constructor(self): - return SubclassedDataFrame2 - -.. code-block:: python - - >>> df = SubclassedDataFrame2({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) - >>> df - A B C - 0 1 4 7 - 1 2 5 8 - 2 3 6 9 - - >>> df.internal_cache = 'cached' - >>> df.added_property = 'property' - - >>> df.internal_cache - cached - >>> df.added_property - property - - # properties defined in _internal_names is reset after manipulation - >>> df[['A', 'B']].internal_cache - AttributeError: 'SubclassedDataFrame2' object has no attribute 'internal_cache' - - # properties defined in _metadata are retained - >>> df[['A', 'B']].added_property - property +This section has been moved to :ref:`extending.subclassing-pandas`. diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt index b1e8aa10457f8..9e1dc391d7ace 100644 --- a/doc/source/whatsnew/v0.16.1.txt +++ b/doc/source/whatsnew/v0.16.1.txt @@ -313,7 +313,7 @@ Other Enhancements - Add/delete ``str/dt/cat`` accessors dynamically from ``__dir__``. (:issue:`9910`) - Add ``normalize`` as a ``dt`` accessor method. (:issue:`10047`) -- ``DataFrame`` and ``Series`` now have ``_constructor_expanddim`` property as overridable constructor for one higher dimensionality data. This should be used only when it is really needed, see :ref:`here <ref-subclassing-pandas>` +- ``DataFrame`` and ``Series`` now have ``_constructor_expanddim`` property as overridable constructor for one higher dimensionality data. This should be used only when it is really needed, see :ref:`here <extending.subclassing-pandas>` - ``pd.lib.infer_dtype`` now returns ``'bytes'`` in Python 3 where appropriate. (:issue:`10032`) diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py index 96bf628c8d7ff..06c4068f86bfe 100644 --- a/pandas/core/accessor.py +++ b/pandas/core/accessor.py @@ -191,9 +191,9 @@ def __init__(self, pandas_obj): @property def center(self): - # return the geographic center point of this DataFarme - lon = self._obj.latitude - lat = self._obj.longitude + # return the geographic center point of this DataFrame + lat = self._obj.latitude + lon = self._obj.longitude return (float(lon.mean()), float(lat.mean())) def plot(self):
- Added a new page on extending pandas - Added some prose on extension arrays / extension dtypes - Moved subclassing there - Added a section to ecosystem.rst about libraries providing extension types and accessors.
https://api.github.com/repos/pandas-dev/pandas/pulls/19936
2018-02-28T13:00:28Z
2018-03-06T15:38:33Z
2018-03-06T15:38:32Z
2018-05-02T13:10:21Z
DOC: fix Series.reset_index example
diff --git a/pandas/core/series.py b/pandas/core/series.py index 6822f1f6b58b5..660bf3f5d4805 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1021,31 +1021,31 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False): >>> s = pd.Series([1, 2, 3, 4], index=pd.Index(['a', 'b', 'c', 'd'], ... name = 'idx')) >>> s.reset_index() - idx 0 - 0 0 1 - 1 1 2 - 2 2 3 - 3 3 4 + idx 0 + 0 a 1 + 1 b 2 + 2 c 3 + 3 d 4 >>> arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', ... 'foo', 'qux', 'qux']), ... np.array(['one', 'two', 'one', 'two', 'one', 'two', ... 'one', 'two'])] >>> s2 = pd.Series( - ... np.random.randn(8), + ... range(8), ... index=pd.MultiIndex.from_arrays(arrays, ... names=['a', 'b'])) >>> s2.reset_index(level='a') - a 0 + a 0 b - one bar -0.286320 - two bar -0.587934 - one baz 0.710491 - two baz -1.429006 - one foo 0.790700 - two foo 0.824863 - one qux -0.718963 - two qux -0.055028 + one bar 0 + two bar 1 + one baz 2 + two baz 3 + one foo 4 + two foo 5 + one qux 6 + two qux 7 """ inplace = validate_bool_kwarg(inplace, 'inplace') if drop:
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Show correct values in idx column.
https://api.github.com/repos/pandas-dev/pandas/pulls/19930
2018-02-27T21:12:59Z
2018-02-28T08:05:56Z
2018-02-28T08:05:56Z
2018-02-28T08:06:11Z
Add CodeTriage badge to pandas-dev/pandas
diff --git a/README.md b/README.md index 4b9c9505e320a..86cf95508a5d9 100644 --- a/README.md +++ b/README.md @@ -216,13 +216,16 @@ Further, general questions and discussions can also take place on the [pydata ma ## Discussion and Development 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 +## Contributing to pandas [![Open Source Helpers](https://www.codetriage.com/pandas-dev/pandas/badges/users.svg)](https://www.codetriage.com/pandas-dev/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.](https://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. +You can also triage issues which may include reproducing bug reports, or asking for vital information such as version numbers or reproduction instructions. If you would like to start triaging issues, one easy way to get started is to [subscribe to pandas on CodeTriage](https://www.codetriage.com/pandas-dev/pandas). + 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! 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).
Adds a badge showing the number of people helping this repo on CodeTriage. [![Open Source Helpers](https://www.codetriage.com/pandas-dev/pandas/badges/users.svg)](https://www.codetriage.com/pandas-dev/pandas) ## What is CodeTriage? CodeTriage is an Open Source app that is designed to make contributing to Open Source projects easier. It works by sending subscribers a few open issues in their inbox. If subscribers get busy, there is an algorithm that backs off issue load so they do not get overwhelmed [Read more about the CodeTriage project](https://www.codetriage.com/what). ## Why am I getting this PR? Your project was picked by the human, @schneems. They selected it from the projects submitted to https://www.codetriage.com and hand edited the PR. How did your project get added to [CodeTriage](https://www.codetriage.com/what)? Roughly about 1 year ago, [vinayaugustine](https://github.com/vinayaugustine) added this project to CodeTriage in order to start contributing. Since then, 207 people have subscribed to help this repo. ## What does adding a badge accomplish? Adding a badge invites people to help contribute to your project. It also lets developers know that others are invested in the longterm success and maintainability of the project. You can see an example of a CodeTriage badge on these popular OSS READMEs: - [![Email clients like GMAIL do not render SVG images](https://www.codetriage.com/rails/rails/badges/users.svg)](https://www.codetriage.com/rails/rails) https://github.com/rails/rails - [![Email clients like GMAIL do not render SVG images](https://www.codetriage.com/crystal-lang/crystal/badges/users.svg)](https://www.codetriage.com/crystal-lang/crystal) https://github.com/crystal-lang/crystal ## Have a question or comment? While I am a bot, this PR was manually reviewed and monitored by a human - @schneems. My job is writing commit messages and handling PR logistics. If you have any questions, you can reply back to this PR and they will be answered by @schneems. If you do not want a badge right now, no worries, close the PR, you will not hear from me again. Thanks for making your project Open Source! Any feedback is greatly appreciated.
https://api.github.com/repos/pandas-dev/pandas/pulls/19928
2018-02-27T20:41:15Z
2018-02-28T11:07:28Z
2018-02-28T11:07:28Z
2018-02-28T11:07:32Z
Added seek to buffer to fix xlwt asv failure
diff --git a/pandas/io/excel.py b/pandas/io/excel.py index 0d3d4286f5a3c..78af86cc00f7f 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -387,6 +387,10 @@ def __init__(self, io, **kwds): self.book = io elif not isinstance(io, xlrd.Book) and hasattr(io, "read"): # N.B. xlrd.Book has a read attribute too + if hasattr(io, 'seek'): + # GH 19779 + io.seek(0) + data = io.read() self.book = xlrd.open_workbook(file_contents=data) elif isinstance(self._io, compat.string_types):
- [X] closes #19779 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Sample ASV results from this as follows. Across 5 runs I got the upstream/master error every time and none on HEAD ```bash (pandas_dev) williams-imac:asv_bench williamayd$ asv continuous -f 1.1 upstream/master HEAD -b io.excel.Excel.time_read_excel --show-stderr · Creating environments · Discovering benchmarks ·· Uninstalling from conda-py3.6-Cython-matplotlib-numexpr-numpy-openpyxl-pytables-pytest-scipy-sqlalchemy-xlrd-xlsxwriter-xlwt. ·· Installing into conda-py3.6-Cython-matplotlib-numexpr-numpy-openpyxl-pytables-pytest-scipy-sqlalchemy-xlrd-xlsxwriter-xlwt.. · Running 2 total benchmarks (2 commits * 1 environments * 1 benchmarks) [ 0.00%] · For pandas commit hash 15cd9d2d: [ 0.00%] ·· Building for conda-py3.6-Cython-matplotlib-numexpr-numpy-openpyxl-pytables-pytest-scipy-sqlalchemy-xlrd-xlsxwriter-xlwt... [ 0.00%] ·· Benchmarking conda-py3.6-Cython-matplotlib-numexpr-numpy-openpyxl-pytables-pytest-scipy-sqlalchemy-xlrd-xlsxwriter-xlwt [ 50.00%] ··· Running io.excel.Excel.time_read_excel ok [ 50.00%] ···· ============ ============= engine ------------ ------------- openpyxl 133±4ms xlsxwriter 118±0.7ms xlwt 54.2±0.05ms ============ ============= [ 50.00%] · For pandas commit hash f4c9d966: [ 50.00%] ·· Building for conda-py3.6-Cython-matplotlib-numexpr-numpy-openpyxl-pytables-pytest-scipy-sqlalchemy-xlrd-xlsxwriter-xlwt... [ 50.00%] ·· Benchmarking conda-py3.6-Cython-matplotlib-numexpr-numpy-openpyxl-pytables-pytest-scipy-sqlalchemy-xlrd-xlsxwriter-xlwt [100.00%] ··· Running io.excel.Excel.time_read_excel 1/3 failed [100.00%] ···· ============ =========== engine ------------ ----------- openpyxl 130±0.7ms xlsxwriter 117±0.4ms xlwt failed ============ =========== [100.00%] ····· For parameters: 'xlwt' Traceback (most recent call last): File "/Users/williamayd/miniconda3/envs/pandas_dev/lib/python3.6/site-packages/asv/benchmark.py", line 867, in <module> commands[mode](args) File "/Users/williamayd/miniconda3/envs/pandas_dev/lib/python3.6/site-packages/asv/benchmark.py", line 844, in main_run result = benchmark.do_run() File "/Users/williamayd/miniconda3/envs/pandas_dev/lib/python3.6/site-packages/asv/benchmark.py", line 398, in do_run return self.run(*self._current_params) File "/Users/williamayd/miniconda3/envs/pandas_dev/lib/python3.6/site-packages/asv/benchmark.py", line 473, in run samples, number = self.benchmark_timing(timer, repeat, warmup_time, number=number) File "/Users/williamayd/miniconda3/envs/pandas_dev/lib/python3.6/site-packages/asv/benchmark.py", line 500, in benchmark_timing timing = timer.timeit(number) File "/Users/williamayd/clones/pandas/asv_bench/env/83b3be1235aa7b08e8a17448e2f70790/lib/python3.6/timeit.py", line 178, in timeit timing = self.inner(it, self.timer) File "<timeit-src>", line 6, in inner File "/Users/williamayd/miniconda3/envs/pandas_dev/lib/python3.6/site-packages/asv/benchmark.py", line 464, in <lambda> func = lambda: self.func(*param) File "/Users/williamayd/clones/pandas/asv_bench/benchmarks/io/excel.py", line 29, in time_read_excel read_excel(self.bio_read) File "/Users/williamayd/clones/pandas/asv_bench/env/83b3be1235aa7b08e8a17448e2f70790/lib/python3.6/site-packages/pandas/util/_decorators.py", line 172, in wrapper return func(*args, **kwargs) File "/Users/williamayd/clones/pandas/asv_bench/env/83b3be1235aa7b08e8a17448e2f70790/lib/python3.6/site-packages/pandas/util/_decorators.py", line 172, in wrapper return func(*args, **kwargs) File "/Users/williamayd/clones/pandas/asv_bench/env/83b3be1235aa7b08e8a17448e2f70790/lib/python3.6/site-packages/pandas/io/excel.py", line 315, in read_excel io = ExcelFile(io, engine=engine) File "/Users/williamayd/clones/pandas/asv_bench/env/83b3be1235aa7b08e8a17448e2f70790/lib/python3.6/site-packages/pandas/io/excel.py", line 391, in __init__ self.book = xlrd.open_workbook(file_contents=data) File "/Users/williamayd/clones/pandas/asv_bench/env/83b3be1235aa7b08e8a17448e2f70790/lib/python3.6/site-packages/xlrd/__init__.py", line 116, in open_workbook with open(filename, "rb") as f: TypeError: expected str, bytes or os.PathLike object, not NoneType SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/19926
2018-02-27T16:01:35Z
2018-02-27T21:28:23Z
2018-02-27T21:28:23Z
2018-02-28T00:54:52Z
TST: Debug flaky plotting test
diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 94adf349fe2cd..08a047a2e7707 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -689,14 +689,17 @@ def test_mixed_freq_regular_first(self): s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]] # it works! - s1.plot() + _, ax = self.plt.subplots() + s1.plot(ax=ax) - ax2 = s2.plot(style='g') + ax2 = s2.plot(style='g', ax=ax) lines = ax2.get_lines() idx1 = PeriodIndex(lines[0].get_xdata()) idx2 = PeriodIndex(lines[1].get_xdata()) - assert idx1.equals(s1.index.to_period('B')) - assert idx2.equals(s2.index.to_period('B')) + + tm.assert_index_equal(idx1, s1.index.to_period('B')) + tm.assert_index_equal(idx2, s2.index.to_period('B')) + left, right = ax2.get_xlim() pidx = s1.index.to_period() assert left <= pidx[0].ordinal
Maybe closes https://github.com/pandas-dev/pandas/issues/19924. I can't reproduce this locally so who knows. A while back I went through and added `plt.subplots()` and explicit `ax=ax` to a bunch of the plotting tests. I apparently missed this one. It seemed to help, but they're flaky tests so who knows. Also chanegd `idx1.equals(idx2)` to `tm.assert_frame_equal` so we get a better error message when it does fail.
https://api.github.com/repos/pandas-dev/pandas/pulls/19925
2018-02-27T15:47:51Z
2018-02-27T21:31:56Z
2018-02-27T21:31:56Z
2018-05-02T13:10:22Z
DOC: fixes pipe example in basics.rst due to statsmodel changes
diff --git a/doc/source/basics.rst b/doc/source/basics.rst index e1b36a6acad70..8d09f1fc04c1f 100644 --- a/doc/source/basics.rst +++ b/doc/source/basics.rst @@ -746,7 +746,7 @@ What if the function you wish to apply takes its data as, say, the second argume In this case, provide ``pipe`` with a tuple of ``(callable, data_keyword)``. ``.pipe`` will route the ``DataFrame`` to the argument specified in the tuple. -For example, we can fit a regression using statsmodels. Their API expects a formula first and a ``DataFrame`` as the second argument, ``data``. We pass in the function, keyword pair ``(sm.poisson, 'data')`` to ``pipe``: +For example, we can fit a regression using statsmodels. Their API expects a formula first and a ``DataFrame`` as the second argument, ``data``. We pass in the function, keyword pair ``(sm.ols, 'data')`` to ``pipe``: .. ipython:: python @@ -756,7 +756,7 @@ For example, we can fit a regression using statsmodels. Their API expects a form (bb.query('h > 0') .assign(ln_h = lambda df: np.log(df.h)) - .pipe((sm.poisson, 'data'), 'hr ~ ln_h + year + g + C(lg)') + .pipe((sm.ols, 'data'), 'hr ~ ln_h + year + g + C(lg)') .fit() .summary() ) diff --git a/doc/source/whatsnew/v0.16.2.txt b/doc/source/whatsnew/v0.16.2.txt index bfe44290e49d2..91ec0c3038985 100644 --- a/doc/source/whatsnew/v0.16.2.txt +++ b/doc/source/whatsnew/v0.16.2.txt @@ -63,10 +63,10 @@ of ``(function, keyword)`` indicating where the DataFrame should flow. For examp bb = pd.read_csv('data/baseball.csv', index_col='id') - # sm.poisson takes (formula, data) + # sm.ols takes (formula, data) (bb.query('h > 0') .assign(ln_h = lambda df: np.log(df.h)) - .pipe((sm.poisson, 'data'), 'hr ~ ln_h + year + g + C(lg)') + .pipe((sm.ols, 'data'), 'hr ~ ln_h + year + g + C(lg)') .fit() .summary() )
To work around changes in statsmodel api. - [ ] closes #19713 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/19923
2018-02-27T03:04:00Z
2018-02-28T08:14:24Z
2018-02-28T08:14:24Z
2018-02-28T08:14:35Z
Consistent Timedelta Writing for all Excel Engines
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 5330f7e7e998b..6865428c352c1 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -867,7 +867,7 @@ I/O - Bug in :func:`read_json` where large numeric values were causing an ``OverflowError`` (:issue:`18842`) - Bug in :func:`DataFrame.to_parquet` where an exception was raised if the write destination is S3 (:issue:`19134`) - :class:`Interval` now supported in :func:`DataFrame.to_excel` for all Excel file types (:issue:`19242`) -- :class:`Timedelta` now supported in :func:`DataFrame.to_excel` for xls file type (:issue:`19242`, :issue:`9155`) +- :class:`Timedelta` now supported in :func:`DataFrame.to_excel` for all Excel file types (:issue:`19242`, :issue:`9155`, :issue:`19900`) - Bug in :meth:`pandas.io.stata.StataReader.value_labels` raising an ``AttributeError`` when called on very old files. Now returns an empty dict (:issue:`19417`) Plotting diff --git a/pandas/io/excel.py b/pandas/io/excel.py index 0d3d4286f5a3c..55124c9956817 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -775,35 +775,6 @@ def _pop_header_name(row, index_col): return none_fill(row[i]), row[:i] + [''] + row[i + 1:] -def _conv_value(val): - """ Convert numpy types to Python types for the Excel writers. - - Parameters - ---------- - val : object - Value to be written into cells - - Returns - ------- - If val is a numpy int, float, or bool, then the equivalent Python - types are returned. :obj:`datetime`, :obj:`date`, and :obj:`timedelta` - are passed and formatting must be handled in the writer. :obj:`str` - representation is returned for all other types. - """ - if is_integer(val): - val = int(val) - elif is_float(val): - val = float(val) - elif is_bool(val): - val = bool(val) - elif isinstance(val, (datetime, date, timedelta)): - pass - else: - val = compat.to_str(val) - - return val - - @add_metaclass(abc.ABCMeta) class ExcelWriter(object): """ @@ -949,6 +920,39 @@ def _get_sheet_name(self, sheet_name): 'cur_sheet property') return sheet_name + def _value_with_fmt(self, val): + """Convert numpy types to Python types for the Excel writers. + + Parameters + ---------- + val : object + Value to be written into cells + + Returns + ------- + Tuple with the first element being the converted value and the second + being an optional format + """ + fmt = None + + if is_integer(val): + val = int(val) + elif is_float(val): + val = float(val) + elif is_bool(val): + val = bool(val) + elif isinstance(val, datetime): + fmt = self.datetime_format + elif isinstance(val, date): + fmt = self.date_format + elif isinstance(val, timedelta): + val = val.total_seconds() / float(86400) + fmt = '0' + else: + val = compat.to_str(val) + + return val, fmt + @classmethod def check_extension(cls, ext): """checks that path's extension against the Writer's supported @@ -1378,7 +1382,9 @@ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0, row=startrow + cell.row + 1, column=startcol + cell.col + 1 ) - xcell.value = _conv_value(cell.val) + xcell.value, fmt = self._value_with_fmt(cell.val) + if fmt: + xcell.number_format = fmt style_kwargs = {} if cell.style: @@ -1465,25 +1471,16 @@ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0, style_dict = {} for cell in cells: - val = _conv_value(cell.val) - - num_format_str = None - if isinstance(cell.val, datetime): - num_format_str = self.datetime_format - elif isinstance(cell.val, date): - num_format_str = self.date_format - elif isinstance(cell.val, timedelta): - delta = cell.val - val = delta.total_seconds() / float(86400) + val, fmt = self._value_with_fmt(cell.val) stylekey = json.dumps(cell.style) - if num_format_str: - stylekey += num_format_str + if fmt: + stylekey += fmt if stylekey in style_dict: style = style_dict[stylekey] else: - style = self._convert_to_style(cell.style, num_format_str) + style = self._convert_to_style(cell.style, fmt) style_dict[stylekey] = style if cell.mergestart is not None and cell.mergeend is not None: @@ -1741,23 +1738,17 @@ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0, wks.freeze_panes(*(freeze_panes)) for cell in cells: - val = _conv_value(cell.val) - - num_format_str = None - if isinstance(cell.val, datetime): - num_format_str = self.datetime_format - elif isinstance(cell.val, date): - num_format_str = self.date_format + val, fmt = self._value_with_fmt(cell.val) stylekey = json.dumps(cell.style) - if num_format_str: - stylekey += num_format_str + if fmt: + stylekey += fmt if stylekey in style_dict: style = style_dict[stylekey] else: style = self.book.add_format( - _XlsxStyler.convert(cell.style, num_format_str)) + _XlsxStyler.convert(cell.style, fmt)) style_dict[stylekey] = style if cell.mergestart is not None and cell.mergeend is not None: diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index fdf9954285db8..15d3062394d6e 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -1373,11 +1373,6 @@ def test_to_excel_interval_labels(self, merge_cells, engine, ext): def test_to_excel_timedelta(self, merge_cells, engine, ext): # GH 19242, GH9155 - test writing timedelta to xls - if engine == 'openpyxl': - pytest.xfail('Timedelta roundtrip broken with openpyxl') - if engine == 'xlsxwriter' and (sys.version_info[0] == 2 and - sys.platform.startswith('linux')): - pytest.xfail('Not working on linux with Py2 and xlsxwriter') frame = DataFrame(np.random.randint(-10, 10, size=(20, 1)), columns=['A'], dtype=np.int64
- [X] closes #19900 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry I've basically copied the implementation that was done for the `XlwtWriter` class in #19244 over to the other engine subclasses for an easy fix. This might also fix #19911
https://api.github.com/repos/pandas-dev/pandas/pulls/19921
2018-02-27T01:30:24Z
2018-02-28T00:16:49Z
2018-02-28T00:16:49Z
2018-05-14T21:11:43Z
Cythonized GroupBy pct_change
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 233816600ec0f..31007adc9ab6a 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -794,6 +794,7 @@ Performance Improvements - Improved performance of variable ``.rolling()`` on ``.min()`` and ``.max()`` (:issue:`19521`) - Improved performance of :func:`pandas.core.groupby.GroupBy.ffill` and :func:`pandas.core.groupby.GroupBy.bfill` (:issue:`11296`) - Improved performance of :func:`pandas.core.groupby.GroupBy.any` and :func:`pandas.core.groupby.GroupBy.all` (:issue:`15435`) +- Improved performance of :func:`pandas.core.groupby.GroupBy.pct_change` (:issue:`19165`) .. _whatsnew_0230.docs: diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 6b10d2ca3b5b2..285c5786b532b 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -2044,6 +2044,23 @@ def shift(self, periods=1, freq=None, axis=0): result_is_index=True, periods=periods) + @Substitution(name='groupby') + @Appender(_doc_template) + def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None, + axis=0): + """Calcuate pct_change of each value to previous entry in group""" + if freq is not None or axis != 0: + return self.apply(lambda x: x.pct_change(periods=periods, + fill_method=fill_method, + limit=limit, freq=freq, + axis=axis)) + + filled = getattr(self, fill_method)(limit=limit).drop( + self.grouper.names, axis=1) + shifted = filled.shift(periods=periods, freq=freq) + + return (filled / shifted) - 1 + @Substitution(name='groupby') @Appender(_doc_template) def head(self, n=5): @@ -3884,6 +3901,13 @@ def _apply_to_column_groupbys(self, func): """ return a pass thru """ return func(self) + def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None): + """Calculate percent change of each value to previous entry in group""" + filled = getattr(self, fill_method)(limit=limit) + shifted = filled.shift(periods=periods, freq=freq) + + return (filled / shifted) - 1 + class NDFrameGroupBy(GroupBy): diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 0561b3a1d8592..be0c32cefa6ff 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -2062,61 +2062,6 @@ def test_rank_object_raises(self, ties_method, ascending, na_option, ascending=ascending, na_option=na_option, pct=pct) - @pytest.mark.parametrize("mix_groupings", [True, False]) - @pytest.mark.parametrize("as_series", [True, False]) - @pytest.mark.parametrize("val1,val2", [ - ('foo', 'bar'), (1, 2), (1., 2.)]) - @pytest.mark.parametrize("fill_method,limit,exp_vals", [ - ("ffill", None, - [np.nan, np.nan, 'val1', 'val1', 'val1', 'val2', 'val2', 'val2']), - ("ffill", 1, - [np.nan, np.nan, 'val1', 'val1', np.nan, 'val2', 'val2', np.nan]), - ("bfill", None, - ['val1', 'val1', 'val1', 'val2', 'val2', 'val2', np.nan, np.nan]), - ("bfill", 1, - [np.nan, 'val1', 'val1', np.nan, 'val2', 'val2', np.nan, np.nan]) - ]) - def test_group_fill_methods(self, mix_groupings, as_series, val1, val2, - fill_method, limit, exp_vals): - vals = [np.nan, np.nan, val1, np.nan, np.nan, val2, np.nan, np.nan] - _exp_vals = list(exp_vals) - # Overwrite placeholder values - for index, exp_val in enumerate(_exp_vals): - if exp_val == 'val1': - _exp_vals[index] = val1 - elif exp_val == 'val2': - _exp_vals[index] = val2 - - # Need to modify values and expectations depending on the - # Series / DataFrame that we ultimately want to generate - if mix_groupings: # ['a', 'b', 'a, 'b', ...] - keys = ['a', 'b'] * len(vals) - - def interweave(list_obj): - temp = list() - for x in list_obj: - temp.extend([x, x]) - - return temp - - _exp_vals = interweave(_exp_vals) - vals = interweave(vals) - else: # ['a', 'a', 'a', ... 'b', 'b', 'b'] - keys = ['a'] * len(vals) + ['b'] * len(vals) - _exp_vals = _exp_vals * 2 - vals = vals * 2 - - df = DataFrame({'key': keys, 'val': vals}) - if as_series: - result = getattr( - df.groupby('key')['val'], fill_method)(limit=limit) - exp = Series(_exp_vals, name='val') - assert_series_equal(result, exp) - else: - result = getattr(df.groupby('key'), fill_method)(limit=limit) - exp = DataFrame({'key': keys, 'val': _exp_vals}) - assert_frame_equal(result, exp) - @pytest.mark.parametrize("agg_func", ['any', 'all']) @pytest.mark.parametrize("skipna", [True, False]) @pytest.mark.parametrize("vals", [ diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index b418bb0c5fea6..bce38b8cf9eed 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -636,3 +636,90 @@ def test_transform_numeric_ret(self, cols, exp, comp_func, agg_func): exp = exp.astype('float') comp_func(result, exp) + + @pytest.mark.parametrize("mix_groupings", [True, False]) + @pytest.mark.parametrize("as_series", [True, False]) + @pytest.mark.parametrize("val1,val2", [ + ('foo', 'bar'), (1, 2), (1., 2.)]) + @pytest.mark.parametrize("fill_method,limit,exp_vals", [ + ("ffill", None, + [np.nan, np.nan, 'val1', 'val1', 'val1', 'val2', 'val2', 'val2']), + ("ffill", 1, + [np.nan, np.nan, 'val1', 'val1', np.nan, 'val2', 'val2', np.nan]), + ("bfill", None, + ['val1', 'val1', 'val1', 'val2', 'val2', 'val2', np.nan, np.nan]), + ("bfill", 1, + [np.nan, 'val1', 'val1', np.nan, 'val2', 'val2', np.nan, np.nan]) + ]) + def test_group_fill_methods(self, mix_groupings, as_series, val1, val2, + fill_method, limit, exp_vals): + vals = [np.nan, np.nan, val1, np.nan, np.nan, val2, np.nan, np.nan] + _exp_vals = list(exp_vals) + # Overwrite placeholder values + for index, exp_val in enumerate(_exp_vals): + if exp_val == 'val1': + _exp_vals[index] = val1 + elif exp_val == 'val2': + _exp_vals[index] = val2 + + # Need to modify values and expectations depending on the + # Series / DataFrame that we ultimately want to generate + if mix_groupings: # ['a', 'b', 'a, 'b', ...] + keys = ['a', 'b'] * len(vals) + + def interweave(list_obj): + temp = list() + for x in list_obj: + temp.extend([x, x]) + + return temp + + _exp_vals = interweave(_exp_vals) + vals = interweave(vals) + else: # ['a', 'a', 'a', ... 'b', 'b', 'b'] + keys = ['a'] * len(vals) + ['b'] * len(vals) + _exp_vals = _exp_vals * 2 + vals = vals * 2 + + df = DataFrame({'key': keys, 'val': vals}) + if as_series: + result = getattr( + df.groupby('key')['val'], fill_method)(limit=limit) + exp = Series(_exp_vals, name='val') + assert_series_equal(result, exp) + else: + result = getattr(df.groupby('key'), fill_method)(limit=limit) + exp = DataFrame({'key': keys, 'val': _exp_vals}) + assert_frame_equal(result, exp) + + @pytest.mark.parametrize("test_series", [True, False]) + @pytest.mark.parametrize("periods,fill_method,limit", [ + (1, 'ffill', None), (1, 'ffill', 1), + (1, 'bfill', None), (1, 'bfill', 1), + (-1, 'ffill', None), (-1, 'ffill', 1), + (-1, 'bfill', None), (-1, 'bfill', 1)]) + def test_pct_change(self, test_series, periods, fill_method, limit): + vals = [np.nan, np.nan, 1, 2, 4, 10, np.nan, np.nan] + exp_vals = Series(vals).pct_change(periods=periods, + fill_method=fill_method, + limit=limit).tolist() + + df = DataFrame({'key': ['a'] * len(vals) + ['b'] * len(vals), + 'vals': vals * 2}) + grp = df.groupby('key') + + def get_result(grp_obj): + return grp_obj.pct_change(periods=periods, + fill_method=fill_method, + limit=limit) + + if test_series: + exp = pd.Series(exp_vals * 2) + exp.name = 'vals' + grp = grp['vals'] + result = get_result(grp) + tm.assert_series_equal(result, exp) + else: + exp = DataFrame({'vals': exp_vals * 2}) + result = get_result(grp) + tm.assert_frame_equal(result, exp)
- [ ] progress towards #19165 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry This seemed like a logical follow up to #19673. ASV benchmarks below: ```bash before after ratio [1e4c50a5] [c8285b5c] + 170±7μs 239±20μs 1.41 groupby.GroupByMethods.time_method('int', 'min') + 702±20μs 968±50μs 1.38 groupby.GroupByMethods.time_method('int', 'cumprod') + 339±2μs 391±6μs 1.15 groupby.GroupByMethods.time_method('float', 'prod') + 90.2±0.3μs 104±3μs 1.15 groupby.GroupByMethods.time_method('float', 'count') - 617±0.09ms 917±40μs 0.00 groupby.GroupByMethods.time_method('int', 'pct_change') - 1.07s 1.08±0.1ms 0.00 groupby.GroupByMethods.time_method('float', 'pct_change') ```
https://api.github.com/repos/pandas-dev/pandas/pulls/19919
2018-02-26T22:41:17Z
2018-03-10T02:06:44Z
2018-03-10T02:06:44Z
2018-03-21T23:45:07Z
transition period_helper to use pandas_datetimestruct
diff --git a/pandas/_libs/src/period_helper.c b/pandas/_libs/src/period_helper.c index 19a7282f38049..cb6f0a220fafe 100644 --- a/pandas/_libs/src/period_helper.c +++ b/pandas/_libs/src/period_helper.c @@ -58,18 +58,6 @@ npy_int64 unix_date_from_ymd(int year, int month, int day) { return unix_date; } -/* Sets the date part of the date_info struct - Assumes GREGORIAN_CALENDAR */ -static int dInfoCalc_SetFromAbsDate(register struct date_info *dinfo, - npy_int64 unix_date) { - pandas_datetimestruct dts; - - pandas_datetime_to_datetimestruct(unix_date, PANDAS_FR_D, &dts); - dinfo->year = dts.year; - dinfo->month = dts.month; - dinfo->day = dts.day; - return 0; -} /////////////////////////////////////////////// @@ -139,9 +127,9 @@ static npy_int64 DtoB_weekday(npy_int64 unix_date) { return floordiv(unix_date + 4, 7) * 5 + mod_compat(unix_date + 4, 7) - 4; } -static npy_int64 DtoB(struct date_info *dinfo, +static npy_int64 DtoB(pandas_datetimestruct *dts, int roll_back, npy_int64 unix_date) { - int day_of_week = dayofweek(dinfo->year, dinfo->month, dinfo->day); + int day_of_week = dayofweek(dts->year, dts->month, dts->day); if (roll_back == 1) { if (day_of_week > 4) { @@ -161,32 +149,32 @@ static npy_int64 DtoB(struct date_info *dinfo, //************ FROM DAILY *************** static npy_int64 asfreq_DTtoA(npy_int64 ordinal, asfreq_info *af_info) { - struct date_info dinfo; + pandas_datetimestruct dts; ordinal = downsample_daytime(ordinal, af_info); - dInfoCalc_SetFromAbsDate(&dinfo, ordinal); - if (dinfo.month > af_info->to_a_year_end) { - return (npy_int64)(dinfo.year + 1 - 1970); + pandas_datetime_to_datetimestruct(ordinal, PANDAS_FR_D, &dts); + if (dts.month > af_info->to_end) { + return (npy_int64)(dts.year + 1 - 1970); } else { - return (npy_int64)(dinfo.year - 1970); + return (npy_int64)(dts.year - 1970); } } static int DtoQ_yq(npy_int64 ordinal, asfreq_info *af_info, int *year) { - struct date_info dinfo; + pandas_datetimestruct dts; int quarter; - dInfoCalc_SetFromAbsDate(&dinfo, ordinal); - if (af_info->to_q_year_end != 12) { - dinfo.month -= af_info->to_q_year_end; - if (dinfo.month <= 0) { - dinfo.month += 12; + pandas_datetime_to_datetimestruct(ordinal, PANDAS_FR_D, &dts); + if (af_info->to_end != 12) { + dts.month -= af_info->to_end; + if (dts.month <= 0) { + dts.month += 12; } else { - dinfo.year += 1; + dts.year += 1; } } - *year = dinfo.year; - quarter = monthToQuarter(dinfo.month); + *year = dts.year; + quarter = monthToQuarter(dts.month); return quarter; } @@ -200,29 +188,28 @@ static npy_int64 asfreq_DTtoQ(npy_int64 ordinal, asfreq_info *af_info) { } static npy_int64 asfreq_DTtoM(npy_int64 ordinal, asfreq_info *af_info) { - struct date_info dinfo; + pandas_datetimestruct dts; ordinal = downsample_daytime(ordinal, af_info); - dInfoCalc_SetFromAbsDate(&dinfo, ordinal); - return (npy_int64)((dinfo.year - 1970) * 12 + dinfo.month - 1); + pandas_datetime_to_datetimestruct(ordinal, PANDAS_FR_D, &dts); + return (npy_int64)((dts.year - 1970) * 12 + dts.month - 1); } static npy_int64 asfreq_DTtoW(npy_int64 ordinal, asfreq_info *af_info) { ordinal = downsample_daytime(ordinal, af_info); - return floordiv(ordinal + 3 - af_info->to_week_end, 7) + 1; + return floordiv(ordinal + 3 - af_info->to_end, 7) + 1; } static npy_int64 asfreq_DTtoB(npy_int64 ordinal, asfreq_info *af_info) { - struct date_info dinfo; int roll_back; - - ordinal = downsample_daytime(ordinal, af_info); - dInfoCalc_SetFromAbsDate(&dinfo, ordinal); + pandas_datetimestruct dts; + npy_int64 unix_date = downsample_daytime(ordinal, af_info); + pandas_datetime_to_datetimestruct(unix_date, PANDAS_FR_D, &dts); // This usage defines roll_back the opposite way from the others roll_back = 1 - af_info->is_end; - return DtoB(&dinfo, roll_back, ordinal); + return DtoB(&dts, roll_back, unix_date); } //************ FROM BUSINESS *************** @@ -252,7 +239,7 @@ static npy_int64 asfreq_BtoW(npy_int64 ordinal, asfreq_info *af_info) { //************ FROM WEEKLY *************** static npy_int64 asfreq_WtoDT(npy_int64 ordinal, asfreq_info *af_info) { - ordinal = ordinal * 7 + af_info->from_week_end - 4 + + ordinal = ordinal * 7 + af_info->from_end - 4 + (7 - 1) * (af_info->is_end - 1); return upsample_daytime(ordinal, af_info); } @@ -274,12 +261,13 @@ static npy_int64 asfreq_WtoW(npy_int64 ordinal, asfreq_info *af_info) { } static npy_int64 asfreq_WtoB(npy_int64 ordinal, asfreq_info *af_info) { - struct date_info dinfo; + int roll_back; + pandas_datetimestruct dts; npy_int64 unix_date = asfreq_WtoDT(ordinal, af_info); - int roll_back = af_info->is_end; - dInfoCalc_SetFromAbsDate(&dinfo, unix_date); - return DtoB(&dinfo, roll_back, unix_date); + pandas_datetime_to_datetimestruct(unix_date, PANDAS_FR_D, &dts); + roll_back = af_info->is_end; + return DtoB(&dts, roll_back, unix_date); } //************ FROM MONTHLY *************** @@ -313,12 +301,13 @@ static npy_int64 asfreq_MtoW(npy_int64 ordinal, asfreq_info *af_info) { } static npy_int64 asfreq_MtoB(npy_int64 ordinal, asfreq_info *af_info) { - struct date_info dinfo; + int roll_back; + pandas_datetimestruct dts; npy_int64 unix_date = asfreq_MtoDT(ordinal, af_info); - int roll_back = af_info->is_end; - dInfoCalc_SetFromAbsDate(&dinfo, unix_date); - return DtoB(&dinfo, roll_back, unix_date); + pandas_datetime_to_datetimestruct(unix_date, PANDAS_FR_D, &dts); + roll_back = af_info->is_end; + return DtoB(&dts, roll_back, unix_date); } //************ FROM QUARTERLY *************** @@ -328,8 +317,8 @@ static void QtoD_ym(npy_int64 ordinal, int *year, int *month, *year = floordiv(ordinal, 4) + 1970; *month = mod_compat(ordinal, 4) * 3 + 1; - if (af_info->from_q_year_end != 12) { - *month += af_info->from_q_year_end; + if (af_info->from_end != 12) { + *month += af_info->from_end; if (*month > 12) { *month -= 12; } else { @@ -367,23 +356,24 @@ static npy_int64 asfreq_QtoW(npy_int64 ordinal, asfreq_info *af_info) { } static npy_int64 asfreq_QtoB(npy_int64 ordinal, asfreq_info *af_info) { - struct date_info dinfo; + int roll_back; + pandas_datetimestruct dts; npy_int64 unix_date = asfreq_QtoDT(ordinal, af_info); - int roll_back = af_info->is_end; - dInfoCalc_SetFromAbsDate(&dinfo, unix_date); - return DtoB(&dinfo, roll_back, unix_date); + pandas_datetime_to_datetimestruct(unix_date, PANDAS_FR_D, &dts); + roll_back = af_info->is_end; + return DtoB(&dts, roll_back, unix_date); } //************ FROM ANNUAL *************** -static void AtoD_ym(npy_int64 ordinal, int *year, int *month, +static void AtoD_ym(npy_int64 ordinal, npy_int64 *year, int *month, asfreq_info *af_info) { *year = ordinal + 1970; *month = 1; - if (af_info->from_a_year_end != 12) { - *month += af_info->from_a_year_end; + if (af_info->from_end != 12) { + *month += af_info->from_end; if (*month > 12) { // This case is never reached, but is kept for symmetry // with QtoD_ym @@ -395,8 +385,8 @@ static void AtoD_ym(npy_int64 ordinal, int *year, int *month, } static npy_int64 asfreq_AtoDT(npy_int64 ordinal, asfreq_info *af_info) { - npy_int64 unix_date; - int year, month; + npy_int64 unix_date, year; + int month; ordinal += af_info->is_end; AtoD_ym(ordinal, &year, &month, af_info); @@ -423,12 +413,13 @@ static npy_int64 asfreq_AtoW(npy_int64 ordinal, asfreq_info *af_info) { } static npy_int64 asfreq_AtoB(npy_int64 ordinal, asfreq_info *af_info) { - struct date_info dinfo; + int roll_back; + pandas_datetimestruct dts; npy_int64 unix_date = asfreq_AtoDT(ordinal, af_info); - int roll_back = af_info->is_end; - dInfoCalc_SetFromAbsDate(&dinfo, unix_date); - return DtoB(&dinfo, roll_back, unix_date); + pandas_datetime_to_datetimestruct(unix_date, PANDAS_FR_D, &dts); + roll_back = af_info->is_end; + return DtoB(&dts, roll_back, unix_date); } static npy_int64 nofunc(npy_int64 ordinal, asfreq_info *af_info) { diff --git a/pandas/_libs/src/period_helper.h b/pandas/_libs/src/period_helper.h index c6313924adddd..8f538b261db9e 100644 --- a/pandas/_libs/src/period_helper.h +++ b/pandas/_libs/src/period_helper.h @@ -81,27 +81,23 @@ typedef struct asfreq_info { // char relation == 'S' (for START) --> is_end = 0 // char relation == 'E' (for END) --> is_end = 1 - int from_week_end; // day the week ends on in the "from" frequency - int to_week_end; // day the week ends on in the "to" frequency - - int from_a_year_end; // month the year ends on in the "from" frequency - int to_a_year_end; // month the year ends on in the "to" frequency - - int from_q_year_end; // month the year ends on in the "from" frequency - int to_q_year_end; // month the year ends on in the "to" frequency + int from_end; + int to_end; + // weekly: + // from_end --> day the week ends on in the "from" frequency + // to_end --> day the week ends on in the "to" frequency + // + // annual: + // from_end --> month the year ends on in the "from" frequency + // to_end --> month the year ends on in the "to" frequency + // + // quarterly: + // from_end --> month the year ends on in the "from" frequency + // to_end --> month the year ends on in the "to" frequency npy_int64 intraday_conversion_factor; } asfreq_info; -typedef struct date_info { - double second; - int minute; - int hour; - int day; - int month; - int year; -} date_info; - typedef npy_int64 (*freq_conv_func)(npy_int64, asfreq_info *af_info); /* diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 9cf7e39791f2b..89f38724cde1a 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -79,14 +79,8 @@ cdef extern from "period_helper.h": int64_t intraday_conversion_factor int is_end - int from_week_end - int to_week_end - - int from_a_year_end - int to_a_year_end - - int from_q_year_end - int to_q_year_end + int to_end + int from_end ctypedef int64_t (*freq_conv_func)(int64_t, asfreq_info*) nogil @@ -147,23 +141,13 @@ cdef inline int get_freq_group_index(int freq) nogil: # specifically _dont_ use cdvision or else ordinals near -1 are assigned to # incorrect dates GH#19643 @cython.cdivision(False) -cdef int64_t get_period_ordinal(int year, int month, int day, - int hour, int minute, int second, - int microseconds, int picoseconds, - int freq) nogil: +cdef int64_t get_period_ordinal(pandas_datetimestruct *dts, int freq) nogil: """ Generate an ordinal in period space Parameters ---------- - year : int - month : int - day : int - hour : int - minute : int - second : int - microseconds : int - picoseconds : int + dts: pandas_datetimestruct* freq : int Returns @@ -182,52 +166,54 @@ cdef int64_t get_period_ordinal(int year, int month, int day, fmonth = freq - FR_ANN if fmonth == 0: fmonth = 12 - if month <= fmonth: - return year - 1970 + + mdiff = dts.month - fmonth + if mdiff <= 0: + return dts.year - 1970 else: - return year - 1970 + 1 + return dts.year - 1970 + 1 elif freq_group == FR_QTR: fmonth = freq - FR_QTR if fmonth == 0: fmonth = 12 - mdiff = month - fmonth + mdiff = dts.month - fmonth # TODO: Aren't the next two conditions equivalent to # unconditional incrementing? if mdiff < 0: mdiff += 12 - if month >= fmonth: + if dts.month >= fmonth: mdiff += 12 - return (year - 1970) * 4 + (mdiff - 1) // 3 + return (dts.year - 1970) * 4 + (mdiff - 1) // 3 elif freq == FR_MTH: - return (year - 1970) * 12 + month - 1 + return (dts.year - 1970) * 12 + dts.month - 1 - unix_date = unix_date_from_ymd(year, month, day) + unix_date = pandas_datetimestruct_to_datetime(PANDAS_FR_D, dts) if freq >= FR_SEC: - seconds = unix_date * 86400 + hour * 3600 + minute * 60 + second + seconds = unix_date * 86400 + dts.hour * 3600 + dts.min * 60 + dts.sec if freq == FR_MS: - return seconds * 1000 + microseconds // 1000 + return seconds * 1000 + dts.us // 1000 elif freq == FR_US: - return seconds * 1000000 + microseconds + return seconds * 1000000 + dts.us elif freq == FR_NS: return (seconds * 1000000000 + - microseconds * 1000 + picoseconds // 1000) + dts.us * 1000 + dts.ps // 1000) else: return seconds elif freq == FR_MIN: - return unix_date * 1440 + hour * 60 + minute + return unix_date * 1440 + dts.hour * 60 + dts.min elif freq == FR_HR: - return unix_date * 24 + hour + return unix_date * 24 + dts.hour elif freq == FR_DAY: return unix_date @@ -374,34 +360,6 @@ cdef double get_abs_time(int freq, int64_t unix_date, int64_t ordinal) nogil: return result -cdef int64_t unix_date_from_ymd(int year, int month, int day) nogil: - """ - Find the unix_date (days elapsed since datetime(1970, 1, 1) - for the given year/month/day. - - Parameters - ---------- - year : int - month : int - day : int - - Returns - ------- - unix_date : int - days elapsed since datetime(1970, 1, 1) - """ - cdef: - pandas_datetimestruct dts - int64_t unix_date - - memset(&dts, 0, sizeof(pandas_datetimestruct)) - dts.year = year - dts.month = month - dts.day = day - unix_date = pandas_datetimestruct_to_datetime(PANDAS_FR_D, &dts) - return unix_date - - cdef int get_yq(int64_t ordinal, int freq, int *quarter, int *year): """ Find the year and quarter of a Period with the given ordinal and frequency @@ -434,6 +392,7 @@ cdef int get_yq(int64_t ordinal, int freq, int *quarter, int *year): else: qtr_freq = FR_QTR + assert (qtr_freq % 1000) <= 12 get_asfreq_info(FR_DAY, qtr_freq, True, &af_info) quarter[0] = DtoQ_yq(unix_date, &af_info, year) @@ -447,8 +406,8 @@ cdef int DtoQ_yq(int64_t unix_date, asfreq_info *af_info, int *year): date_info_from_days_and_time(&dts, unix_date, 0) - if af_info.to_q_year_end != 12: - dts.month -= af_info.to_q_year_end + if af_info.to_end != 12: + dts.month -= af_info.to_end if dts.month <= 0: dts.month += 12 else: @@ -490,9 +449,7 @@ def dt64arr_to_periodarr(ndarray[int64_t] dtarr, int freq, tz=None): out[i] = NPY_NAT continue dt64_to_dtstruct(dtarr[i], &dts) - out[i] = get_period_ordinal(dts.year, dts.month, dts.day, - dts.hour, dts.min, dts.sec, - dts.us, dts.ps, freq) + out[i] = get_period_ordinal(&dts, freq) else: out = localize_dt64arr_to_period(dtarr, freq, tz) return out @@ -570,18 +527,18 @@ cdef void get_asfreq_info(int from_freq, int to_freq, get_freq_group_index(max_value(to_group, FR_DAY))) if from_group == FR_WK: - af_info.from_week_end = calc_week_end(from_freq, from_group) + af_info.from_end = calc_week_end(from_freq, from_group) elif from_group == FR_ANN: - af_info.from_a_year_end = calc_a_year_end(from_freq, from_group) + af_info.from_end = calc_a_year_end(from_freq, from_group) elif from_group == FR_QTR: - af_info.from_q_year_end = calc_a_year_end(from_freq, from_group) + af_info.from_end = calc_a_year_end(from_freq, from_group) if to_group == FR_WK: - af_info.to_week_end = calc_week_end(to_freq, to_group) + af_info.to_end = calc_week_end(to_freq, to_group) elif to_group == FR_ANN: - af_info.to_a_year_end = calc_a_year_end(to_freq, to_group) + af_info.to_end = calc_a_year_end(to_freq, to_group) elif to_group == FR_QTR: - af_info.to_q_year_end = calc_a_year_end(to_freq, to_group) + af_info.to_end = calc_a_year_end(to_freq, to_group) @cython.cdivision @@ -635,15 +592,43 @@ def period_asfreq_arr(ndarray[int64_t] arr, int freq1, int freq2, bint end): return result -def period_ordinal(int y, int m, int d, int h, int min, - int s, int us, int ps, int freq): - return get_period_ordinal(y, m, d, h, min, s, us, ps, freq) +cpdef int64_t period_ordinal(int y, int m, int d, int h, int min, + int s, int us, int ps, int freq): + """ + Find the ordinal representation of the given datetime components at the + frequency `freq`. + + Parameters + ---------- + y : int + m : int + d : int + h : int + min : int + s : int + us : int + ps : int + + Returns + ------- + ordinal : int64_t + """ + cdef: + pandas_datetimestruct dts + dts.year = y + dts.month = m + dts.day = d + dts.hour = h + dts.min = min + dts.sec = s + dts.us = us + dts.ps = ps + return get_period_ordinal(&dts, freq) cpdef int64_t period_ordinal_to_dt64(int64_t ordinal, int freq) nogil: cdef: pandas_datetimestruct dts - float subsecond_fraction if ordinal == NPY_NAT: return NPY_NAT @@ -770,19 +755,15 @@ cdef int pyear(int64_t ordinal, int freq): @cython.cdivision cdef int pqyear(int64_t ordinal, int freq): cdef: - int year, quarter, qtr_freq - qtr_freq = get_yq(ordinal, freq, &quarter, &year) - if (qtr_freq % 1000) > 12: - year -= 1 + int year, quarter + get_yq(ordinal, freq, &quarter, &year) return year cdef int pquarter(int64_t ordinal, int freq): cdef: - int year, quarter, qtr_freq - qtr_freq = get_yq(ordinal, freq, &quarter, &year) - if (qtr_freq % 1000) > 12: - year -= 1 + int year, quarter + get_yq(ordinal, freq, &quarter, &year) return quarter @@ -968,9 +949,7 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps, result[i] = NPY_NAT continue dt64_to_dtstruct(stamps[i], &dts) - result[i] = get_period_ordinal(dts.year, dts.month, dts.day, - dts.hour, dts.min, dts.sec, - dts.us, dts.ps, freq) + result[i] = get_period_ordinal(&dts, freq) elif is_tzlocal(tz): for i in range(n): @@ -979,9 +958,7 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps, continue local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) dt64_to_dtstruct(local_val, &dts) - result[i] = get_period_ordinal(dts.year, dts.month, dts.day, - dts.hour, dts.min, dts.sec, - dts.us, dts.ps, freq) + result[i] = get_period_ordinal(&dts, freq) else: # Adjust datetime64 timestamp, recompute datetimestruct trans, deltas, typ = get_dst_info(tz) @@ -998,18 +975,14 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps, result[i] = NPY_NAT continue dt64_to_dtstruct(stamps[i] + deltas[0], &dts) - result[i] = get_period_ordinal(dts.year, dts.month, dts.day, - dts.hour, dts.min, dts.sec, - dts.us, dts.ps, freq) + result[i] = get_period_ordinal(&dts, freq) else: for i in range(n): if stamps[i] == NPY_NAT: result[i] = NPY_NAT continue dt64_to_dtstruct(stamps[i] + deltas[pos[i]], &dts) - result[i] = get_period_ordinal(dts.year, dts.month, dts.day, - dts.hour, dts.min, dts.sec, - dts.us, dts.ps, freq) + result[i] = get_period_ordinal(&dts, freq) return result @@ -1595,9 +1568,9 @@ class Period(_Period): if ordinal is None: base, mult = get_freq_code(freq) - ordinal = get_period_ordinal(dt.year, dt.month, dt.day, - dt.hour, dt.minute, dt.second, - dt.microsecond, 0, base) + ordinal = period_ordinal(dt.year, dt.month, dt.day, + dt.hour, dt.minute, dt.second, + dt.microsecond, 0, base) return cls._from_ordinal(ordinal, freq) @@ -1608,8 +1581,8 @@ cdef int64_t _ordinal_from_fields(year, month, quarter, day, if quarter is not None: year, month = _quarter_to_myear(year, quarter, freq) - return get_period_ordinal(year, month, day, hour, - minute, second, 0, 0, base) + return period_ordinal(year, month, day, hour, + minute, second, 0, 0, base) def _quarter_to_myear(year, quarter, freq):
In the last round we transitioned period.pyx to use pandas_datetimestruct instead of date_info. This does the same thing for period_helper.
https://api.github.com/repos/pandas-dev/pandas/pulls/19918
2018-02-26T22:07:41Z
2018-03-04T20:00:40Z
2018-03-04T20:00:40Z
2018-06-22T03:30:59Z
DOC fix incorrect example in DataFrame.to_dict docstring. Close GH19868
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e4ef1b97882d9..c39664047a01b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -957,8 +957,8 @@ def to_dict(self, orient='dict', into=dict): {'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b']) >>> df col1 col2 - a 1 0.1 - b 2 0.2 + a 1 0.50 + b 2 0.75 >>> df.to_dict() {'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}
- [x] closes #19868 - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] What's new: Fix incorrect example
https://api.github.com/repos/pandas-dev/pandas/pulls/19915
2018-02-26T19:34:50Z
2018-02-27T01:24:58Z
2018-02-27T01:24:58Z
2018-02-27T01:48:43Z
BUG: Adding skipna as an option to groupby cumsum and cumprod
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index f2c96ba3f53a8..7a19f87051746 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -927,6 +927,7 @@ Groupby/Resample/Rolling - Bug in :func:`DataFrame.groupby` passing the `on=` kwarg, and subsequently using ``.apply()`` (:issue:`17813`) - Bug in :func:`DataFrame.resample().aggregate` not raising a ``KeyError`` when aggregating a non-existent column (:issue:`16766`, :issue:`19566`) - Fixed a performance regression for ``GroupBy.nth`` and ``GroupBy.last`` with some object columns (:issue:`19283`) +- Bug in :func:`DataFrameGroupBy.cumsum` and :func:`DataFrameGroupBy.cumprod` when ``skipna`` was passed (:issue:`19806`) Sparse ^^^^^^ diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index d3fcd84e5f38d..43afd1e0f5969 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -139,7 +139,8 @@ def group_median_float64(ndarray[float64_t, ndim=2] out, def group_cumprod_float64(float64_t[:, :] out, float64_t[:, :] values, int64_t[:] labels, - bint is_datetimelike): + bint is_datetimelike, + bint skipna=True): """ Only transforms on axis=0 """ @@ -163,6 +164,11 @@ def group_cumprod_float64(float64_t[:, :] out, if val == val: accum[lab, j] *= val out[i, j] = accum[lab, j] + else: + out[i, j] = NaN + if not skipna: + accum[lab, j] = NaN + break @cython.boundscheck(False) @@ -170,7 +176,8 @@ def group_cumprod_float64(float64_t[:, :] out, def group_cumsum(numeric[:, :] out, numeric[:, :] values, int64_t[:] labels, - is_datetimelike): + is_datetimelike, + bint skipna=True): """ Only transforms on axis=0 """ @@ -196,6 +203,11 @@ def group_cumsum(numeric[:, :] out, if val == val: accum[lab, j] += val out[i, j] = accum[lab, j] + else: + out[i, j] = NaN + if not skipna: + accum[lab, j] = NaN + break else: accum[lab, j] += val out[i, j] = accum[lab, j] diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index b8ca104c4b2c7..4a09d636ee320 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -1888,7 +1888,8 @@ def rank(self, method='average', ascending=True, na_option='keep', @Appender(_doc_template) def cumprod(self, axis=0, *args, **kwargs): """Cumulative product for each group""" - nv.validate_groupby_func('cumprod', args, kwargs, ['numeric_only']) + nv.validate_groupby_func('cumprod', args, kwargs, + ['numeric_only', 'skipna']) if axis != 0: return self.apply(lambda x: x.cumprod(axis=axis, **kwargs)) @@ -1898,7 +1899,8 @@ def cumprod(self, axis=0, *args, **kwargs): @Appender(_doc_template) def cumsum(self, axis=0, *args, **kwargs): """Cumulative sum for each group""" - nv.validate_groupby_func('cumsum', args, kwargs, ['numeric_only']) + nv.validate_groupby_func('cumsum', args, kwargs, + ['numeric_only', 'skipna']) if axis != 0: return self.apply(lambda x: x.cumsum(axis=axis, **kwargs)) diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index 1be7dfdcc64e6..b418bb0c5fea6 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -498,6 +498,31 @@ def test_cython_transform_series(self, op, args, targop): tm.assert_series_equal(expected, getattr( data.groupby(labels), op)(*args)) + @pytest.mark.parametrize("op", ['cumprod', 'cumsum']) + @pytest.mark.parametrize("skipna", [False, True]) + @pytest.mark.parametrize('input, exp', [ + # When everything is NaN + ({'key': ['b'] * 10, 'value': np.nan}, + pd.Series([np.nan] * 10, name='value')), + # When there is a single NaN + ({'key': ['b'] * 10 + ['a'] * 2, + 'value': [3] * 3 + [np.nan] + [3] * 8}, + {('cumprod', False): [3.0, 9.0, 27.0] + [np.nan] * 7 + [3.0, 9.0], + ('cumprod', True): [3.0, 9.0, 27.0, np.nan, 81., 243., 729., + 2187., 6561., 19683., 3.0, 9.0], + ('cumsum', False): [3.0, 6.0, 9.0] + [np.nan] * 7 + [3.0, 6.0], + ('cumsum', True): [3.0, 6.0, 9.0, np.nan, 12., 15., 18., + 21., 24., 27., 3.0, 6.0]})]) + def test_groupby_cum_skipna(self, op, skipna, input, exp): + df = pd.DataFrame(input) + result = df.groupby('key')['value'].transform(op, skipna=skipna) + if isinstance(exp, dict): + expected = exp[(op, skipna)] + else: + expected = exp + expected = pd.Series(expected, name='value') + tm.assert_series_equal(expected, result) + @pytest.mark.parametrize( "op, args, targop", [('cumprod', (), lambda x: x.cumprod()),
- [x] closes #19806 - [x] tests added in `test_groupby.py` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This handles #19806 by adding skipna as an option to both `cumsum` and `cumprod` after groupby. I'm assuming that default behavior is what is described in the docs, with skipna=True.
https://api.github.com/repos/pandas-dev/pandas/pulls/19914
2018-02-26T19:11:45Z
2018-03-01T23:13:58Z
2018-03-01T23:13:58Z
2018-03-01T23:14:01Z
API: Added ExtensionArray constructors
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index cec881394a021..37074b563efbd 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -18,6 +18,7 @@ class ExtensionArray(object): The interface includes the following abstract methods that must be implemented by subclasses: + * _constructor_from_sequence * __getitem__ * __len__ * dtype @@ -56,6 +57,25 @@ class ExtensionArray(object): # '_typ' is for pandas.core.dtypes.generic.ABCExtensionArray. # Don't override this. _typ = 'extension' + + # ------------------------------------------------------------------------ + # Constructors + # ------------------------------------------------------------------------ + @classmethod + def _constructor_from_sequence(cls, scalars): + """Construct a new ExtensionArray from a sequence of scalars. + + Parameters + ---------- + scalars : Sequence + Each element will be an instance of the scalar type for this + array, ``cls.dtype.type``. + Returns + ------- + ExtensionArray + """ + raise AbstractMethodError(cls) + # ------------------------------------------------------------------------ # Must be a Sequence # ------------------------------------------------------------------------ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c6eeabf0148d0..e23dc3b3e5b89 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -364,6 +364,10 @@ def __init__(self, values, categories=None, ordered=None, dtype=None, self._dtype = self._dtype.update_dtype(dtype) self._codes = coerce_indexer_dtype(codes, dtype.categories) + @classmethod + def _constructor_from_sequence(cls, scalars): + return cls(scalars) + @property def categories(self): """The categories of this categorical. diff --git a/pandas/tests/extension/base/constructors.py b/pandas/tests/extension/base/constructors.py index 2d5d747aec5a7..4ac04d71338fd 100644 --- a/pandas/tests/extension/base/constructors.py +++ b/pandas/tests/extension/base/constructors.py @@ -9,6 +9,11 @@ class BaseConstructorsTests(BaseExtensionTests): + def test_array_from_scalars(self, data): + scalars = [data[0], data[1], data[2]] + result = data._constructor_from_sequence(scalars) + assert isinstance(result, type(data)) + def test_series_constructor(self, data): result = pd.Series(data) assert result.dtype == data.dtype diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 8b2eaadeca99e..736556e4be20d 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -32,6 +32,10 @@ def __init__(self, values): self.values = values + @classmethod + def _constructor_from_sequence(cls, scalars): + return cls(scalars) + def __getitem__(self, item): if isinstance(item, numbers.Integral): return self.values[item] diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 90aac93c68f64..21addf9d1549f 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -33,11 +33,17 @@ def __init__(self, values): raise TypeError self.data = values + @classmethod + def _constructor_from_sequence(cls, scalars): + return cls(scalars) + def __getitem__(self, item): if isinstance(item, numbers.Integral): return self.data[item] elif isinstance(item, np.ndarray) and item.dtype == 'bool': - return type(self)([x for x, m in zip(self, item) if m]) + return self._constructor_from_sequence([ + x for x, m in zip(self, item) if m + ]) else: return type(self)(self.data[item]) @@ -77,7 +83,7 @@ def isna(self): def take(self, indexer, allow_fill=True, fill_value=None): output = [self.data[loc] if loc != -1 else self._na_value for loc in indexer] - return type(self)(output) + return self._constructor_from_sequence(output) def copy(self, deep=False): return type(self)(self.data[:])
Adds two new (private, but part of the interface) constructors to EA. Closes #19906
https://api.github.com/repos/pandas-dev/pandas/pulls/19913
2018-02-26T18:03:54Z
2018-03-02T21:20:29Z
2018-03-02T21:20:29Z
2018-05-02T13:10:20Z
Datetimelike add/sub catch cases more explicitly, tests
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 4c6effc65a4d3..e673bfe411cb4 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -37,7 +37,7 @@ is_period_dtype, is_timedelta64_dtype) from pandas.core.dtypes.generic import ( - ABCIndex, ABCSeries, ABCPeriodIndex, ABCIndexClass) + ABCIndex, ABCSeries, ABCDataFrame, ABCPeriodIndex, ABCIndexClass) from pandas.core.dtypes.missing import isna from pandas.core import common as com, algorithms, ops from pandas.core.algorithms import checked_add_with_arr @@ -48,6 +48,7 @@ from pandas.util._decorators import Appender, cache_readonly import pandas.core.dtypes.concat as _concat import pandas.tseries.frequencies as frequencies +from pandas.tseries.offsets import Tick, DateOffset import pandas.core.indexes.base as ibase _index_doc_kwargs = dict(ibase._index_doc_kwargs) @@ -666,6 +667,9 @@ def _sub_nat(self): def _sub_period(self, other): return NotImplemented + def _add_offset(self, offset): + raise com.AbstractMethodError(self) + def _addsub_offset_array(self, other, op): """ Add or subtract array-like of DateOffset objects @@ -705,14 +709,17 @@ def __add__(self, other): from pandas import DateOffset other = lib.item_from_zerodim(other) - if isinstance(other, ABCSeries): + if isinstance(other, (ABCSeries, ABCDataFrame)): return NotImplemented # scalar others elif other is NaT: result = self._add_nat() - elif isinstance(other, (DateOffset, timedelta, np.timedelta64)): + elif isinstance(other, (Tick, timedelta, np.timedelta64)): result = self._add_delta(other) + elif isinstance(other, DateOffset): + # specifically _not_ a Tick + result = self._add_offset(other) elif isinstance(other, (datetime, np.datetime64)): result = self._add_datelike(other) elif is_integer(other): @@ -733,6 +740,12 @@ def __add__(self, other): elif is_integer_dtype(other) and self.freq is None: # GH#19123 raise NullFrequencyError("Cannot shift with no freq") + elif is_float_dtype(other): + # Explicitly catch invalid dtypes + raise TypeError("cannot add {dtype}-dtype to {cls}" + .format(dtype=other.dtype, + cls=type(self).__name__)) + else: # pragma: no cover return NotImplemented @@ -753,17 +766,20 @@ def __radd__(self, other): cls.__radd__ = __radd__ def __sub__(self, other): - from pandas import Index, DateOffset + from pandas import Index other = lib.item_from_zerodim(other) - if isinstance(other, ABCSeries): + if isinstance(other, (ABCSeries, ABCDataFrame)): return NotImplemented # scalar others elif other is NaT: result = self._sub_nat() - elif isinstance(other, (DateOffset, timedelta, np.timedelta64)): + elif isinstance(other, (Tick, timedelta, np.timedelta64)): result = self._add_delta(-other) + elif isinstance(other, DateOffset): + # specifically _not_ a Tick + result = self._add_offset(-other) elif isinstance(other, (datetime, np.datetime64)): result = self._sub_datelike(other) elif is_integer(other): @@ -790,6 +806,12 @@ def __sub__(self, other): elif is_integer_dtype(other) and self.freq is None: # GH#19123 raise NullFrequencyError("Cannot shift with no freq") + + elif is_float_dtype(other): + # Explicitly catch invalid dtypes + raise TypeError("cannot subtract {dtype}-dtype from {cls}" + .format(dtype=other.dtype, + cls=type(self).__name__)) else: # pragma: no cover return NotImplemented diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index eb8133a1bbf97..f8eea7bf1316e 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -933,8 +933,6 @@ def _add_delta(self, delta): if not isinstance(delta, TimedeltaIndex): delta = TimedeltaIndex(delta) new_values = self._add_delta_tdi(delta) - elif isinstance(delta, DateOffset): - new_values = self._add_offset(delta).asi8 else: new_values = self.astype('O') + delta @@ -945,6 +943,7 @@ def _add_delta(self, delta): return result def _add_offset(self, offset): + assert not isinstance(offset, Tick) try: if self.tz is not None: values = self.tz_localize(None) @@ -953,12 +952,13 @@ def _add_offset(self, offset): result = offset.apply_index(values) if self.tz is not None: result = result.tz_localize(self.tz) - return result except NotImplementedError: warnings.warn("Non-vectorized DateOffset being applied to Series " "or DatetimeIndex", PerformanceWarning) - return self.astype('O') + offset + result = self.astype('O') + offset + + return DatetimeIndex(result, freq='infer') def _format_native_types(self, na_rep='NaT', date_format=None, **kwargs): from pandas.io.formats.format import _get_format_datetime64_from_values diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index b936a4e26af60..97cb3fbd877dd 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -21,10 +21,11 @@ import pandas.tseries.frequencies as frequencies from pandas.tseries.frequencies import get_freq_code as _gfc +from pandas.tseries.offsets import Tick, DateOffset + from pandas.core.indexes.datetimes import DatetimeIndex, Int64Index, Index from pandas.core.indexes.datetimelike import DatelikeOps, DatetimeIndexOpsMixin from pandas.core.tools.datetimes import parse_time_string -import pandas.tseries.offsets as offsets from pandas._libs.lib import infer_dtype from pandas._libs import tslib, index as libindex @@ -680,9 +681,9 @@ def to_timestamp(self, freq=None, how='start'): def _maybe_convert_timedelta(self, other): if isinstance( - other, (timedelta, np.timedelta64, offsets.Tick, np.ndarray)): + other, (timedelta, np.timedelta64, Tick, np.ndarray)): offset = frequencies.to_offset(self.freq.rule_code) - if isinstance(offset, offsets.Tick): + if isinstance(offset, Tick): if isinstance(other, np.ndarray): nanos = np.vectorize(delta_to_nanoseconds)(other) else: @@ -691,7 +692,7 @@ def _maybe_convert_timedelta(self, other): check = np.all(nanos % offset_nanos == 0) if check: return nanos // offset_nanos - elif isinstance(other, offsets.DateOffset): + elif isinstance(other, DateOffset): freqstr = other.rule_code base = frequencies.get_base_alias(freqstr) if base == self.freq.rule_code: @@ -707,6 +708,30 @@ def _maybe_convert_timedelta(self, other): msg = "Input has different freq from PeriodIndex(freq={0})" raise IncompatibleFrequency(msg.format(self.freqstr)) + def _add_offset(self, other): + assert not isinstance(other, Tick) + base = frequencies.get_base_alias(other.rule_code) + if base != self.freq.rule_code: + msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + raise IncompatibleFrequency(msg) + return self.shift(other.n) + + def _add_delta_td(self, other): + assert isinstance(other, (timedelta, np.timedelta64, Tick)) + nanos = delta_to_nanoseconds(other) + own_offset = frequencies.to_offset(self.freq.rule_code) + + if isinstance(own_offset, Tick): + offset_nanos = delta_to_nanoseconds(own_offset) + if np.all(nanos % offset_nanos == 0): + return self.shift(nanos // offset_nanos) + + # raise when input doesn't have freq + raise IncompatibleFrequency("Input has different freq from " + "{cls}(freq={freqstr})" + .format(cls=type(self).__name__, + freqstr=self.freqstr)) + def _add_delta(self, other): ordinal_delta = self._maybe_convert_timedelta(other) return self.shift(ordinal_delta) diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index c42c0656c585a..a14de18b1012f 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -353,6 +353,12 @@ def _maybe_update_attributes(self, attrs): attrs['freq'] = 'infer' return attrs + def _add_offset(self, other): + assert not isinstance(other, Tick) + raise TypeError("cannot add the type {typ} to a {cls}" + .format(typ=type(other).__name__, + cls=type(self).__name__)) + def _add_delta(self, delta): """ Add a timedelta-like, Tick, or TimedeltaIndex-like object diff --git a/pandas/tests/indexes/datetimes/test_arithmetic.py b/pandas/tests/indexes/datetimes/test_arithmetic.py index 0c56c6b16fb2f..8f259a7e78897 100644 --- a/pandas/tests/indexes/datetimes/test_arithmetic.py +++ b/pandas/tests/indexes/datetimes/test_arithmetic.py @@ -14,6 +14,7 @@ from pandas import (Timestamp, Timedelta, Series, DatetimeIndex, TimedeltaIndex, date_range) +from pandas.core import ops from pandas._libs import tslib from pandas._libs.tslibs.offsets import shift_months @@ -307,6 +308,17 @@ def test_dti_cmp_list(self): class TestDatetimeIndexArithmetic(object): + # ------------------------------------------------------------- + # Invalid Operations + + @pytest.mark.parametrize('other', [3.14, np.array([2.0, 3.0])]) + @pytest.mark.parametrize('op', [operator.add, ops.radd, + operator.sub, ops.rsub]) + def test_dti_add_sub_float(self, op, other): + dti = DatetimeIndex(['2011-01-01', '2011-01-02'], freq='D') + with pytest.raises(TypeError): + op(dti, other) + def test_dti_add_timestamp_raises(self): idx = DatetimeIndex(['2011-01-01', '2011-01-02']) msg = "cannot add DatetimeIndex and Timestamp" diff --git a/pandas/tests/indexes/period/test_arithmetic.py b/pandas/tests/indexes/period/test_arithmetic.py index d7bf1e0210f62..c75fdd35a974c 100644 --- a/pandas/tests/indexes/period/test_arithmetic.py +++ b/pandas/tests/indexes/period/test_arithmetic.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- from datetime import timedelta +import operator + import pytest import numpy as np @@ -9,6 +11,7 @@ period_range, Period, PeriodIndex, _np_version_under1p10) import pandas.core.indexes.period as period +from pandas.core import ops from pandas.errors import PerformanceWarning @@ -256,6 +259,18 @@ def test_comp_nat(self, dtype): class TestPeriodIndexArithmetic(object): + # ------------------------------------------------------------- + # Invalid Operations + + @pytest.mark.parametrize('other', [3.14, np.array([2.0, 3.0])]) + @pytest.mark.parametrize('op', [operator.add, ops.radd, + operator.sub, ops.rsub]) + def test_pi_add_sub_float(self, op, other): + dti = pd.DatetimeIndex(['2011-01-01', '2011-01-02'], freq='D') + pi = dti.to_period('D') + with pytest.raises(TypeError): + op(pi, other) + # ----------------------------------------------------------------- # __add__/__sub__ with ndarray[datetime64] and ndarray[timedelta64] diff --git a/pandas/tests/indexes/timedeltas/test_arithmetic.py b/pandas/tests/indexes/timedeltas/test_arithmetic.py index 9ffffb6ff06d5..9035434046ccb 100644 --- a/pandas/tests/indexes/timedeltas/test_arithmetic.py +++ b/pandas/tests/indexes/timedeltas/test_arithmetic.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +import operator + import pytest import numpy as np from datetime import timedelta @@ -11,6 +13,7 @@ Series, Timestamp, Timedelta) from pandas.errors import PerformanceWarning, NullFrequencyError +from pandas.core import ops @pytest.fixture(params=[pd.offsets.Hour(2), timedelta(hours=2), @@ -270,6 +273,15 @@ class TestTimedeltaIndexArithmetic(object): # ------------------------------------------------------------- # Invalid Operations + @pytest.mark.parametrize('other', [3.14, np.array([2.0, 3.0])]) + @pytest.mark.parametrize('op', [operator.add, ops.radd, + operator.sub, ops.rsub]) + def test_tdi_add_sub_float(self, op, other): + dti = DatetimeIndex(['2011-01-01', '2011-01-02'], freq='D') + tdi = dti - dti.shift(1) + with pytest.raises(TypeError): + op(tdi, other) + def test_tdi_add_str_invalid(self): # GH 13624 tdi = TimedeltaIndex(['1 day', '2 days'])
Align some of the dispatching logic between that is currently special-cased by PeriodIndex. Should avoid overlap with #19903. Catch some currently-implicit cases explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/19912
2018-02-26T16:49:24Z
2018-03-06T12:27:22Z
2018-03-06T12:27:22Z
2018-06-22T03:31:34Z
ENH: ExtensionArray.fillna
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index e838afdbbd083..4add3b9e80280 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -843,6 +843,7 @@ Categorical - Bug in :meth:`Series.astype` and ``Categorical.astype()`` where an existing categorical data does not get updated (:issue:`10696`, :issue:`18593`) - Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`) - Bug in :class:`Series` constructor with scalar and ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19565`) +- Bug in ``Categorical.__iter__`` not converting to Python types (:issue:`19909`) - Bug in :func:`pandas.factorize` returning the unique codes for the ``uniques``. This now returns a ``Categorical`` with the same dtype as the input (:issue:`19721`) - Bug in :func:`pandas.factorize` including an item for missing values in the ``uniques`` return value (:issue:`19721`) diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 1f33081a5f610..fa565aa802faf 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -236,6 +236,59 @@ def isna(self): """ raise AbstractMethodError(self) + def fillna(self, value=None, method=None, limit=None): + """ Fill NA/NaN values using the specified method. + + Parameters + ---------- + value : scalar, array-like + If a scalar value is passed it is used to fill all missing values. + Alternatively, an array-like 'value' can be given. It's expected + that the array-like have the same length as 'self'. + method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None + Method to use for filling holes in reindexed Series + pad / ffill: propagate last valid observation forward to next valid + backfill / bfill: use NEXT valid observation to fill gap + limit : int, default None + If method is specified, this is the maximum number of consecutive + NaN values to forward/backward fill. In other words, if there is + a gap with more than this number of consecutive NaNs, it will only + be partially filled. If method is not specified, this is the + maximum number of entries along the entire axis where NaNs will be + filled. + + Returns + ------- + filled : ExtensionArray with NA/NaN filled + """ + from pandas.api.types import is_scalar + from pandas.util._validators import validate_fillna_kwargs + from pandas.core.missing import pad_1d, backfill_1d + + value, method = validate_fillna_kwargs(value, method) + + mask = self.isna() + + if not is_scalar(value): + if len(value) != len(self): + raise ValueError("Length of 'value' does not match. Got ({}) " + " expected {}".format(len(value), len(self))) + value = value[mask] + + if mask.any(): + if method is not None: + func = pad_1d if method == 'pad' else backfill_1d + new_values = func(self.astype(object), limit=limit, + mask=mask) + new_values = self._constructor_from_sequence(new_values) + else: + # fill with value + new_values = self.copy() + new_values[mask] = value + else: + new_values = self.copy() + return new_values + def unique(self): """Compute the ExtensionArray of unique values. @@ -285,6 +338,7 @@ def take(self, indexer, allow_fill=True, fill_value=None): .. code-block:: python def take(self, indexer, allow_fill=True, fill_value=None): + indexer = np.asarray(indexer) mask = indexer == -1 result = self.data.take(indexer) result[mask] = np.nan # NA for this type diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index b37f88d8bfdce..43b8bc6244637 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -480,9 +480,7 @@ def tolist(self): (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period) """ - if is_datetimelike(self.categories): - return [com._maybe_box_datetimelike(x) for x in self] - return np.array(self).tolist() + return list(self) @property def base(self): @@ -1592,16 +1590,16 @@ def fillna(self, value=None, method=None, limit=None): Parameters ---------- - method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None - Method to use for filling holes in reindexed Series - pad / ffill: propagate last valid observation forward to next valid - backfill / bfill: use NEXT valid observation to fill gap value : scalar, dict, Series If a scalar value is passed it is used to fill all missing values. Alternatively, a Series or dict can be used to fill in different values for each index. The value should not be a list. The value(s) passed should either be in the categories or should be NaN. + method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None + Method to use for filling holes in reindexed Series + pad / ffill: propagate last valid observation forward to next valid + backfill / bfill: use NEXT valid observation to fill gap limit : int, default None (Not implemented yet for Categorical!) If method is specified, this is the maximum number of consecutive @@ -1717,7 +1715,7 @@ def __len__(self): def __iter__(self): """Returns an Iterator over the values of this Categorical.""" - return iter(self.get_values()) + return iter(self.get_values().tolist()) def _tidy_repr(self, max_vals=10, footer=True): """ a short repr displaying only max_vals and an optional (but default diff --git a/pandas/core/base.py b/pandas/core/base.py index 257b26b64e642..3ccfe88a1d54d 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -9,10 +9,10 @@ from pandas.core.dtypes.missing import isna from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries, ABCIndexClass from pandas.core.dtypes.common import ( + is_datetimelike, is_object_dtype, is_list_like, is_scalar, - is_datetimelike, is_extension_type, is_extension_array_dtype) @@ -826,9 +826,10 @@ def tolist(self): -------- numpy.ndarray.tolist """ - - if is_datetimelike(self): + if is_datetimelike(self._values): return [com._maybe_box_datetimelike(x) for x in self._values] + elif is_extension_array_dtype(self._values): + return list(self._values) else: return self._values.tolist() diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index b1d0dc2a2442e..747dfe62e1fb7 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -11,7 +11,8 @@ from .common import (_ensure_object, is_bool, is_integer, is_float, is_complex, is_datetimetz, is_categorical_dtype, is_datetimelike, - is_extension_type, is_object_dtype, + is_extension_type, + is_object_dtype, is_datetime64tz_dtype, is_datetime64_dtype, is_datetime64_ns_dtype, is_timedelta64_dtype, is_timedelta64_ns_dtype, diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 240c9b1f3377c..81baa3734f12f 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -1963,6 +1963,23 @@ def concat_same_type(self, to_concat, placement=None): return self.make_block_same_class(values, ndim=self.ndim, placement=placement) + def fillna(self, value, limit=None, inplace=False, downcast=None, + mgr=None): + values = self.values if inplace else self.values.copy() + values = values.fillna(value=value, limit=limit) + return [self.make_block_same_class(values=values, + placement=self.mgr_locs, + ndim=self.ndim)] + + def interpolate(self, method='pad', axis=0, inplace=False, limit=None, + fill_value=None, **kwargs): + + values = self.values if inplace else self.values.copy() + return self.make_block_same_class( + values=values.fillna(value=fill_value, method=method, + limit=limit), + placement=self.mgr_locs) + class NumericBlock(Block): __slots__ = () @@ -2522,27 +2539,6 @@ def _try_coerce_result(self, result): return result - def fillna(self, value, limit=None, inplace=False, downcast=None, - mgr=None): - # we may need to upcast our fill to match our dtype - if limit is not None: - raise NotImplementedError("specifying a limit for 'fillna' has " - "not been implemented yet") - - values = self.values if inplace else self.values.copy() - values = self._try_coerce_result(values.fillna(value=value, - limit=limit)) - return [self.make_block(values=values)] - - def interpolate(self, method='pad', axis=0, inplace=False, limit=None, - fill_value=None, **kwargs): - - values = self.values if inplace else self.values.copy() - return self.make_block_same_class( - values=values.fillna(fill_value=fill_value, method=method, - limit=limit), - placement=self.mgr_locs) - def shift(self, periods, axis=0, mgr=None): return self.make_block_same_class(values=self.values.shift(periods), placement=self.mgr_locs) diff --git a/pandas/tests/categorical/test_dtypes.py b/pandas/tests/categorical/test_dtypes.py index 8973d1196f6a9..00e99db628c2a 100644 --- a/pandas/tests/categorical/test_dtypes.py +++ b/pandas/tests/categorical/test_dtypes.py @@ -1,12 +1,12 @@ # -*- coding: utf-8 -*- - import pytest import numpy as np import pandas.util.testing as tm from pandas.core.dtypes.dtypes import CategoricalDtype -from pandas import Categorical, Index, CategoricalIndex, Series +from pandas.compat import long +from pandas import Categorical, Index, CategoricalIndex, Series, Timestamp class TestCategoricalDtypes(object): @@ -161,3 +161,16 @@ def test_astype_category(self, dtype_ordered, cat_ordered): result = cat.astype('category') expected = cat tm.assert_categorical_equal(result, expected) + + def test_iter_python_types(self): + # GH-19909 + # TODO(Py2): Remove long + cat = Categorical([1, 2]) + assert isinstance(list(cat)[0], (int, long)) + assert isinstance(cat.tolist()[0], (int, long)) + + def test_iter_python_types_datetime(self): + cat = Categorical([Timestamp('2017-01-01'), + Timestamp('2017-01-02')]) + assert isinstance(list(cat)[0], Timestamp) + assert isinstance(cat.tolist()[0], Timestamp) diff --git a/pandas/tests/extension/base/casting.py b/pandas/tests/extension/base/casting.py index adc690939b36c..74fe8f196a089 100644 --- a/pandas/tests/extension/base/casting.py +++ b/pandas/tests/extension/base/casting.py @@ -11,3 +11,8 @@ def test_astype_object_series(self, all_data): ser = pd.Series({"A": all_data}) result = ser.astype(object) assert isinstance(result._data.blocks[0], ObjectBlock) + + def test_tolist(self, data): + result = pd.Series(data).tolist() + expected = list(data) + assert result == expected diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py index 3ae82fa1ca432..bf404ac01bf2b 100644 --- a/pandas/tests/extension/base/missing.py +++ b/pandas/tests/extension/base/missing.py @@ -1,4 +1,5 @@ import numpy as np +import pytest import pandas as pd import pandas.util.testing as tm @@ -45,3 +46,71 @@ def test_dropna_frame(self, data_missing): result = df.dropna() expected = df.iloc[:0] self.assert_frame_equal(result, expected) + + def test_fillna_limit_pad(self, data_missing): + arr = data_missing.take([1, 0, 0, 0, 1]) + result = pd.Series(arr).fillna(method='ffill', limit=2) + expected = pd.Series(data_missing.take([1, 1, 1, 0, 1])) + self.assert_series_equal(result, expected) + + def test_fillna_limit_backfill(self, data_missing): + arr = data_missing.take([1, 0, 0, 0, 1]) + result = pd.Series(arr).fillna(method='backfill', limit=2) + expected = pd.Series(data_missing.take([1, 0, 1, 1, 1])) + self.assert_series_equal(result, expected) + + def test_fillna_series(self, data_missing): + fill_value = data_missing[1] + ser = pd.Series(data_missing) + + result = ser.fillna(fill_value) + expected = pd.Series(type(data_missing)([fill_value, fill_value])) + self.assert_series_equal(result, expected) + + # Fill with a series + result = ser.fillna(expected) + self.assert_series_equal(result, expected) + + # Fill with a series not affecting the missing values + result = ser.fillna(ser) + self.assert_series_equal(result, ser) + + @pytest.mark.parametrize('method', ['ffill', 'bfill']) + def test_fillna_series_method(self, data_missing, method): + fill_value = data_missing[1] + + if method == 'ffill': + data_missing = type(data_missing)(data_missing[::-1]) + + result = pd.Series(data_missing).fillna(method=method) + expected = pd.Series(type(data_missing)([fill_value, fill_value])) + + self.assert_series_equal(result, expected) + + def test_fillna_frame(self, data_missing): + fill_value = data_missing[1] + + result = pd.DataFrame({ + "A": data_missing, + "B": [1, 2] + }).fillna(fill_value) + + expected = pd.DataFrame({ + "A": type(data_missing)([fill_value, fill_value]), + "B": [1, 2], + }) + + self.assert_frame_equal(result, expected) + + def test_fillna_fill_other(self, data): + result = pd.DataFrame({ + "A": data, + "B": [np.nan] * len(data) + }).fillna({"B": 0.0}) + + expected = pd.DataFrame({ + "A": data, + "B": [0.0] * len(result), + }) + + self.assert_frame_equal(result, expected) diff --git a/pandas/tests/extension/category/test_categorical.py b/pandas/tests/extension/category/test_categorical.py index 8f413b4a19730..b6dd181c1d8f3 100644 --- a/pandas/tests/extension/category/test_categorical.py +++ b/pandas/tests/extension/category/test_categorical.py @@ -69,7 +69,14 @@ def test_getitem_scalar(self): class TestMissing(base.BaseMissingTests): - pass + + @pytest.mark.skip(reason="Not implemented") + def test_fillna_limit_pad(self): + pass + + @pytest.mark.skip(reason="Not implemented") + def test_fillna_limit_backfill(self): + pass class TestMethods(base.BaseMethodsTests): diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 736556e4be20d..f1852542088ff 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -71,6 +71,7 @@ def isna(self): return np.array([x.is_nan() for x in self.values]) def take(self, indexer, allow_fill=True, fill_value=None): + indexer = np.asarray(indexer) mask = indexer == -1 indexer = _ensure_platform_int(indexer) diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 7b4d079ecad87..01ae092bc1521 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -35,68 +35,59 @@ def na_value(): return decimal.Decimal("NaN") -class TestDtype(base.BaseDtypeTests): - pass +class BaseDecimal(object): + @staticmethod + def assert_series_equal(left, right, *args, **kwargs): + # tm.assert_series_equal doesn't handle Decimal('NaN'). + # We will ensure that the NA values match, and then + # drop those values before moving on. + left_na = left.isna() + right_na = right.isna() -class TestInterface(base.BaseInterfaceTests): - pass + tm.assert_series_equal(left_na, right_na) + tm.assert_series_equal(left[~left_na], right[~right_na], + *args, **kwargs) + @staticmethod + def assert_frame_equal(left, right, *args, **kwargs): + # TODO(EA): select_dtypes + decimals = (left.dtypes == 'decimal').index -class TestConstructors(base.BaseConstructorsTests): - pass + for col in decimals: + BaseDecimal.assert_series_equal(left[col], right[col], + *args, **kwargs) + left = left.drop(columns=decimals) + right = right.drop(columns=decimals) + tm.assert_frame_equal(left, right, *args, **kwargs) -class TestReshaping(base.BaseReshapingTests): - def test_align(self, data, na_value): - # Have to override since assert_series_equal doesn't - # compare Decimal(NaN) properly. - a = data[:3] - b = data[2:5] - r1, r2 = pd.Series(a).align(pd.Series(b, index=[1, 2, 3])) +class TestDtype(BaseDecimal, base.BaseDtypeTests): + pass - # NaN handling - e1 = pd.Series(type(data)(list(a) + [na_value])) - e2 = pd.Series(type(data)([na_value] + list(b))) - tm.assert_series_equal(r1.iloc[:3], e1.iloc[:3]) - assert r1[3].is_nan() - assert e1[3].is_nan() - tm.assert_series_equal(r2.iloc[1:], e2.iloc[1:]) - assert r2[0].is_nan() - assert e2[0].is_nan() +class TestInterface(BaseDecimal, base.BaseInterfaceTests): + pass - def test_align_frame(self, data, na_value): - # Override for Decimal(NaN) comparison - a = data[:3] - b = data[2:5] - r1, r2 = pd.DataFrame({'A': a}).align( - pd.DataFrame({'A': b}, index=[1, 2, 3]) - ) - # Assumes that the ctor can take a list of scalars of the type - e1 = pd.DataFrame({'A': type(data)(list(a) + [na_value])}) - e2 = pd.DataFrame({'A': type(data)([na_value] + list(b))}) +class TestConstructors(BaseDecimal, base.BaseConstructorsTests): + pass - tm.assert_frame_equal(r1.iloc[:3], e1.iloc[:3]) - assert r1.loc[3, 'A'].is_nan() - assert e1.loc[3, 'A'].is_nan() - tm.assert_frame_equal(r2.iloc[1:], e2.iloc[1:]) - assert r2.loc[0, 'A'].is_nan() - assert e2.loc[0, 'A'].is_nan() +class TestReshaping(BaseDecimal, base.BaseReshapingTests): + pass -class TestGetitem(base.BaseGetitemTests): +class TestGetitem(BaseDecimal, base.BaseGetitemTests): pass -class TestMissing(base.BaseMissingTests): +class TestMissing(BaseDecimal, base.BaseMissingTests): pass -class TestMethods(base.BaseMethodsTests): +class TestMethods(BaseDecimal, base.BaseMethodsTests): @pytest.mark.parametrize('dropna', [True, False]) @pytest.mark.xfail(reason="value_counts not implemented yet.") def test_value_counts(self, all_data, dropna): @@ -112,7 +103,7 @@ def test_value_counts(self, all_data, dropna): tm.assert_series_equal(result, expected) -class TestCasting(base.BaseCastingTests): +class TestCasting(BaseDecimal, base.BaseCastingTests): pass diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index e0721bb1d8d1a..16d5e4415a79f 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -60,7 +60,13 @@ class TestGetitem(base.BaseGetitemTests): class TestMissing(base.BaseMissingTests): - pass + @pytest.mark.xfail(reason="Setting a dict as a scalar") + def test_fillna_series(self): + """We treat dictionaries as a mapping in fillna, not a scalar.""" + + @pytest.mark.xfail(reason="Setting a dict as a scalar") + def test_fillna_frame(self): + """We treat dictionaries as a mapping in fillna, not a scalar.""" class TestMethods(base.BaseMethodsTests):
xref https://github.com/pandas-dev/pandas/issues/19696 This adds `ExtensionArray.fillna`, and support for `NDFrame.fillna` with extension arrays. Like `Categorical.fillna`, `limit` is not implemented. This shouldn't make it any harder to support that in the future.
https://api.github.com/repos/pandas-dev/pandas/pulls/19909
2018-02-26T16:25:55Z
2018-03-16T21:44:35Z
2018-03-16T21:44:35Z
2018-05-02T13:10:12Z
DOC: update install.rst to include ActivePython distribution
diff --git a/doc/source/install.rst b/doc/source/install.rst index 4ff63d59024b2..e3667221e5166 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -12,7 +12,7 @@ cross platform distribution for data analysis and scientific computing. This is the recommended installation method for most users. Instructions for installing from source, -`PyPI <http://pypi.python.org/pypi/pandas>`__, various Linux distributions, or a +`PyPI <http://pypi.python.org/pypi/pandas>`__, `ActivePython <https://www.activestate.com/activepython/downloads>`__, various Linux distributions, or a `development version <http://github.com/pandas-dev/pandas>`__ are also provided. Python version support @@ -25,8 +25,8 @@ Installing pandas .. _install.anaconda: -Installing pandas with Anaconda -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Installing with Anaconda +~~~~~~~~~~~~~~~~~~~~~~~~ Installing pandas and the rest of the `NumPy <http://www.numpy.org/>`__ and `SciPy <http://www.scipy.org/>`__ stack can be a little @@ -58,8 +58,8 @@ that folder). .. _install.miniconda: -Installing pandas with Miniconda -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Installing with Miniconda +~~~~~~~~~~~~~~~~~~~~~~~~~ The previous section outlined how to get pandas installed as part of the `Anaconda <http://docs.continuum.io/anaconda/>`__ distribution. @@ -134,6 +134,10 @@ pandas can be installed via pip from pip install pandas +Installing with ActivePython +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Installation instructions for `ActivePython <https://www.activestate.com/activepython>`__ can be found `here <https://www.activestate.com/activepython/downloads>`__. Installing using your Linux distribution's package manager. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -164,7 +168,7 @@ Installing from source See the :ref:`contributing documentation <contributing>` for complete instructions on building from the git source tree. Further, see :ref:`creating a development environment <contributing.dev_env>` if you wish to create a *pandas* development environment. Running the test suite -~~~~~~~~~~~~~~~~~~~~~~ +---------------------- pandas is equipped with an exhaustive set of unit tests, covering about 97% of the codebase as of this writing. To run it on your machine to verify that @@ -299,5 +303,5 @@ Optional Dependencies Without the optional dependencies, many useful features will not work. Hence, it is highly recommended that you install these. A packaged - distribution like `Anaconda <http://docs.continuum.io/anaconda/>`__, or `Enthought Canopy + distribution like `Anaconda <http://docs.continuum.io/anaconda/>`__, `ActivePython <https://www.activestate.com/activepython/downloads>`__, or `Enthought Canopy <http://enthought.com/products/canopy>`__ may be worth considering.
PR associated with [Issue #19845](https://github.com/pandas-dev/pandas/issues/19845#issuecomment-367879282): update Installation webpage to include ActivePython distribution per @jreback - [ ] closes #19845 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/19908
2018-02-26T16:09:02Z
2018-03-02T11:33:50Z
2018-03-02T11:33:50Z
2018-03-02T12:50:40Z
ENH: ExtensionArray.setitem
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7c0e367e74ffa..26c51ce93a47b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3330,7 +3330,11 @@ def reindexer(value): value = reindexer(value).T elif isinstance(value, ExtensionArray): + from pandas.core.series import _sanitize_index + # Explicitly copy here, instead of in _sanitize_index, + # as sanitize_index won't copy an EA, even with copy=True value = value.copy() + value = _sanitize_index(value, self.index, copy=False) elif isinstance(value, Index) or is_sequence(value): from pandas.core.series import _sanitize_index diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 9736bba78ab72..5240a4703c242 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2310,6 +2310,49 @@ def check_bool_indexer(ax, key): return result +def check_setitem_lengths(indexer, value, values): + """Validate that value and indexer are the same length. + + An special-case is allowed for when the indexer is a boolean array + and the number of true values equals the length of ``value``. In + this case, no exception is raised. + + Parameters + ---------- + indexer : sequence + The key for the setitem + value : array-like + The value for the setitem + values : array-like + The values being set into + + Returns + ------- + None + + Raises + ------ + ValueError + When the indexer is an ndarray or list and the lengths don't + match. + """ + # boolean with truth values == len of the value is ok too + if isinstance(indexer, (np.ndarray, list)): + if is_list_like(value) and len(indexer) != len(value): + if not (isinstance(indexer, np.ndarray) and + indexer.dtype == np.bool_ and + len(indexer[indexer]) == len(value)): + raise ValueError("cannot set using a list-like indexer " + "with a different length than the value") + # slice + elif isinstance(indexer, slice): + + if is_list_like(value) and len(values): + if len(value) != length_of_indexer(indexer, values): + raise ValueError("cannot set using a slice indexer with a " + "different length than the value") + + def convert_missing_indexer(indexer): """ reverse convert a missing indexer, which is a dict return the scalar indexer and a boolean indicating if we converted diff --git a/pandas/core/internals.py b/pandas/core/internals.py index e8fab3748bacf..37d11296400be 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -66,7 +66,7 @@ import pandas.core.algorithms as algos from pandas.core.index import Index, MultiIndex, _ensure_index -from pandas.core.indexing import maybe_convert_indices, length_of_indexer +from pandas.core.indexing import maybe_convert_indices, check_setitem_lengths from pandas.core.arrays import Categorical from pandas.core.indexes.datetimes import DatetimeIndex from pandas.core.indexes.timedeltas import TimedeltaIndex @@ -817,11 +817,24 @@ def _replace_single(self, *args, **kwargs): return self if kwargs['inplace'] else self.copy() def setitem(self, indexer, value, mgr=None): - """ set the value inplace; return a new block (of a possibly different - dtype) + """Set the value inplace, returning a a maybe different typed block. - indexer is a direct slice/positional indexer; value must be a - compatible shape + Parameters + ---------- + indexer : tuple, list-like, array-like, slice + The subset of self.values to set + value : object + The value being set + mgr : BlockPlacement, optional + + Returns + ------- + Block + + Notes + ----- + `indexer` is a direct slice/positional indexer. `value` must + be a compatible shape. """ # coerce None values, if appropriate if value is None: @@ -876,22 +889,7 @@ def setitem(self, indexer, value, mgr=None): values = transf(values) # length checking - # boolean with truth values == len of the value is ok too - if isinstance(indexer, (np.ndarray, list)): - if is_list_like(value) and len(indexer) != len(value): - if not (isinstance(indexer, np.ndarray) and - indexer.dtype == np.bool_ and - len(indexer[indexer]) == len(value)): - raise ValueError("cannot set using a list-like indexer " - "with a different length than the value") - - # slice - elif isinstance(indexer, slice): - - if is_list_like(value) and len(values): - if len(value) != length_of_indexer(indexer, values): - raise ValueError("cannot set using a slice indexer with a " - "different length than the value") + check_setitem_lengths(indexer, value, values) def _is_scalar_indexer(indexer): # return True if we are all scalar indexers @@ -1900,6 +1898,37 @@ def is_view(self): """Extension arrays are never treated as views.""" return False + def setitem(self, indexer, value, mgr=None): + """Set the value inplace, returning a same-typed block. + + This differs from Block.setitem by not allowing setitem to change + the dtype of the Block. + + Parameters + ---------- + indexer : tuple, list-like, array-like, slice + The subset of self.values to set + value : object + The value being set + mgr : BlockPlacement, optional + + Returns + ------- + Block + + Notes + ----- + `indexer` is a direct slice/positional indexer. `value` must + be a compatible shape. + """ + if isinstance(indexer, tuple): + # we are always 1-D + indexer = indexer[0] + + check_setitem_lengths(indexer, value, self.values) + self.values[indexer] = value + return self + def get_values(self, dtype=None): # ExtensionArrays must be iterable, so this works. values = np.asarray(self.values) @@ -3519,7 +3548,8 @@ def apply(self, f, axes=None, filter=None, do_integrity_check=False, # with a .values attribute. aligned_args = dict((k, kwargs[k]) for k in align_keys - if hasattr(kwargs[k], 'values')) + if hasattr(kwargs[k], 'values') and + not isinstance(kwargs[k], ABCExtensionArray)) for b in self.blocks: if filter is not None: @@ -5220,7 +5250,7 @@ def _safe_reshape(arr, new_shape): If possible, reshape `arr` to have shape `new_shape`, with a couple of exceptions (see gh-13012): - 1) If `arr` is a Categorical or Index, `arr` will be + 1) If `arr` is a ExtensionArray or Index, `arr` will be returned as is. 2) If `arr` is a Series, the `_values` attribute will be reshaped and returned. diff --git a/pandas/tests/extension/base/__init__.py b/pandas/tests/extension/base/__init__.py index f8078d2798b32..9da985625c4ee 100644 --- a/pandas/tests/extension/base/__init__.py +++ b/pandas/tests/extension/base/__init__.py @@ -49,3 +49,4 @@ class TestMyDtype(BaseDtypeTests): from .methods import BaseMethodsTests # noqa from .missing import BaseMissingTests # noqa from .reshaping import BaseReshapingTests # noqa +from .setitem import BaseSetitemTests # noqa diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py new file mode 100644 index 0000000000000..e91345b504d86 --- /dev/null +++ b/pandas/tests/extension/base/setitem.py @@ -0,0 +1,167 @@ +import operator + +import numpy as np +import pytest + +import pandas as pd +import pandas.util.testing as tm +from .base import BaseExtensionTests + + +class BaseSetitemTests(BaseExtensionTests): + def test_setitem_scalar_series(self, data): + arr = pd.Series(data) + arr[0] = data[1] + assert arr[0] == data[1] + + def test_setitem_sequence(self, data): + arr = pd.Series(data) + original = data.copy() + + arr[[0, 1]] = [data[1], data[0]] + assert arr[0] == original[1] + assert arr[1] == original[0] + + @pytest.mark.parametrize('as_array', [True, False]) + def test_setitem_sequence_mismatched_length_raises(self, data, as_array): + ser = pd.Series(data) + value = [data[0]] + if as_array: + value = type(data)(value) + + xpr = 'cannot set using a {} indexer with a different length' + with tm.assert_raises_regex(ValueError, xpr.format('list-like')): + ser[[0, 1]] = value + + with tm.assert_raises_regex(ValueError, xpr.format('slice')): + ser[slice(3)] = value + + def test_setitem_empty_indxer(self, data): + ser = pd.Series(data) + original = ser.copy() + ser[[]] = [] + self.assert_series_equal(ser, original) + + def test_setitem_sequence_broadcasts(self, data): + arr = pd.Series(data) + + arr[[0, 1]] = data[2] + assert arr[0] == data[2] + assert arr[1] == data[2] + + @pytest.mark.parametrize('setter', ['loc', 'iloc']) + def test_setitem_scalar(self, data, setter): + arr = pd.Series(data) + setter = getattr(arr, setter) + operator.setitem(setter, 0, data[1]) + assert arr[0] == data[1] + + def test_setitem_loc_scalar_mixed(self, data): + df = pd.DataFrame({"A": np.arange(len(data)), "B": data}) + df.loc[0, 'B'] = data[1] + assert df.loc[0, 'B'] == data[1] + + def test_setitem_loc_scalar_single(self, data): + df = pd.DataFrame({"B": data}) + df.loc[10, 'B'] = data[1] + assert df.loc[10, 'B'] == data[1] + + def test_setitem_loc_scalar_multiple_homogoneous(self, data): + df = pd.DataFrame({"A": data, "B": data}) + df.loc[10, 'B'] = data[1] + assert df.loc[10, 'B'] == data[1] + + def test_setitem_iloc_scalar_mixed(self, data): + df = pd.DataFrame({"A": np.arange(len(data)), "B": data}) + df.iloc[0, 1] = data[1] + assert df.loc[0, 'B'] == data[1] + + def test_setitem_iloc_scalar_single(self, data): + df = pd.DataFrame({"B": data}) + df.iloc[10, 0] = data[1] + assert df.loc[10, 'B'] == data[1] + + def test_setitem_iloc_scalar_multiple_homogoneous(self, data): + df = pd.DataFrame({"A": data, "B": data}) + df.iloc[10, 1] = data[1] + assert df.loc[10, 'B'] == data[1] + + @pytest.mark.parametrize('as_callable', [True, False]) + @pytest.mark.parametrize('setter', ['loc', None]) + def test_setitem_mask_aligned(self, data, as_callable, setter): + ser = pd.Series(data) + mask = np.zeros(len(data), dtype=bool) + mask[:2] = True + + if as_callable: + mask2 = lambda x: mask + else: + mask2 = mask + + if setter: + # loc + target = getattr(ser, setter) + else: + # Series.__setitem__ + target = ser + + operator.setitem(target, mask2, data[5:7]) + + ser[mask2] = data[5:7] + assert ser[0] == data[5] + assert ser[1] == data[6] + + @pytest.mark.parametrize('setter', ['loc', None]) + def test_setitem_mask_broadcast(self, data, setter): + ser = pd.Series(data) + mask = np.zeros(len(data), dtype=bool) + mask[:2] = True + + if setter: # loc + target = getattr(ser, setter) + else: # __setitem__ + target = ser + + operator.setitem(target, mask, data[10]) + assert ser[0] == data[10] + assert ser[1] == data[10] + + def test_setitem_expand_columns(self, data): + df = pd.DataFrame({"A": data}) + result = df.copy() + result['B'] = 1 + expected = pd.DataFrame({"A": data, "B": [1] * len(data)}) + self.assert_frame_equal(result, expected) + + result = df.copy() + result.loc[:, 'B'] = 1 + self.assert_frame_equal(result, expected) + + # overwrite with new type + result['B'] = data + expected = pd.DataFrame({"A": data, "B": data}) + self.assert_frame_equal(result, expected) + + def test_setitem_expand_with_extension(self, data): + df = pd.DataFrame({"A": [1] * len(data)}) + result = df.copy() + result['B'] = data + expected = pd.DataFrame({"A": [1] * len(data), "B": data}) + self.assert_frame_equal(result, expected) + + result = df.copy() + result.loc[:, 'B'] = data + self.assert_frame_equal(result, expected) + + def test_setitem_frame_invalid_length(self, data): + df = pd.DataFrame({"A": [1] * len(data)}) + xpr = "Length of values does not match length of index" + with tm.assert_raises_regex(ValueError, xpr): + df['B'] = data[:5] + + @pytest.mark.xfail(reason="GH-20441: setitem on extension types.") + def test_setitem_tuple_index(self, data): + s = pd.Series(data[:2], index=[(0, 0), (0, 1)]) + expected = pd.Series(data.take([1, 1]), index=s.index) + s[(0, 1)] = data[1] + self.assert_series_equal(s, expected) diff --git a/pandas/tests/extension/category/test_categorical.py b/pandas/tests/extension/category/test_categorical.py index 7528299578326..6abf1f7f9a65a 100644 --- a/pandas/tests/extension/category/test_categorical.py +++ b/pandas/tests/extension/category/test_categorical.py @@ -85,6 +85,10 @@ def test_getitem_scalar(self): pass +class TestSetitem(base.BaseSetitemTests): + pass + + class TestMissing(base.BaseMissingTests): @pytest.mark.skip(reason="Not implemented") diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index b66a14c77a059..f93d11f579f11 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -31,6 +31,9 @@ def __init__(self, values): values = np.asarray(values, dtype=object) self.values = values + # Some aliases for common attribute names to ensure pandas supports + # these + self._items = self._data = self.data = self.values @classmethod def _constructor_from_sequence(cls, scalars): @@ -62,7 +65,7 @@ def __len__(self): return len(self.values) def __repr__(self): - return repr(self.values) + return 'DecimalArray({!r})'.format(self.values) @property def nbytes(self): diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 87668cc1196b6..dcf08440738e7 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -135,6 +135,10 @@ def test_astype_str(self): """ +# We intentionally don't run base.BaseSetitemTests because pandas' +# internals has trouble setting sequences of values into scalar positions. + + class TestGroupby(base.BaseGroupbyTests): @unhashable
xref https://github.com/pandas-dev/pandas/issues/19696 Adds `ExtensionBlock.__setitem__`. This is only tested for with `DecimalArray` and `Categorical`. Supporting something like `JSONArray` where the "scalar" elements are actual sequences runs into issues elsewhere in internals. Maybe someday we can support that.
https://api.github.com/repos/pandas-dev/pandas/pulls/19907
2018-02-26T16:05:47Z
2018-04-16T10:33:14Z
2018-04-16T10:33:14Z
2018-04-16T10:33:26Z
handle NaT add/sub in one place
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 8e56fc2775a56..4c6effc65a4d3 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- """ Base and utility classes for tseries type pandas objects. """ @@ -640,6 +641,28 @@ def _add_datelike(self, other): def _sub_datelike(self, other): raise com.AbstractMethodError(self) + def _add_nat(self): + """Add pd.NaT to self""" + if is_period_dtype(self): + raise TypeError('Cannot add {cls} and {typ}' + .format(cls=type(self).__name__, + typ=type(NaT).__name__)) + + # GH#19124 pd.NaT is treated like a timedelta for both timedelta + # and datetime dtypes + return self._nat_new(box=True) + + def _sub_nat(self): + """Subtract pd.NaT from self""" + # GH#19124 Timedelta - datetime is not in general well-defined. + # We make an exception for pd.NaT, which in this case quacks + # like a timedelta. + # For datetime64 dtypes by convention we treat NaT as a datetime, so + # this subtraction returns a timedelta64 dtype. + # For period dtype, timedelta64 is a close-enough return dtype. + result = self._nat_new(box=False) + return result.view('timedelta64[ns]') + def _sub_period(self, other): return NotImplemented @@ -686,6 +709,8 @@ def __add__(self, other): return NotImplemented # scalar others + elif other is NaT: + result = self._add_nat() elif isinstance(other, (DateOffset, timedelta, np.timedelta64)): result = self._add_delta(other) elif isinstance(other, (datetime, np.datetime64)): @@ -711,9 +736,13 @@ def __add__(self, other): else: # pragma: no cover return NotImplemented - if result is not NotImplemented: - res_name = ops.get_op_result_name(self, other) - result.name = res_name + if result is NotImplemented: + return NotImplemented + elif not isinstance(result, Index): + # Index.__new__ will choose appropriate subclass for dtype + result = Index(result) + res_name = ops.get_op_result_name(self, other) + result.name = res_name return result cls.__add__ = __add__ @@ -731,6 +760,8 @@ def __sub__(self, other): return NotImplemented # scalar others + elif other is NaT: + result = self._sub_nat() elif isinstance(other, (DateOffset, timedelta, np.timedelta64)): result = self._add_delta(-other) elif isinstance(other, (datetime, np.datetime64)): @@ -762,9 +793,13 @@ def __sub__(self, other): else: # pragma: no cover return NotImplemented - if result is not NotImplemented: - res_name = ops.get_op_result_name(self, other) - result.name = res_name + if result is NotImplemented: + return NotImplemented + elif not isinstance(result, Index): + # Index.__new__ will choose appropriate subclass for dtype + result = Index(result) + res_name = ops.get_op_result_name(self, other) + result.name = res_name return result cls.__sub__ = __sub__ diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 55d8b7c18a622..eb8133a1bbf97 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -853,22 +853,11 @@ def __setstate__(self, state): raise Exception("invalid pickle state") _unpickle_compat = __setstate__ - def _add_datelike(self, other): - # adding a timedeltaindex to a datetimelike - if other is libts.NaT: - return self._nat_new(box=True) - raise TypeError("cannot add {0} and {1}" - .format(type(self).__name__, - type(other).__name__)) - def _sub_datelike(self, other): - # subtract a datetime from myself, yielding a TimedeltaIndex - from pandas import TimedeltaIndex - + # subtract a datetime from myself, yielding a ndarray[timedelta64[ns]] if isinstance(other, (DatetimeIndex, np.ndarray)): # if other is an ndarray, we assume it is datetime64-dtype other = DatetimeIndex(other) - # require tz compat if not self._has_same_tz(other): raise TypeError("{cls} subtraction must have the same " @@ -876,9 +865,10 @@ def _sub_datelike(self, other): .format(cls=type(self).__name__)) result = self._sub_datelike_dti(other) elif isinstance(other, (datetime, np.datetime64)): + assert other is not libts.NaT other = Timestamp(other) if other is libts.NaT: - result = self._nat_new(box=False) + return self - libts.NaT # require tz compat elif not self._has_same_tz(other): raise TypeError("Timestamp subtraction must have the same " @@ -893,7 +883,7 @@ def _sub_datelike(self, other): raise TypeError("cannot subtract {cls} and {typ}" .format(cls=type(self).__name__, typ=type(other).__name__)) - return TimedeltaIndex(result) + return result.view('timedelta64[ns]') def _sub_datelike_dti(self, other): """subtraction of two DatetimeIndexes""" @@ -906,7 +896,7 @@ def _sub_datelike_dti(self, other): if self.hasnans or other.hasnans: mask = (self._isnan) | (other._isnan) new_values[mask] = libts.iNaT - return new_values.view('i8') + return new_values.view('timedelta64[ns]') def _maybe_update_attributes(self, attrs): """ Update Index attributes (e.g. freq) depending on op """ diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index f0567c9c963af..b936a4e26af60 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -12,7 +12,6 @@ is_scalar, is_datetime64_dtype, is_datetime64_any_dtype, - is_timedelta64_dtype, is_period_dtype, is_bool_dtype, pandas_dtype, @@ -23,7 +22,6 @@ import pandas.tseries.frequencies as frequencies from pandas.tseries.frequencies import get_freq_code as _gfc from pandas.core.indexes.datetimes import DatetimeIndex, Int64Index, Index -from pandas.core.indexes.timedeltas import TimedeltaIndex from pandas.core.indexes.datetimelike import DatelikeOps, DatetimeIndexOpsMixin from pandas.core.tools.datetimes import parse_time_string import pandas.tseries.offsets as offsets @@ -700,16 +698,6 @@ def _maybe_convert_timedelta(self, other): return other.n msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) - elif isinstance(other, np.ndarray): - if is_integer_dtype(other): - return other - elif is_timedelta64_dtype(other): - offset = frequencies.to_offset(self.freq) - if isinstance(offset, offsets.Tick): - nanos = delta_to_nanoseconds(other) - offset_nanos = delta_to_nanoseconds(offset) - if (nanos % offset_nanos).all() == 0: - return nanos // offset_nanos elif is_integer(other): # integer is passed to .shift via # _add_datetimelike_methods basically @@ -724,10 +712,7 @@ def _add_delta(self, other): return self.shift(ordinal_delta) def _sub_datelike(self, other): - if other is tslib.NaT: - new_data = np.empty(len(self), dtype=np.int64) - new_data.fill(tslib.iNaT) - return TimedeltaIndex(new_data) + assert other is not tslib.NaT return NotImplemented def _sub_period(self, other): diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index eebd52d7fb801..c42c0656c585a 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -414,16 +414,13 @@ def _evaluate_with_timedelta_like(self, other, op): def _add_datelike(self, other): # adding a timedeltaindex to a datetimelike from pandas import Timestamp, DatetimeIndex - - if other is NaT: - # GH#19124 pd.NaT is treated like a timedelta - return self._nat_new() - elif isinstance(other, (DatetimeIndex, np.ndarray)): + if isinstance(other, (DatetimeIndex, np.ndarray)): # if other is an ndarray, we assume it is datetime64-dtype # defer to implementation in DatetimeIndex other = DatetimeIndex(other) return other + self else: + assert other is not NaT other = Timestamp(other) i8 = self.asi8 result = checked_add_with_arr(i8, other.value, @@ -432,14 +429,9 @@ def _add_datelike(self, other): return DatetimeIndex(result) def _sub_datelike(self, other): - # GH#19124 Timedelta - datetime is not in general well-defined. - # We make an exception for pd.NaT, which in this case quacks - # like a timedelta. - if other is NaT: - return self._nat_new() - else: - raise TypeError("cannot subtract a datelike from a {cls}" - .format(cls=type(self).__name__)) + assert other is not NaT + raise TypeError("cannot subtract a datelike from a {cls}" + .format(cls=type(self).__name__)) def _addsub_offset_array(self, other, op): # Add or subtract Array-like of DateOffset objects
ATM DatetimeIndex/TimedeltaIndex/PeriodIndex each have special-casing for addition/subtraction of NaT. This checks for NaT up-front and puts all of that logic into add_nat and sub_nat methods. Also makes another step towards centralizing all of the wrapping of the add/sub ops at the end of `__add__` and `__sub__`. Should be orthogonal to other outstanding PRs, albeit just barely.
https://api.github.com/repos/pandas-dev/pandas/pulls/19903
2018-02-26T07:23:12Z
2018-02-27T11:36:23Z
2018-02-27T11:36:23Z
2018-06-22T03:31:13Z
ENH: implement DatetimeLikeArray
diff --git a/pandas/core/arrays/__init__.py b/pandas/core/arrays/__init__.py index f57348116c195..1b8a43d4293a5 100644 --- a/pandas/core/arrays/__init__.py +++ b/pandas/core/arrays/__init__.py @@ -1,3 +1,6 @@ from .base import (ExtensionArray, # noqa ExtensionScalarOpsMixin) from .categorical import Categorical # noqa +from .datetimes import DatetimeArrayMixin # noqa +from .period import PeriodArrayMixin # noqa +from .timedelta import TimedeltaArrayMixin # noqa diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py new file mode 100644 index 0000000000000..180417ce5e49c --- /dev/null +++ b/pandas/core/arrays/datetimelike.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- + +import numpy as np + +from pandas._libs import iNaT +from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds + +from pandas.tseries import frequencies + +import pandas.core.common as com +from pandas.core.algorithms import checked_add_with_arr + + +class DatetimeLikeArrayMixin(object): + """ + Shared Base/Mixin class for DatetimeArray, TimedeltaArray, PeriodArray + + Assumes that __new__/__init__ defines: + _data + _freq + + and that the inheriting class has methods: + _validate_frequency + """ + + @property + def _box_func(self): + """ + box function to get object from internal representation + """ + raise com.AbstractMethodError(self) + + def __iter__(self): + return (self._box_func(v) for v in self.asi8) + + @property + def values(self): + """ return the underlying data as an ndarray """ + return self._data.view(np.ndarray) + + @property + def asi8(self): + # do not cache or you'll create a memory leak + return self.values.view('i8') + + # ------------------------------------------------------------------ + # Null Handling + + @property # NB: override with cache_readonly in immutable subclasses + def _isnan(self): + """ return if each value is nan""" + return (self.asi8 == iNaT) + + @property # NB: override with cache_readonly in immutable subclasses + def hasnans(self): + """ return if I have any nans; enables various perf speedups """ + return self._isnan.any() + + def _maybe_mask_results(self, result, fill_value=None, convert=None): + """ + Parameters + ---------- + result : a ndarray + convert : string/dtype or None + + Returns + ------- + result : ndarray with values replace by the fill_value + + mask the result if needed, convert to the provided dtype if its not + None + + This is an internal routine + """ + + if self.hasnans: + if convert: + result = result.astype(convert) + if fill_value is None: + fill_value = np.nan + result[self._isnan] = fill_value + return result + + # ------------------------------------------------------------------ + # Frequency Properties/Methods + + @property + def freq(self): + """Return the frequency object if it is set, otherwise None""" + return self._freq + + @freq.setter + def freq(self, value): + if value is not None: + value = frequencies.to_offset(value) + self._validate_frequency(self, value) + + self._freq = value + + @property + def freqstr(self): + """ + Return the frequency object as a string if its set, otherwise None + """ + if self.freq is None: + return None + return self.freq.freqstr + + @property # NB: override with cache_readonly in immutable subclasses + def inferred_freq(self): + """ + Tryies to return a string representing a frequency guess, + generated by infer_freq. Returns None if it can't autodetect the + frequency. + """ + try: + return frequencies.infer_freq(self) + except ValueError: + return None + + # ------------------------------------------------------------------ + # Arithmetic Methods + + def _add_datelike(self, other): + raise TypeError("cannot add {cls} and {typ}" + .format(cls=type(self).__name__, + typ=type(other).__name__)) + + def _sub_datelike(self, other): + raise com.AbstractMethodError(self) + + def _sub_period(self, other): + return NotImplemented + + def _add_offset(self, offset): + raise com.AbstractMethodError(self) + + def _add_delta(self, other): + return NotImplemented + + def _add_delta_td(self, other): + """ + Add a delta of a timedeltalike + return the i8 result view + """ + inc = delta_to_nanoseconds(other) + new_values = checked_add_with_arr(self.asi8, inc, + arr_mask=self._isnan).view('i8') + if self.hasnans: + new_values[self._isnan] = iNaT + return new_values.view('i8') + + def _add_delta_tdi(self, other): + """ + Add a delta of a TimedeltaIndex + return the i8 result view + """ + if not len(self) == len(other): + raise ValueError("cannot add indices of unequal length") + + self_i8 = self.asi8 + other_i8 = other.asi8 + new_values = checked_add_with_arr(self_i8, other_i8, + arr_mask=self._isnan, + b_mask=other._isnan) + if self.hasnans or other.hasnans: + mask = (self._isnan) | (other._isnan) + new_values[mask] = iNaT + return new_values.view('i8') diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py new file mode 100644 index 0000000000000..fb51f3324c5ea --- /dev/null +++ b/pandas/core/arrays/datetimes.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +import warnings + +import numpy as np + +from pandas._libs.tslib import Timestamp, NaT, iNaT +from pandas._libs.tslibs import timezones + +from pandas.util._decorators import cache_readonly + +from pandas.core.dtypes.common import _NS_DTYPE, is_datetime64tz_dtype +from pandas.core.dtypes.dtypes import DatetimeTZDtype + +from .datetimelike import DatetimeLikeArrayMixin + + +class DatetimeArrayMixin(DatetimeLikeArrayMixin): + """ + Assumes that subclass __new__/__init__ defines: + tz + _freq + _data + """ + + # ----------------------------------------------------------------- + # Descriptive Properties + + @property + def _box_func(self): + return lambda x: Timestamp(x, freq=self.freq, tz=self.tz) + + @cache_readonly + def dtype(self): + if self.tz is None: + return _NS_DTYPE + return DatetimeTZDtype('ns', self.tz) + + @property + def tzinfo(self): + """ + Alias for tz attribute + """ + return self.tz + + @property # NB: override with cache_readonly in immutable subclasses + def _timezone(self): + """ Comparable timezone both for pytz / dateutil""" + return timezones.get_timezone(self.tzinfo) + + @property + def offset(self): + """get/set the frequency of the instance""" + msg = ('DatetimeIndex.offset has been deprecated and will be removed ' + 'in a future version; use DatetimeIndex.freq instead.') + warnings.warn(msg, FutureWarning, stacklevel=2) + return self.freq + + @offset.setter + def offset(self, value): + """get/set the frequency of the instance""" + msg = ('DatetimeIndex.offset has been deprecated and will be removed ' + 'in a future version; use DatetimeIndex.freq instead.') + warnings.warn(msg, FutureWarning, stacklevel=2) + self.freq = value + + # ----------------------------------------------------------------- + # Comparison Methods + + def _has_same_tz(self, other): + zzone = self._timezone + + # vzone sholdn't be None if value is non-datetime like + if isinstance(other, np.datetime64): + # convert to Timestamp as np.datetime64 doesn't have tz attr + other = Timestamp(other) + vzone = timezones.get_timezone(getattr(other, 'tzinfo', '__no_tz__')) + return zzone == vzone + + def _assert_tzawareness_compat(self, other): + # adapted from _Timestamp._assert_tzawareness_compat + other_tz = getattr(other, 'tzinfo', None) + if is_datetime64tz_dtype(other): + # Get tzinfo from Series dtype + other_tz = other.dtype.tz + if other is NaT: + # pd.NaT quacks both aware and naive + pass + elif self.tz is None: + if other_tz is not None: + raise TypeError('Cannot compare tz-naive and tz-aware ' + 'datetime-like objects.') + elif other_tz is None: + raise TypeError('Cannot compare tz-naive and tz-aware ' + 'datetime-like objects') + + # ----------------------------------------------------------------- + # Arithmetic Methods + + def _sub_datelike_dti(self, other): + """subtraction of two DatetimeIndexes""" + if not len(self) == len(other): + raise ValueError("cannot add indices of unequal length") + + self_i8 = self.asi8 + other_i8 = other.asi8 + new_values = self_i8 - other_i8 + if self.hasnans or other.hasnans: + mask = (self._isnan) | (other._isnan) + new_values[mask] = iNaT + return new_values.view('timedelta64[ns]') diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py new file mode 100644 index 0000000000000..1158bae748f0a --- /dev/null +++ b/pandas/core/arrays/period.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- + +from pandas._libs.tslibs.period import Period + +from pandas.util._decorators import cache_readonly + +from pandas.core.dtypes.dtypes import PeriodDtype + +from .datetimelike import DatetimeLikeArrayMixin + + +class PeriodArrayMixin(DatetimeLikeArrayMixin): + @property + def _box_func(self): + return lambda x: Period._from_ordinal(ordinal=x, freq=self.freq) + + @cache_readonly + def dtype(self): + return PeriodDtype.construct_from_string(self.freq) + + @property + def _ndarray_values(self): + # Ordinals + return self._data + + @property + def asi8(self): + return self._ndarray_values.view('i8') diff --git a/pandas/core/arrays/timedelta.py b/pandas/core/arrays/timedelta.py new file mode 100644 index 0000000000000..487858c49b66a --- /dev/null +++ b/pandas/core/arrays/timedelta.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- + +from pandas._libs.tslib import Timedelta + +from pandas.core.dtypes.common import _TD_DTYPE + +from .datetimelike import DatetimeLikeArrayMixin + + +class TimedeltaArrayMixin(DatetimeLikeArrayMixin): + @property + def _box_func(self): + return lambda x: Timedelta(x, unit='ns') + + @property + def dtype(self): + return _TD_DTYPE diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 5afa99d7b6fe8..328c51aae1807 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -15,7 +15,6 @@ from pandas._libs import lib, iNaT, NaT, Timedelta from pandas._libs.tslibs.period import (Period, IncompatibleFrequency, _DIFFERENT_FREQ_INDEX) -from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds from pandas._libs.tslibs.timestamps import round_ns from pandas.core.dtypes.common import ( @@ -46,6 +45,7 @@ from pandas.errors import NullFrequencyError, PerformanceWarning import pandas.io.formats.printing as printing +from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin from pandas.core.indexes.base import Index, _index_shared_docs from pandas.util._decorators import Appender, cache_readonly import pandas.core.dtypes.concat as _concat @@ -231,23 +231,17 @@ def _validate_frequency(cls, index, freq, **kwargs): 'conform to passed frequency {passed}') raise ValueError(msg.format(infer=inferred, passed=freq.freqstr)) - @property - def freq(self): - """Return the frequency object if it is set, otherwise None""" - return self._freq - - @freq.setter - def freq(self, value): - if value is not None: - value = frequencies.to_offset(value) - self._validate_frequency(self, value) - - self._freq = value - -class DatetimeIndexOpsMixin(object): +class DatetimeIndexOpsMixin(DatetimeLikeArrayMixin): """ common ops mixin to support a unified interface datetimelike Index """ + # DatetimeLikeArrayMixin assumes subclasses are mutable, so these are + # properties there. They can be made into cache_readonly for Index + # subclasses bc they are immutable + inferred_freq = cache_readonly(DatetimeLikeArrayMixin.inferred_freq.fget) + _isnan = cache_readonly(DatetimeLikeArrayMixin._isnan.fget) + hasnans = cache_readonly(DatetimeLikeArrayMixin.hasnans.fget) + def equals(self, other): """ Determines if two Index objects contain the same elements. @@ -276,9 +270,6 @@ def equals(self, other): return np.array_equal(self.asi8, other.asi8) - def __iter__(self): - return (self._box_func(v) for v in self.asi8) - @staticmethod def _join_i8_wrapper(joinf, dtype, with_indexers=True): """ create the join wrapper methods """ @@ -354,13 +345,6 @@ def _ensure_localized(self, result): result = result.tz_localize(self.tz) return result - @property - def _box_func(self): - """ - box function to get object from internal representation - """ - raise com.AbstractMethodError(self) - def _box_values(self, values): """ apply box func to passed values @@ -437,27 +421,6 @@ def __getitem__(self, key): return self._simple_new(result, **attribs) - @property - def freqstr(self): - """ - Return the frequency object as a string if it is set, otherwise None - """ - if self.freq is None: - return None - return self.freq.freqstr - - @cache_readonly - def inferred_freq(self): - """ - Tries to return a string representing a frequency guess, - generated by infer_freq. Returns None if it can't autodetect the - frequency. - """ - try: - return frequencies.infer_freq(self) - except ValueError: - return None - def _nat_new(self, box=True): """ Return Index or ndarray filled with NaT which has the same @@ -546,11 +509,6 @@ def take(self, indices, axis=0, allow_fill=True, _na_value = NaT """The expected NA value to use with this index.""" - @cache_readonly - def _isnan(self): - """ return if each value is nan""" - return (self.asi8 == iNaT) - @property def asobject(self): """Return object Index which contains boxed values. @@ -571,31 +529,6 @@ def _convert_tolerance(self, tolerance, target): 'target index size') return tolerance - def _maybe_mask_results(self, result, fill_value=None, convert=None): - """ - Parameters - ---------- - result : a ndarray - convert : string/dtype or None - - Returns - ------- - result : ndarray with values replace by the fill_value - - mask the result if needed, convert to the provided dtype if its not - None - - This is an internal routine - """ - - if self.hasnans: - if convert: - result = result.astype(convert) - if fill_value is None: - fill_value = np.nan - result[self._isnan] = fill_value - return result - def tolist(self): """ return a list of the underlying data @@ -752,14 +685,6 @@ def _convert_scalar_indexer(self, key, kind=None): return (super(DatetimeIndexOpsMixin, self) ._convert_scalar_indexer(key, kind=kind)) - def _add_datelike(self, other): - raise TypeError("cannot add {cls} and {typ}" - .format(cls=type(self).__name__, - typ=type(other).__name__)) - - def _sub_datelike(self, other): - raise com.AbstractMethodError(self) - def _add_nat(self): """Add pd.NaT to self""" if is_period_dtype(self): @@ -1048,42 +973,6 @@ def __isub__(self, other): return self.__sub__(other) cls.__isub__ = __isub__ - def _add_delta(self, other): - return NotImplemented - - def _add_delta_td(self, other): - """ - Add a delta of a timedeltalike - return the i8 result view - """ - - inc = delta_to_nanoseconds(other) - new_values = checked_add_with_arr(self.asi8, inc, - arr_mask=self._isnan).view('i8') - if self.hasnans: - new_values[self._isnan] = iNaT - return new_values.view('i8') - - def _add_delta_tdi(self, other): - """ - Add a delta of a TimedeltaIndex - return the i8 result view - """ - - # delta operation - if not len(self) == len(other): - raise ValueError("cannot add indices of unequal length") - - self_i8 = self.asi8 - other_i8 = other.asi8 - new_values = checked_add_with_arr(self_i8, other_i8, - arr_mask=self._isnan, - b_mask=other._isnan) - if self.hasnans or other.hasnans: - mask = (self._isnan) | (other._isnan) - new_values[mask] = iNaT - return new_values.view('i8') - def isin(self, values): """ Compute boolean array of whether each index value is found in the diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 9515d41080f87..7475998909ec2 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -13,7 +13,7 @@ _INT64_DTYPE, _NS_DTYPE, is_object_dtype, - is_datetime64_dtype, is_datetime64tz_dtype, + is_datetime64_dtype, is_datetimetz, is_dtype_equal, is_timedelta64_dtype, @@ -35,6 +35,7 @@ import pandas.core.dtypes.concat as _concat from pandas.errors import PerformanceWarning from pandas.core.algorithms import checked_add_with_arr +from pandas.core.arrays.datetimes import DatetimeArrayMixin from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.numeric import Int64Index, Float64Index @@ -173,8 +174,8 @@ def _new_DatetimeIndex(cls, d): return result -class DatetimeIndex(DatelikeOps, TimelikeOps, DatetimeIndexOpsMixin, - Int64Index): +class DatetimeIndex(DatetimeArrayMixin, DatelikeOps, TimelikeOps, + DatetimeIndexOpsMixin, Int64Index): """ Immutable ndarray of datetime64 data, represented internally as int64, and which can be boxed to Timestamp objects that are subclasses of datetime and @@ -329,6 +330,7 @@ def _add_comparison_methods(cls): _is_numeric_dtype = False _infer_as_myclass = True + _timezone = cache_readonly(DatetimeArrayMixin._timezone.fget) def __new__(cls, data=None, freq=None, start=None, end=None, periods=None, tz=None, @@ -591,10 +593,6 @@ def _generate(cls, start, end, periods, name, freq, index = cls._simple_new(index, name=name, freq=freq, tz=tz) return index - @property - def _box_func(self): - return lambda x: Timestamp(x, freq=self.freq, tz=self.tz) - def _convert_for_op(self, value): """ Convert value to be insertable to ndarray """ if self._has_same_tz(value): @@ -645,23 +643,6 @@ def _simple_new(cls, values, name=None, freq=None, tz=None, result._reset_identity() return result - def _assert_tzawareness_compat(self, other): - # adapted from _Timestamp._assert_tzawareness_compat - other_tz = getattr(other, 'tzinfo', None) - if is_datetime64tz_dtype(other): - # Get tzinfo from Series dtype - other_tz = other.dtype.tz - if other is libts.NaT: - # pd.NaT quacks both aware and naive - pass - elif self.tz is None: - if other_tz is not None: - raise TypeError('Cannot compare tz-naive and tz-aware ' - 'datetime-like objects.') - elif other_tz is None: - raise TypeError('Cannot compare tz-naive and tz-aware ' - 'datetime-like objects') - @property def _values(self): # tz-naive -> ndarray @@ -682,13 +663,6 @@ def tz(self, value): raise AttributeError("Cannot directly set timezone. Use tz_localize() " "or tz_convert() as appropriate") - @property - def tzinfo(self): - """ - Alias for tz attribute - """ - return self.tz - @property def size(self): # TODO: Remove this when we have a DatetimeTZArray @@ -710,21 +684,6 @@ def nbytes(self): # for TZ-aware return self._ndarray_values.nbytes - @cache_readonly - def _timezone(self): - """ Comparable timezone both for pytz / dateutil""" - return timezones.get_timezone(self.tzinfo) - - def _has_same_tz(self, other): - zzone = self._timezone - - # vzone sholdn't be None if value is non-datetime like - if isinstance(other, np.datetime64): - # convert to Timestamp as np.datetime64 doesn't have tz attr - other = Timestamp(other) - vzone = timezones.get_timezone(getattr(other, 'tzinfo', '__no_tz__')) - return zzone == vzone - @classmethod def _cached_range(cls, start=None, end=None, periods=None, freq=None, name=None): @@ -880,19 +839,6 @@ def _sub_datelike(self, other): typ=type(other).__name__)) return result.view('timedelta64[ns]') - def _sub_datelike_dti(self, other): - """subtraction of two DatetimeIndexes""" - if not len(self) == len(other): - raise ValueError("cannot add indices of unequal length") - - self_i8 = self.asi8 - other_i8 = other.asi8 - new_values = self_i8 - other_i8 - if self.hasnans or other.hasnans: - mask = (self._isnan) | (other._isnan) - new_values[mask] = libts.iNaT - return new_values.view('timedelta64[ns]') - def _maybe_update_attributes(self, attrs): """ Update Index attributes (e.g. freq) depending on op """ freq = attrs.get('freq', None) @@ -1720,22 +1666,6 @@ def slice_indexer(self, start=None, end=None, step=None, kind=None): else: raise - @property - def offset(self): - """get/set the frequency of the Index""" - msg = ('DatetimeIndex.offset has been deprecated and will be removed ' - 'in a future version; use DatetimeIndex.freq instead.') - warnings.warn(msg, FutureWarning, stacklevel=2) - return self.freq - - @offset.setter - def offset(self, value): - """get/set the frequency of the Index""" - msg = ('DatetimeIndex.offset has been deprecated and will be removed ' - 'in a future version; use DatetimeIndex.freq instead.') - warnings.warn(msg, FutureWarning, stacklevel=2) - self.freq = value - year = _field_accessor('year', 'Y', "The year of the datetime") month = _field_accessor('month', 'M', "The month as January=1, December=12") @@ -2114,12 +2044,6 @@ def inferred_type(self): # sure we can't have ambiguous indexing return 'datetime64' - @cache_readonly - def dtype(self): - if self.tz is None: - return _NS_DTYPE - return DatetimeTZDtype('ns', self.tz) - @property def is_all_dates(self): return True diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index d4d35d48743bd..1257266025c03 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -16,7 +16,6 @@ is_bool_dtype, pandas_dtype, _ensure_object) -from pandas.core.dtypes.dtypes import PeriodDtype from pandas.core.dtypes.generic import ABCSeries import pandas.tseries.frequencies as frequencies @@ -36,6 +35,7 @@ from pandas._libs.tslibs import resolution, period from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds +from pandas.core.arrays.period import PeriodArrayMixin from pandas.core.base import _shared_docs from pandas.core.indexes.base import _index_shared_docs, _ensure_index @@ -122,7 +122,8 @@ def _new_PeriodIndex(cls, **d): return cls._from_ordinals(values=values, **d) -class PeriodIndex(DatelikeOps, DatetimeIndexOpsMixin, Int64Index): +class PeriodIndex(PeriodArrayMixin, DatelikeOps, DatetimeIndexOpsMixin, + Int64Index): """ Immutable ndarray holding ordinal values indicating regular periods in time such as particular years, quarters, months, etc. @@ -410,10 +411,6 @@ def __contains__(self, key): contains = __contains__ - @property - def asi8(self): - return self._ndarray_values.view('i8') - @cache_readonly def _int64index(self): return Int64Index(self.asi8, name=self.name, fastpath=True) @@ -422,11 +419,6 @@ def _int64index(self): def values(self): return self.astype(object).values - @property - def _ndarray_values(self): - # Ordinals - return self._data - def __array__(self, dtype=None): if is_integer_dtype(dtype): return self.asi8 @@ -467,10 +459,6 @@ def __array_wrap__(self, result, context=None): # cannot pass _simple_new as it is return self._shallow_copy(result, freq=self.freq, name=self.name) - @property - def _box_func(self): - return lambda x: Period._from_ordinal(ordinal=x, freq=self.freq) - def _to_embed(self, keep_tz=False, dtype=None): """ return an array repr of this object, potentially casting to object @@ -795,10 +783,6 @@ def shift(self, n): values[self._isnan] = tslib.iNaT return self._shallow_copy(values=values) - @cache_readonly - def dtype(self): - return PeriodDtype.construct_from_string(self.freq) - @property def inferred_type(self): # b/c data is represented as ints make sure we can't have ambiguous diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index e90e1264638b0..8b62d9aa631e9 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -17,6 +17,7 @@ from pandas.core.dtypes.missing import isna from pandas.core.dtypes.generic import ABCSeries +from pandas.core.arrays.timedelta import TimedeltaArrayMixin from pandas.core.indexes.base import Index from pandas.core.indexes.numeric import Int64Index import pandas.compat as compat @@ -96,7 +97,8 @@ def wrapper(self, other): return compat.set_function_name(wrapper, opname, cls) -class TimedeltaIndex(DatetimeIndexOpsMixin, TimelikeOps, Int64Index): +class TimedeltaIndex(TimedeltaArrayMixin, DatetimeIndexOpsMixin, + TimelikeOps, Int64Index): """ Immutable ndarray of timedelta64 data, represented internally as int64, and which can be boxed to timedelta objects @@ -311,10 +313,6 @@ def _generate(cls, start, end, periods, name, freq, closed=None): return index - @property - def _box_func(self): - return lambda x: Timedelta(x, unit='ns') - @classmethod def _simple_new(cls, values, name=None, freq=None, **kwargs): values = np.array(values, copy=False) @@ -906,10 +904,6 @@ def is_type_compatible(self, typ): def inferred_type(self): return 'timedelta64' - @property - def dtype(self): - return _TD_DTYPE - @property def is_all_dates(self): return True
The medium-term goal: refactor out of `DatetimeIndexOpsMixin`/`DatetimeIndex`/`TimedeltaIndex`/`PeriodIndex` the bare minimum subset of functionality to implement arithmetic+comparisons for `DatetimeArray`/`TimedeltaArray`/`PeriodArray`. This PR does _not_ do that. What it _does_ do is refactor out the subset of those methods that can be transplanted directly into the Array classes (i.e. cut/paste). On its own this PR is not very useful, so think of it as a Proof of Concept/discussion piece. cc @TomAugspurger since this is a precursor to getting a "real" PeriodArray.
https://api.github.com/repos/pandas-dev/pandas/pulls/19902
2018-02-26T05:26:43Z
2018-07-02T23:58:48Z
2018-07-02T23:58:48Z
2018-07-02T23:59:52Z
DOC: small typo fix
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 852ad04cd8a2e..00643614e8803 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -1440,7 +1440,7 @@ def resample(self, rule, *args, **kwargs): def rolling(self, *args, **kwargs): """ Return a rolling grouper, providing rolling - functionaility per group + functionality per group """ from pandas.core.window import RollingGroupby @@ -1451,7 +1451,7 @@ def rolling(self, *args, **kwargs): def expanding(self, *args, **kwargs): """ Return an expanding grouper, providing expanding - functionaility per group + functionality per group """ from pandas.core.window import ExpandingGroupby
"functionaility" -> "functionality" - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/19901
2018-02-26T03:07:45Z
2018-02-26T10:34:59Z
2018-02-26T10:34:59Z
2018-02-26T10:35:04Z
DOC: fix numpydoc section titles in misc plotting docstrings
diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index d6048f54993e6..45594e9c6ea95 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -149,8 +149,8 @@ def _get_marker_compat(marker): def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds): """RadViz - a multivariate data visualization algorithm - Parameters: - ----------- + Parameters + ---------- frame: DataFrame class_column: str Column name containing class names @@ -163,8 +163,8 @@ def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds): kwds: keywords Options to pass to matplotlib scatter plotting method - Returns: - -------- + Returns + ------- ax: Matplotlib axis object """ import matplotlib.pyplot as plt @@ -247,8 +247,8 @@ def andrews_curves(frame, class_column, ax=None, samples=200, color=None, linearly spaced between -pi and +pi. Each row of frame then corresponds to a single curve. - Parameters: - ----------- + Parameters + ---------- frame : DataFrame Data to be plotted, preferably normalized to (0.0, 1.0) class_column : Name of the column containing class names @@ -262,8 +262,8 @@ def andrews_curves(frame, class_column, ax=None, samples=200, color=None, kwds: keywords Options to pass to matplotlib plotting method - Returns: - -------- + Returns + ------- ax: Matplotlib axis object """ @@ -325,8 +325,8 @@ def f(t): def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds): """Bootstrap plot. - Parameters: - ----------- + Parameters + ---------- series: Time series fig: matplotlib figure object, optional size: number of data points to consider during each sampling @@ -334,8 +334,8 @@ def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds): kwds: optional keyword arguments for plotting commands, must be accepted by both hist and plot - Returns: - -------- + Returns + ------- fig: matplotlib figure """ import random @@ -503,15 +503,15 @@ def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None, def lag_plot(series, lag=1, ax=None, **kwds): """Lag plot for time series. - Parameters: - ----------- + Parameters + ---------- series: Time series lag: lag of the scatter plot, default 1 ax: Matplotlib axis object, optional kwds: Matplotlib scatter method keyword arguments, optional - Returns: - -------- + Returns + ------- ax: Matplotlib axis object """ import matplotlib.pyplot as plt
https://api.github.com/repos/pandas-dev/pandas/pulls/19899
2018-02-25T22:44:21Z
2018-02-26T08:48:11Z
2018-02-26T08:48:11Z
2018-02-26T08:48:14Z
DOC: Adding script to validate docstrings, and generate list of all functions/methods with state
diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py new file mode 100755 index 0000000000000..7807785c24751 --- /dev/null +++ b/scripts/validate_docstrings.py @@ -0,0 +1,355 @@ +#!/usr/bin/env python +""" +Analyze docstrings to detect errors. + +If no argument is provided, it does a quick check of docstrings and returns +a csv with all API functions and results of basic checks. + +If a function or method is provided in the form "pandas.function", +"pandas.module.class.method", etc. a list of all errors in the docstring for +the specified function or method. + +Usage:: + $ ./validate_docstrings.py + $ ./validate_docstrings.py pandas.DataFrame.head +""" +import os +import sys +import csv +import re +import functools +import argparse +import contextlib +import inspect +import importlib +import doctest +import textwrap +try: + from io import StringIO +except ImportError: + from cStringIO import StringIO +import numpy + +BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +sys.path.insert(0, os.path.join(BASE_PATH)) +import pandas + +sys.path.insert(1, os.path.join(BASE_PATH, 'doc', 'sphinxext')) +from numpydoc.docscrape import NumpyDocString + + +def _to_original_callable(obj): + while True: + if inspect.isfunction(obj) or inspect.isclass(obj): + f = inspect.getfile(obj) + if f.startswith('<') and f.endswith('>'): + return None + return obj + if inspect.ismethod(obj): + obj = obj.__func__ + elif isinstance(obj, functools.partial): + obj = obj.func + elif isinstance(obj, property): + obj = obj.fget + else: + return None + + +def _output_header(title, width=80, char='#'): + full_line = char * width + side_len = (width - len(title) - 2) // 2 + adj = '' if len(title) % 2 == 0 else ' ' + title_line = '{side} {title}{adj} {side}'.format(side=char * side_len, + title=title, + adj=adj) + + return '\n{full_line}\n{title_line}\n{full_line}\n\n'.format( + full_line=full_line, title_line=title_line) + + +class Docstring: + def __init__(self, method_name, method_obj): + self.method_name = method_name + self.method_obj = method_obj + self.raw_doc = method_obj.__doc__ or '' + self.raw_doc = textwrap.dedent(self.raw_doc) + self.doc = NumpyDocString(self.raw_doc) + + def __len__(self): + return len(self.raw_doc) + + @property + def source_file_name(self): + fname = inspect.getsourcefile(self.method_obj) + if fname: + fname = os.path.relpath(fname, BASE_PATH) + return fname + + @property + def source_file_def_line(self): + try: + return inspect.getsourcelines(self.method_obj)[-1] + except OSError: + pass + + @property + def github_url(self): + url = 'https://github.com/pandas-dev/pandas/blob/master/' + url += '{}#L{}'.format(self.source_file_name, + self.source_file_def_line) + return url + + @property + def first_line_blank(self): + if self.raw_doc: + return not bool(self.raw_doc.split('\n')[0].strip()) + + @property + def summary(self): + if not self.doc['Extended Summary'] and len(self.doc['Summary']) > 1: + return '' + return ' '.join(self.doc['Summary']) + + @property + def extended_summary(self): + if not self.doc['Extended Summary'] and len(self.doc['Summary']) > 1: + return ' '.join(self.doc['Summary']) + return ' '.join(self.doc['Extended Summary']) + + @property + def needs_summary(self): + return not (bool(self.summary) and bool(self.extended_summary)) + + @property + def doc_parameters(self): + return self.doc['Parameters'] + + @property + def signature_parameters(self): + if not inspect.isfunction(self.method_obj): + return tuple() + params = tuple(inspect.signature(self.method_obj).parameters.keys()) + if params and params[0] in ('self', 'cls'): + return params[1:] + return params + + @property + def parameter_mismatches(self): + errs = [] + signature_params = self.signature_parameters + if self.doc_parameters: + doc_params = list(zip(*self.doc_parameters))[0] + else: + doc_params = [] + + missing = set(signature_params) - set(doc_params) + if missing: + errs.append('Parameters {!r} not documented'.format(missing)) + extra = set(doc_params) - set(signature_params) + if extra: + errs.append('Unknown parameters {!r}'.format(extra)) + if not missing and not extra and signature_params != doc_params: + errs.append('Wrong parameters order. ' + + 'Actual: {!r}. '.format(signature_params) + + 'Documented: {!r}'.format(doc_params)) + + return errs + + @property + def correct_parameters(self): + return not bool(self.parameter_mismatches) + + @property + def see_also(self): + return self.doc['See Also'] + + @property + def examples(self): + return self.doc['Examples'] + + @property + def first_line_ends_in_dot(self): + if self.doc: + return self.doc.split('\n')[0][-1] == '.' + + @property + def deprecated(self): + pattern = re.compile('.. deprecated:: ') + return (self.method_name.startswith('pandas.Panel') or + bool(pattern.search(self.summary)) or + bool(pattern.search(self.extended_summary))) + + @property + def examples_errors(self): + flags = doctest.NORMALIZE_WHITESPACE | doctest.IGNORE_EXCEPTION_DETAIL + finder = doctest.DocTestFinder() + runner = doctest.DocTestRunner(optionflags=flags) + context = {'np': numpy, 'pd': pandas} + error_msgs = '' + for test in finder.find(self.raw_doc, self.method_name, globs=context): + f = StringIO() + with contextlib.redirect_stdout(f): + runner.run(test) + error_msgs += f.getvalue() + return error_msgs + + +def get_api_items(): + api_fname = os.path.join(BASE_PATH, 'doc', 'source', 'api.rst') + + position = None + with open(api_fname) as f: + for line in f: + if line.startswith('.. currentmodule::'): + current_module = line.replace('.. currentmodule::', '').strip() + continue + + if line == '.. autosummary::\n': + position = 'autosummary' + continue + + if position == 'autosummary': + if line == '\n': + position = 'items' + continue + + if position == 'items': + if line == '\n': + position = None + continue + item = line.strip() + func = importlib.import_module(current_module) + for part in item.split('.'): + func = getattr(func, part) + + yield '.'.join([current_module, item]), func + + +def validate_all(): + writer = csv.writer(sys.stdout) + writer.writerow(['Function or method', + 'Type', + 'File', + 'Code line', + 'GitHub link', + 'Is deprecated', + 'Has summary', + 'Has extended summary', + 'Parameters ok', + 'Has examples', + 'Shared code with']) + seen = {} + for func_name, func in get_api_items(): + obj_type = type(func).__name__ + original_callable = _to_original_callable(func) + if original_callable is None: + writer.writerow([func_name, obj_type] + [''] * 9) + else: + doc = Docstring(func_name, original_callable) + key = doc.source_file_name, doc.source_file_def_line + shared_code = seen.get(key, '') + seen[key] = func_name + writer.writerow([func_name, + obj_type, + doc.source_file_name, + doc.source_file_def_line, + doc.github_url, + int(doc.deprecated), + int(bool(doc.summary)), + int(bool(doc.extended_summary)), + int(doc.correct_parameters), + int(bool(doc.examples)), + shared_code]) + + return 0 + + +def validate_one(func_name): + for maxsplit in range(1, func_name.count('.') + 1): + # TODO when py3 only replace by: module, *func_parts = ... + func_name_split = func_name.rsplit('.', maxsplit=maxsplit) + module = func_name_split[0] + func_parts = func_name_split[1:] + try: + func_obj = importlib.import_module(module) + except ImportError: + pass + else: + continue + + if 'module' not in locals(): + raise ImportError('No module can be imported ' + 'from "{}"'.format(func_name)) + + for part in func_parts: + func_obj = getattr(func_obj, part) + + doc = Docstring(func_name, func_obj) + + sys.stderr.write(_output_header('Docstring ({})'.format(func_name))) + sys.stderr.write('{}\n'.format(doc.raw_doc)) + + errs = [] + if not doc.summary: + errs.append('No summary found') + else: + if not doc.summary[0].isupper(): + errs.append('Summary does not start with capital') + if doc.summary[-1] != '.': + errs.append('Summary does not end with dot') + if doc.summary.split(' ')[0][-1] == 's': + errs.append('Summary must start with infinitive verb, ' + 'not third person (e.g. use "Generate" instead of ' + '"Generates")') + if not doc.extended_summary: + errs.append('No extended summary found') + + param_errs = doc.parameter_mismatches + if param_errs: + errs.append('Errors in parameters section') + for param_err in param_errs: + errs.append('\t{}'.format(param_err)) + + examples_errs = '' + if not doc.examples: + errs.append('No examples section found') + else: + examples_errs = doc.examples_errors + if examples_errs: + errs.append('Examples do not pass tests') + + sys.stderr.write(_output_header('Validation')) + if errs: + sys.stderr.write('Errors found:\n') + for err in errs: + sys.stderr.write('\t{}\n'.format(err)) + else: + sys.stderr.write('Docstring for "{}" correct. :)\n'.format(func_name)) + + if examples_errs: + sys.stderr.write(_output_header('Doctests')) + sys.stderr.write(examples_errs) + + return len(errs) + + +def main(function): + if function is None: + return validate_all() + else: + return validate_one(function) + + +if __name__ == '__main__': + argparser = argparse.ArgumentParser( + description='validate pandas docstrings') + argparser.add_argument('function', + nargs='?', + default=None, + help=('function or method to validate ' + '(e.g. pandas.DataFrame.head) ' + 'if not provided, all docstrings ' + 'are validated')) + args = argparser.parse_args() + sys.exit(main(args.function))
- [ ] closes #xxxx - [ ] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Adding a new script to check whether a docstring follows the defined standards or not. Also, without arguments, the script returns a report of all the functions and methods in the API, with information about its docstring. CC @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/19898
2018-02-25T21:37:27Z
2018-03-02T09:39:46Z
2018-03-02T09:39:46Z
2018-03-02T09:40:02Z
parameterize test_pct_change_periods_freq
diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index 9f94439a71a57..e1bc310e1e934 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -122,36 +122,31 @@ def test_pct_change_shift_over_nas(self): edf = DataFrame({'a': expected, 'b': expected}) assert_frame_equal(chg, edf) - def test_pct_change_periods_freq(self): + @pytest.mark.parametrize("freq, periods, fill_method, limit", + [('5B', 5, None, None), + ('3B', 3, None, None), + ('3B', 3, 'bfill', None), + ('7B', 7, 'pad', 1), + ('7B', 7, 'bfill', 3), + ('14B', 14, None, None)]) + def test_pct_change_periods_freq(self, freq, periods, fill_method, limit): # GH 7292 - rs_freq = self.tsframe.pct_change(freq='5B') - rs_periods = self.tsframe.pct_change(5) - assert_frame_equal(rs_freq, rs_periods) - - rs_freq = self.tsframe.pct_change(freq='3B', fill_method=None) - rs_periods = self.tsframe.pct_change(3, fill_method=None) - assert_frame_equal(rs_freq, rs_periods) - - rs_freq = self.tsframe.pct_change(freq='3B', fill_method='bfill') - rs_periods = self.tsframe.pct_change(3, fill_method='bfill') - assert_frame_equal(rs_freq, rs_periods) - - rs_freq = self.tsframe.pct_change(freq='7B', - fill_method='pad', - limit=1) - rs_periods = self.tsframe.pct_change(7, fill_method='pad', limit=1) - assert_frame_equal(rs_freq, rs_periods) - - rs_freq = self.tsframe.pct_change(freq='7B', - fill_method='bfill', - limit=3) - rs_periods = self.tsframe.pct_change(7, fill_method='bfill', limit=3) + rs_freq = self.tsframe.pct_change(freq=freq, + fill_method=fill_method, + limit=limit) + rs_periods = self.tsframe.pct_change(periods, + fill_method=fill_method, + limit=limit) assert_frame_equal(rs_freq, rs_periods) empty_ts = DataFrame(index=self.tsframe.index, columns=self.tsframe.columns) - rs_freq = empty_ts.pct_change(freq='14B') - rs_periods = empty_ts.pct_change(14) + rs_freq = empty_ts.pct_change(freq=freq, + fill_method=fill_method, + limit=limit) + rs_periods = empty_ts.pct_change(periods, + fill_method=fill_method, + limit=limit) assert_frame_equal(rs_freq, rs_periods) def test_frame_ctor_datetime64_column(self): diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 63a05ef7de565..baf2619c7b022 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -355,31 +355,30 @@ def test_pct_change_shift_over_nas(self): expected = Series([np.nan, 0.5, 0., 2.5 / 1.5 - 1, .2]) assert_series_equal(chg, expected) - def test_pct_change_periods_freq(self): + @pytest.mark.parametrize("freq, periods, fill_method, limit", + [('5B', 5, None, None), + ('3B', 3, None, None), + ('3B', 3, 'bfill', None), + ('7B', 7, 'pad', 1), + ('7B', 7, 'bfill', 3), + ('14B', 14, None, None)]) + def test_pct_change_periods_freq(self, freq, periods, fill_method, limit): # GH 7292 - rs_freq = self.ts.pct_change(freq='5B') - rs_periods = self.ts.pct_change(5) - assert_series_equal(rs_freq, rs_periods) - - rs_freq = self.ts.pct_change(freq='3B', fill_method=None) - rs_periods = self.ts.pct_change(3, fill_method=None) - assert_series_equal(rs_freq, rs_periods) - - rs_freq = self.ts.pct_change(freq='3B', fill_method='bfill') - rs_periods = self.ts.pct_change(3, fill_method='bfill') - assert_series_equal(rs_freq, rs_periods) - - rs_freq = self.ts.pct_change(freq='7B', fill_method='pad', limit=1) - rs_periods = self.ts.pct_change(7, fill_method='pad', limit=1) - assert_series_equal(rs_freq, rs_periods) - - rs_freq = self.ts.pct_change(freq='7B', fill_method='bfill', limit=3) - rs_periods = self.ts.pct_change(7, fill_method='bfill', limit=3) + rs_freq = self.ts.pct_change(freq=freq, + fill_method=fill_method, + limit=limit) + rs_periods = self.ts.pct_change(periods, + fill_method=fill_method, + limit=limit) assert_series_equal(rs_freq, rs_periods) empty_ts = Series(index=self.ts.index) - rs_freq = empty_ts.pct_change(freq='14B') - rs_periods = empty_ts.pct_change(14) + rs_freq = empty_ts.pct_change(freq=freq, + fill_method=fill_method, + limit=limit) + rs_periods = empty_ts.pct_change(periods, + fill_method=fill_method, + limit=limit) assert_series_equal(rs_freq, rs_periods) def test_autocorr(self):
- [x] closes https://github.com/pandas-dev/pandas/pull/19410 - [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/19897
2018-02-25T21:18:36Z
2018-02-25T23:06:26Z
2018-02-25T23:06:26Z
2018-02-25T23:12:18Z
cleanup order of operations kludges
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 99a3773603fc4..72487faf933c7 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -586,6 +586,7 @@ Datetimelike API Changes - Operations between a :class:`Series` with dtype ``dtype='datetime64[ns]'`` and a :class:`PeriodIndex` will correctly raises ``TypeError`` (:issue:`18850`) - Subtraction of :class:`Series` with timezone-aware ``dtype='datetime64[ns]'`` with mis-matched timezones will raise ``TypeError`` instead of ``ValueError`` (:issue:`18817`) - :func:`pandas.merge` provides a more informative error message when trying to merge on timezone-aware and timezone-naive columns (:issue:`15800`) +- For :class:`DatetimeIndex` and :class:`TimedeltaIndex` with ``freq=None``, addition or subtraction of integer-dtyped array or ``Index`` will raise ``NullFrequencyError`` instead of ``TypeError`` (:issue:`19895`) .. _whatsnew_0230.api.other: diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 9411428b2e68d..8e56fc2775a56 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -32,6 +32,7 @@ is_object_dtype, is_string_dtype, is_datetime64_dtype, + is_datetime64tz_dtype, is_period_dtype, is_timedelta64_dtype) from pandas.core.dtypes.generic import ( @@ -200,8 +201,9 @@ def _evaluate_compare(self, other, op): if is_bool_dtype(result): result[mask] = False return result + + result[mask] = iNaT try: - result[mask] = iNaT return Index(result) except TypeError: return result @@ -349,7 +351,7 @@ def _nat_new(self, box=True): return result attribs = self._get_attributes_dict() - if not isinstance(self, ABCPeriodIndex): + if not is_period_dtype(self): attribs['freq'] = None return self._simple_new(result, **attribs) @@ -631,9 +633,9 @@ def _convert_scalar_indexer(self, key, kind=None): ._convert_scalar_indexer(key, kind=kind)) def _add_datelike(self, other): - raise TypeError("cannot add {0} and {1}" - .format(type(self).__name__, - type(other).__name__)) + raise TypeError("cannot add {cls} and {typ}" + .format(cls=type(self).__name__, + typ=type(other).__name__)) def _sub_datelike(self, other): raise com.AbstractMethodError(self) @@ -677,7 +679,7 @@ def _add_datetimelike_methods(cls): """ def __add__(self, other): - from pandas import Index, DatetimeIndex, TimedeltaIndex, DateOffset + from pandas import DateOffset other = lib.item_from_zerodim(other) if isinstance(other, ABCSeries): @@ -700,18 +702,9 @@ def __add__(self, other): elif is_offsetlike(other): # Array/Index of DateOffset objects result = self._addsub_offset_array(other, operator.add) - elif isinstance(self, TimedeltaIndex) and isinstance(other, Index): - if hasattr(other, '_add_delta'): - # i.e. DatetimeIndex, TimedeltaIndex, or PeriodIndex - result = other._add_delta(self) - else: - raise TypeError("cannot add TimedeltaIndex and {typ}" - .format(typ=type(other))) - elif isinstance(other, Index): - result = self._add_datelike(other) - elif is_datetime64_dtype(other): - # ndarray[datetime64]; note DatetimeIndex is caught above - return self + DatetimeIndex(other) + elif is_datetime64_dtype(other) or is_datetime64tz_dtype(other): + # DatetimeIndex, ndarray[datetime64] + return self._add_datelike(other) elif is_integer_dtype(other) and self.freq is None: # GH#19123 raise NullFrequencyError("Cannot shift with no freq") @@ -731,7 +724,7 @@ def __radd__(self, other): cls.__radd__ = __radd__ def __sub__(self, other): - from pandas import Index, DatetimeIndex, TimedeltaIndex, DateOffset + from pandas import Index, DateOffset other = lib.item_from_zerodim(other) if isinstance(other, ABCSeries): @@ -756,20 +749,13 @@ def __sub__(self, other): elif is_offsetlike(other): # Array/Index of DateOffset objects result = self._addsub_offset_array(other, operator.sub) - elif isinstance(self, TimedeltaIndex) and isinstance(other, Index): - # We checked above for timedelta64_dtype(other) so this - # must be invalid. - raise TypeError("cannot subtract TimedeltaIndex and {typ}" - .format(typ=type(other).__name__)) - elif isinstance(other, DatetimeIndex): + elif is_datetime64_dtype(other) or is_datetime64tz_dtype(other): + # DatetimeIndex, ndarray[datetime64] result = self._sub_datelike(other) - elif is_datetime64_dtype(other): - # ndarray[datetime64]; note we caught DatetimeIndex earlier - return self - DatetimeIndex(other) elif isinstance(other, Index): - raise TypeError("cannot subtract {typ1} and {typ2}" - .format(typ1=type(self).__name__, - typ2=type(other).__name__)) + raise TypeError("cannot subtract {cls} and {typ}" + .format(cls=type(self).__name__, + typ=type(other).__name__)) elif is_integer_dtype(other) and self.freq is None: # GH#19123 raise NullFrequencyError("Cannot shift with no freq") diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 36ea2bffb9531..55d8b7c18a622 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -864,11 +864,16 @@ def _add_datelike(self, other): def _sub_datelike(self, other): # subtract a datetime from myself, yielding a TimedeltaIndex from pandas import TimedeltaIndex - if isinstance(other, DatetimeIndex): + + if isinstance(other, (DatetimeIndex, np.ndarray)): + # if other is an ndarray, we assume it is datetime64-dtype + other = DatetimeIndex(other) + # require tz compat if not self._has_same_tz(other): - raise TypeError("DatetimeIndex subtraction must have the same " - "timezones or no timezones") + raise TypeError("{cls} subtraction must have the same " + "timezones or no timezones" + .format(cls=type(self).__name__)) result = self._sub_datelike_dti(other) elif isinstance(other, (datetime, np.datetime64)): other = Timestamp(other) @@ -885,8 +890,9 @@ def _sub_datelike(self, other): result = self._maybe_mask_results(result, fill_value=libts.iNaT) else: - raise TypeError("cannot subtract DatetimeIndex and {typ}" - .format(typ=type(other).__name__)) + raise TypeError("cannot subtract {cls} and {typ}" + .format(cls=type(self).__name__, + typ=type(other).__name__)) return TimedeltaIndex(result) def _sub_datelike_dti(self, other): diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 6f80962eab079..eebd52d7fb801 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -59,30 +59,28 @@ def _td_index_cmp(opname, cls): nat_result = True if opname == '__ne__' else False def wrapper(self, other): - msg = "cannot compare a TimedeltaIndex with type {0}" + msg = "cannot compare a {cls} with type {typ}" func = getattr(super(TimedeltaIndex, self), opname) if _is_convertible_to_td(other) or other is NaT: try: other = _to_m8(other) except ValueError: # failed to parse as timedelta - raise TypeError(msg.format(type(other))) + raise TypeError(msg.format(cls=type(self).__name__, + typ=type(other).__name__)) result = func(other) if isna(other): result.fill(nat_result) - else: - if not is_list_like(other): - raise TypeError(msg.format(type(other))) + elif not is_list_like(other): + raise TypeError(msg.format(cls=type(self).__name__, + typ=type(other).__name__)) + else: other = TimedeltaIndex(other).values result = func(other) result = com._values_from_object(result) - if isinstance(other, Index): - o_mask = other.values.view('i8') == iNaT - else: - o_mask = other.view('i8') == iNaT - + o_mask = np.array(isna(other)) if o_mask.any(): result[o_mask] = nat_result @@ -416,9 +414,15 @@ def _evaluate_with_timedelta_like(self, other, op): def _add_datelike(self, other): # adding a timedeltaindex to a datetimelike from pandas import Timestamp, DatetimeIndex + if other is NaT: # GH#19124 pd.NaT is treated like a timedelta return self._nat_new() + elif isinstance(other, (DatetimeIndex, np.ndarray)): + # if other is an ndarray, we assume it is datetime64-dtype + # defer to implementation in DatetimeIndex + other = DatetimeIndex(other) + return other + self else: other = Timestamp(other) i8 = self.asi8 @@ -434,7 +438,8 @@ def _sub_datelike(self, other): if other is NaT: return self._nat_new() else: - raise TypeError("cannot subtract a datelike from a TimedeltaIndex") + raise TypeError("cannot subtract a datelike from a {cls}" + .format(cls=type(self).__name__)) def _addsub_offset_array(self, other, op): # Add or subtract Array-like of DateOffset objects @@ -962,8 +967,7 @@ def _is_convertible_to_index(other): def _is_convertible_to_td(key): - # TODO: Not all DateOffset objects are convertible to Timedelta - return isinstance(key, (DateOffset, timedelta, Timedelta, + return isinstance(key, (Tick, timedelta, np.timedelta64, compat.string_types)) diff --git a/pandas/tests/indexes/datetimes/test_arithmetic.py b/pandas/tests/indexes/datetimes/test_arithmetic.py index 5a7ea44f3698c..0c56c6b16fb2f 100644 --- a/pandas/tests/indexes/datetimes/test_arithmetic.py +++ b/pandas/tests/indexes/datetimes/test_arithmetic.py @@ -508,7 +508,7 @@ def test_dti_sub_tdi(self, tz): result = dti - tdi tm.assert_index_equal(result, expected) - msg = 'cannot subtract TimedeltaIndex and DatetimeIndex' + msg = 'cannot subtract .*TimedeltaIndex' with tm.assert_raises_regex(TypeError, msg): tdi - dti @@ -531,7 +531,7 @@ def test_dti_isub_tdi(self, tz): result -= tdi tm.assert_index_equal(result, expected) - msg = 'cannot subtract TimedeltaIndex and DatetimeIndex' + msg = 'cannot subtract .*TimedeltaIndex' with tm.assert_raises_regex(TypeError, msg): tdi -= dti diff --git a/pandas/tests/indexes/timedeltas/test_arithmetic.py b/pandas/tests/indexes/timedeltas/test_arithmetic.py index 6a80b995b6ee9..9ffffb6ff06d5 100644 --- a/pandas/tests/indexes/timedeltas/test_arithmetic.py +++ b/pandas/tests/indexes/timedeltas/test_arithmetic.py @@ -792,7 +792,7 @@ def test_addition_ops(self): pytest.raises(ValueError, lambda: tdi[0:1] + dti) # random indexes - pytest.raises(TypeError, lambda: tdi + Int64Index([1, 2, 3])) + pytest.raises(NullFrequencyError, lambda: tdi + Int64Index([1, 2, 3])) # this is a union! # pytest.raises(TypeError, lambda : Int64Index([1,2,3]) + tdi)
DatetimeIndexOpsMixin has an unfortunate kludge where it checks if `self` is a `TimedeltaIndex` and if so dispatches to a reversed operation. This then makes subsequent checks less straightforward than they could/should be. This fixes that. This is in preparation for separating out DatetimeArray/TimedeltaArray/PeriodArray, so this uses formatting on error messages to be class-agnostic.
https://api.github.com/repos/pandas-dev/pandas/pulls/19895
2018-02-25T19:00:46Z
2018-02-26T11:10:15Z
2018-02-26T11:10:15Z
2018-06-22T03:29:35Z
EHN: Implement method argument for DataFrame.replace
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 79d85513efa26..feca90aae6237 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -338,6 +338,7 @@ Other Enhancements - For subclassed ``DataFrames``, :func:`DataFrame.apply` will now preserve the ``Series`` subclass (if defined) when passing the data to the applied function (:issue:`19822`) - :func:`DataFrame.from_dict` now accepts a ``columns`` argument that can be used to specify the column names when ``orient='index'`` is used (:issue:`18529`) - Added option ``display.html.use_mathjax`` so `MathJax <https://www.mathjax.org/>`_ can be disabled when rendering tables in ``Jupyter`` notebooks (:issue:`19856`, :issue:`19824`) +- :func:`DataFrame.replace` now supports the ``method`` parameter, which can be used to specify the replacement method when ``to_replace`` is a scalar, list or tuple and ``value`` is ``None`` (:issue:`19632`) - :meth:`Timestamp.month_name`, :meth:`DatetimeIndex.month_name`, and :meth:`Series.dt.month_name` are now available (:issue:`12805`) - :meth:`Timestamp.day_name` and :meth:`DatetimeIndex.day_name` are now available to return day names with a specified locale (:issue:`12806`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index e34fe606be759..a893b2ba1a189 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4886,7 +4886,10 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): ``to_replace`` must be ``None``. method : string, optional, {'pad', 'ffill', 'bfill'} The method to use when for replacement, when ``to_replace`` is a - ``list``. + scalar, list or tuple and ``value`` is None. + + .. versionchanged:: 0.23.0 + Added to DataFrame See Also -------- @@ -5055,6 +5058,10 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, to_replace = [to_replace] if isinstance(to_replace, (tuple, list)): + if isinstance(self, pd.DataFrame): + return self.apply(_single_replace, + args=(to_replace, method, inplace, + limit)) return _single_replace(self, to_replace, method, inplace, limit) diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index fbc4accd0e41e..dd83a94b7062a 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -33,9 +33,6 @@ def test_replace_inplace(self): tsframe.replace(nan, 0, inplace=True) assert_frame_equal(tsframe, self.tsframe.fillna(0)) - pytest.raises(TypeError, self.tsframe.replace, nan, inplace=True) - pytest.raises(TypeError, self.tsframe.replace, nan) - # mixed type mf = self.mixed_frame mf.iloc[5:20, mf.columns.get_loc('foo')] = nan @@ -720,7 +717,6 @@ def test_replace_simple_nested_dict_with_nonexistent_value(self): assert_frame_equal(expected, result) def test_replace_value_is_none(self): - pytest.raises(TypeError, self.tsframe.replace, nan) orig_value = self.tsframe.iloc[0, 0] orig2 = self.tsframe.iloc[1, 0] @@ -1072,3 +1068,36 @@ def test_replace_with_empty_dictlike(self): assert_frame_equal(df, df.replace({'b': {}})) assert_frame_equal(df, df.replace(Series({'b': {}}))) + + @pytest.mark.parametrize("to_replace, method, expected", [ + (0, 'bfill', {'A': [1, 1, 2], + 'B': [5, nan, 7], + 'C': ['a', 'b', 'c']}), + (nan, 'bfill', {'A': [0, 1, 2], + 'B': [5.0, 7.0, 7.0], + 'C': ['a', 'b', 'c']}), + ('d', 'ffill', {'A': [0, 1, 2], + 'B': [5, nan, 7], + 'C': ['a', 'b', 'c']}), + ([0, 2], 'bfill', {'A': [1, 1, 2], + 'B': [5, nan, 7], + 'C': ['a', 'b', 'c']}), + ([1, 2], 'pad', {'A': [0, 0, 0], + 'B': [5, nan, 7], + 'C': ['a', 'b', 'c']}), + ((1, 2), 'bfill', {'A': [0, 2, 2], + 'B': [5, nan, 7], + 'C': ['a', 'b', 'c']}), + (['b', 'c'], 'ffill', {'A': [0, 1, 2], + 'B': [5, nan, 7], + 'C': ['a', 'a', 'a']}), + ]) + def test_replace_method(self, to_replace, method, expected): + # GH 19632 + df = DataFrame({'A': [0, 1, 2], + 'B': [5, nan, 7], + 'C': ['a', 'b', 'c']}) + + result = df.replace(to_replace=to_replace, value=None, method=method) + expected = DataFrame(expected) + assert_frame_equal(result, expected)
- [x] closes #19632 - [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/19894
2018-02-25T12:49:20Z
2018-03-07T14:32:12Z
2018-03-07T14:32:12Z
2018-03-07T22:19:06Z
CLN: Remove Series._from_array
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index d306d0d78f1f4..0501493e718d0 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -101,6 +101,27 @@ def _get_frame_result_type(result, objs): ABCSparseDataFrame)) +def _get_sliced_frame_result_type(data, obj): + """ + return appropriate class of Series. When data is sparse + it will return a SparseSeries, otherwise it will return + the Series. + + Parameters + ---------- + data : array-like + obj : DataFrame + + Returns + ------- + Series or SparseSeries + """ + if is_sparse(data): + from pandas.core.sparse.api import SparseSeries + return SparseSeries + return obj._constructor_sliced + + def _concat_compat(to_concat, axis=0): """ provide concatenation of an array of arrays each of which is a single diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 061b69f25e7ac..5e9c7d5e4e699 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -60,6 +60,7 @@ is_iterator, is_sequence, is_named_tuple) +from pandas.core.dtypes.concat import _get_sliced_frame_result_type from pandas.core.dtypes.missing import isna, notna @@ -2166,8 +2167,7 @@ def _ixs(self, i, axis=0): if index_len and not len(values): values = np.array([np.nan] * index_len, dtype=object) - result = self._constructor_sliced._from_array( - values, index=self.index, name=label, fastpath=True) + result = self._box_col_values(values, label) # this is a cached value, mark it so result._set_as_cached(label, self) @@ -2563,8 +2563,8 @@ def _box_item_values(self, key, values): def _box_col_values(self, values, items): """ provide boxed values for a column """ - return self._constructor_sliced._from_array(values, index=self.index, - name=items, fastpath=True) + klass = _get_sliced_frame_result_type(values, self) + return klass(values, index=self.index, name=items, fastpath=True) def __setitem__(self, key, value): key = com._apply_if_callable(key, self) diff --git a/pandas/core/series.py b/pandas/core/series.py index b42e02bc99237..17f91606c1062 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -305,25 +305,11 @@ def from_array(cls, arr, index=None, name=None, dtype=None, copy=False, warnings.warn("'from_array' is deprecated and will be removed in a " "future version. Please use the pd.Series(..) " "constructor instead.", FutureWarning, stacklevel=2) - return cls._from_array(arr, index=index, name=name, dtype=dtype, - copy=copy, fastpath=fastpath) - - @classmethod - def _from_array(cls, arr, index=None, name=None, dtype=None, copy=False, - fastpath=False): - """ - Internal method used in DataFrame.__setitem__/__getitem__. - Difference with Series(..) is that this method checks if a sparse - array is passed. - - """ - # return a sparse series here if isinstance(arr, ABCSparseArray): from pandas.core.sparse.series import SparseSeries cls = SparseSeries - - return cls(arr, index=index, name=name, dtype=dtype, copy=copy, - fastpath=fastpath) + return cls(arr, index=index, name=name, dtype=dtype, + copy=copy, fastpath=fastpath) @property def _constructor(self): diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py index 26cf9dbadbbf2..3a6b87f832ff7 100644 --- a/pandas/core/sparse/series.py +++ b/pandas/core/sparse/series.py @@ -216,12 +216,6 @@ def from_array(cls, arr, index=None, name=None, copy=False, warnings.warn("'from_array' is deprecated and will be removed in a " "future version. Please use the pd.SparseSeries(..) " "constructor instead.", FutureWarning, stacklevel=2) - return cls._from_array(arr, index=index, name=name, copy=copy, - fill_value=fill_value, fastpath=fastpath) - - @classmethod - def _from_array(cls, arr, index=None, name=None, copy=False, - fill_value=None, fastpath=False): return cls(arr, index=index, name=name, copy=copy, fill_value=fill_value, fastpath=fastpath)
This PR transfers the class check of `Series._from_array` to `DataFrame._box_col_values`; removing the need for calling the `Series._from_array` and allowing for user-defined slice-inheritance of metadata. I opted to delete the function as it was private but leave the `Series.from_array` public access working and it's FutureWarning of deprecation, as it was. To do that, I had to modify `Series.from_array` so it would keep also its original functionality until is completely deleted. - [x] closes #19883 - [ ] passed tests. - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/19893
2018-02-25T09:40:50Z
2018-02-27T01:15:32Z
2018-02-27T01:15:31Z
2018-02-27T01:15:36Z
BUG: Retain timezone dtype with cut and qcut
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 233816600ec0f..bf267f2299f90 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1018,6 +1018,7 @@ Reshaping - Bug in :func:`DataFrame.iterrows`, which would infers strings not compliant to `ISO8601 <https://en.wikipedia.org/wiki/ISO_8601>`_ to datetimes (:issue:`19671`) - Bug in :class:`Series` constructor with ``Categorical`` where a ```ValueError`` is not raised when an index of different length is given (:issue:`19342`) - Bug in :meth:`DataFrame.astype` where column metadata is lost when converting to categorical or a dictionary of dtypes (:issue:`19920`) +- Bug in :func:`cut` and :func:`qcut` where timezone information was dropped (:issue:`19872`) Other ^^^^^ diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 359c030157bd3..30132ddc05c40 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -1,6 +1,7 @@ """ Quantilization functions and related stuff """ +from functools import partial from pandas.core.dtypes.missing import isna from pandas.core.dtypes.common import ( @@ -9,6 +10,7 @@ is_categorical_dtype, is_datetime64_dtype, is_timedelta64_dtype, + is_datetime64tz_dtype, _ensure_int64) import pandas.core.algorithms as algos @@ -239,7 +241,8 @@ def _bins_to_cuts(x, bins, right=True, labels=None, ids = _ensure_int64(bins.searchsorted(x, side=side)) if include_lowest: - ids[x == bins[0]] = 1 + # Numpy 1.9 support: ensure this mask is a Numpy array + ids[np.asarray(x == bins[0])] = 1 na_mask = isna(x) | (ids == len(bins)) | (ids == 0) has_nas = na_mask.any() @@ -284,12 +287,14 @@ def _coerce_to_type(x): """ dtype = None - if is_timedelta64_dtype(x): - x = to_timedelta(x) - dtype = np.timedelta64 + if is_datetime64tz_dtype(x): + dtype = x.dtype elif is_datetime64_dtype(x): x = to_datetime(x) dtype = np.datetime64 + elif is_timedelta64_dtype(x): + x = to_timedelta(x) + dtype = np.timedelta64 if dtype is not None: # GH 19768: force NaT to NaN during integer conversion @@ -305,7 +310,7 @@ def _convert_bin_to_numeric_type(bins, dtype): Parameters ---------- - bins : list-liek of bins + bins : list-like of bins dtype : dtype of data Raises @@ -318,7 +323,7 @@ def _convert_bin_to_numeric_type(bins, dtype): bins = to_timedelta(bins).view(np.int64) else: raise ValueError("bins must be of timedelta64 dtype") - elif is_datetime64_dtype(dtype): + elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype): if bins_dtype in ['datetime', 'datetime64']: bins = to_datetime(bins).view(np.int64) else: @@ -333,7 +338,10 @@ def _format_labels(bins, precision, right=True, closed = 'right' if right else 'left' - if is_datetime64_dtype(dtype): + if is_datetime64tz_dtype(dtype): + formatter = partial(Timestamp, tz=dtype.tz) + adjust = lambda x: x - Timedelta('1ns') + elif is_datetime64_dtype(dtype): formatter = Timestamp adjust = lambda x: x - Timedelta('1ns') elif is_timedelta64_dtype(dtype): @@ -372,7 +380,13 @@ def _preprocess_for_cut(x): series_index = x.index name = x.name - x = np.asarray(x) + # Check that the passed array is a Pandas or Numpy object + # We don't want to strip away a Pandas data-type here (e.g. datetimetz) + ndim = getattr(x, 'ndim', None) + if ndim is None: + x = np.asarray(x) + if x.ndim != 1: + raise ValueError("Input array must be 1 dimensional") return x_is_series, series_index, name, x diff --git a/pandas/tests/reshape/test_tile.py b/pandas/tests/reshape/test_tile.py index ff914273d47b1..8d093f2784ba1 100644 --- a/pandas/tests/reshape/test_tile.py +++ b/pandas/tests/reshape/test_tile.py @@ -4,7 +4,7 @@ import numpy as np from pandas.compat import zip -from pandas import (Series, isna, to_datetime, DatetimeIndex, +from pandas import (DataFrame, Series, isna, to_datetime, DatetimeIndex, Index, Timestamp, Interval, IntervalIndex, Categorical, cut, qcut, date_range, NaT, TimedeltaIndex) from pandas.tseries.offsets import Nano, Day @@ -104,6 +104,12 @@ def test_cut_corner(self): pytest.raises(ValueError, cut, [1, 2, 3], 0.5) + @pytest.mark.parametrize('arg', [2, np.eye(2), DataFrame(np.eye(2))]) + @pytest.mark.parametrize('cut_func', [cut, qcut]) + def test_cut_not_1d_arg(self, arg, cut_func): + with pytest.raises(ValueError): + cut_func(arg, 2) + def test_cut_out_of_range_more(self): # #1511 s = Series([0, -1, 0, 1, -3], name='x') @@ -251,18 +257,6 @@ def test_qcut_nas(self): result = qcut(arr, 4) assert isna(result[:20]).all() - @pytest.mark.parametrize('s', [ - Series(DatetimeIndex(['20180101', NaT, '20180103'])), - Series(TimedeltaIndex(['0 days', NaT, '2 days']))], - ids=lambda x: str(x.dtype)) - def test_qcut_nat(self, s): - # GH 19768 - intervals = IntervalIndex.from_tuples( - [(s[0] - Nano(), s[2] - Day()), np.nan, (s[2] - Day(), s[2])]) - expected = Series(Categorical(intervals, ordered=True)) - result = qcut(s, 2) - tm.assert_series_equal(result, expected) - def test_qcut_index(self): result = qcut([0, 2], 2) intervals = [Interval(-0.001, 1), Interval(1, 2)] @@ -452,6 +446,37 @@ def test_single_bin(self): result = cut(s, 1, labels=False) tm.assert_series_equal(result, expected) + @pytest.mark.parametrize( + "array_1_writeable, array_2_writeable", + [(True, True), (True, False), (False, False)]) + def test_cut_read_only(self, array_1_writeable, array_2_writeable): + # issue 18773 + array_1 = np.arange(0, 100, 10) + array_1.flags.writeable = array_1_writeable + + array_2 = np.arange(0, 100, 10) + array_2.flags.writeable = array_2_writeable + + hundred_elements = np.arange(100) + + tm.assert_categorical_equal(cut(hundred_elements, array_1), + cut(hundred_elements, array_2)) + + +class TestDatelike(object): + + @pytest.mark.parametrize('s', [ + Series(DatetimeIndex(['20180101', NaT, '20180103'])), + Series(TimedeltaIndex(['0 days', NaT, '2 days']))], + ids=lambda x: str(x.dtype)) + def test_qcut_nat(self, s): + # GH 19768 + intervals = IntervalIndex.from_tuples( + [(s[0] - Nano(), s[2] - Day()), np.nan, (s[2] - Day(), s[2])]) + expected = Series(Categorical(intervals, ordered=True)) + result = qcut(s, 2) + tm.assert_series_equal(result, expected) + def test_datetime_cut(self): # GH 14714 # testing for time data to be present as series @@ -488,6 +513,47 @@ def test_datetime_cut(self): result, bins = cut(data, 3, retbins=True) tm.assert_series_equal(Series(result), expected) + @pytest.mark.parametrize('bins', [ + 3, [Timestamp('2013-01-01 04:57:07.200000'), + Timestamp('2013-01-01 21:00:00'), + Timestamp('2013-01-02 13:00:00'), + Timestamp('2013-01-03 05:00:00')]]) + @pytest.mark.parametrize('box', [list, np.array, Index, Series]) + def test_datetimetz_cut(self, bins, box): + # GH 19872 + tz = 'US/Eastern' + s = Series(date_range('20130101', periods=3, tz=tz)) + if not isinstance(bins, int): + bins = box(bins) + result = cut(s, bins) + expected = ( + Series(IntervalIndex([ + Interval(Timestamp('2012-12-31 23:57:07.200000', tz=tz), + Timestamp('2013-01-01 16:00:00', tz=tz)), + Interval(Timestamp('2013-01-01 16:00:00', tz=tz), + Timestamp('2013-01-02 08:00:00', tz=tz)), + Interval(Timestamp('2013-01-02 08:00:00', tz=tz), + Timestamp('2013-01-03 00:00:00', tz=tz))])) + .astype(CDT(ordered=True))) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize('bins', [3, np.linspace(0, 1, 4)]) + def test_datetimetz_qcut(self, bins): + # GH 19872 + tz = 'US/Eastern' + s = Series(date_range('20130101', periods=3, tz=tz)) + result = qcut(s, bins) + expected = ( + Series(IntervalIndex([ + Interval(Timestamp('2012-12-31 23:59:59.999999999', tz=tz), + Timestamp('2013-01-01 16:00:00', tz=tz)), + Interval(Timestamp('2013-01-01 16:00:00', tz=tz), + Timestamp('2013-01-02 08:00:00', tz=tz)), + Interval(Timestamp('2013-01-02 08:00:00', tz=tz), + Timestamp('2013-01-03 00:00:00', tz=tz))])) + .astype(CDT(ordered=True))) + tm.assert_series_equal(result, expected) + def test_datetime_bin(self): data = [np.datetime64('2012-12-13'), np.datetime64('2012-12-15')] bin_data = ['2012-12-12', '2012-12-14', '2012-12-16'] @@ -523,19 +589,3 @@ def f(): mask = result.isna() tm.assert_numpy_array_equal( mask, np.array([False, True, True, True, True])) - - @pytest.mark.parametrize( - "array_1_writeable, array_2_writeable", - [(True, True), (True, False), (False, False)]) - def test_cut_read_only(self, array_1_writeable, array_2_writeable): - # issue 18773 - array_1 = np.arange(0, 100, 10) - array_1.flags.writeable = array_1_writeable - - array_2 = np.arange(0, 100, 10) - array_2.flags.writeable = array_2_writeable - - hundred_elements = np.arange(100) - - tm.assert_categorical_equal(cut(hundred_elements, array_1), - cut(hundred_elements, array_2))
- [x] closes #19872 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Timezone dtypes were getting lost as the `_preprocess_for_cut` function called `np.asarray` on all incomming data. I added an additional check that the input array is 1D as stated in the docs of `cut` and `qcut`.
https://api.github.com/repos/pandas-dev/pandas/pulls/19890
2018-02-25T06:41:12Z
2018-03-09T11:13:51Z
2018-03-09T11:13:51Z
2023-09-06T15:09:40Z
ENH: Allow Timestamp to accept Nanosecond argument
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index fb22dc40e335f..6bfd8fcca45b1 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -587,6 +587,7 @@ Datetimelike API Changes - Subtraction of :class:`Series` with timezone-aware ``dtype='datetime64[ns]'`` with mis-matched timezones will raise ``TypeError`` instead of ``ValueError`` (:issue:`18817`) - :func:`pandas.merge` provides a more informative error message when trying to merge on timezone-aware and timezone-naive columns (:issue:`15800`) - For :class:`DatetimeIndex` and :class:`TimedeltaIndex` with ``freq=None``, addition or subtraction of integer-dtyped array or ``Index`` will raise ``NullFrequencyError`` instead of ``TypeError`` (:issue:`19895`) +- :class:`Timestamp` constructor now accepts a `nanosecond` keyword or positional argument (:issue:`18898`) .. _whatsnew_0230.api.other: diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index 868c2641b34db..8f887dc3af203 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -16,7 +16,8 @@ cdef class _TSObject: cdef convert_to_tsobject(object ts, object tz, object unit, - bint dayfirst, bint yearfirst) + bint dayfirst, bint yearfirst, + int32_t nanos=*) cdef _TSObject convert_datetime_to_tsobject(datetime ts, object tz, int32_t nanos=*) diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index beaca1a8483c7..fd1ec1c21e55c 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -252,7 +252,7 @@ cpdef int64_t pydt_to_i8(object pydt) except? -1: cdef convert_to_tsobject(object ts, object tz, object unit, - bint dayfirst, bint yearfirst): + bint dayfirst, bint yearfirst, int32_t nanos=0): """ Extract datetime and int64 from any of: - np.int64 (with unit providing a possible modifier) @@ -297,7 +297,7 @@ cdef convert_to_tsobject(object ts, object tz, object unit, obj.value = ts dt64_to_dtstruct(ts, &obj.dts) elif PyDateTime_Check(ts): - return convert_datetime_to_tsobject(ts, tz) + return convert_datetime_to_tsobject(ts, tz, nanos) elif PyDate_Check(ts): # Keep the converter same as PyDateTime's ts = datetime.combine(ts, datetime_time()) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index ed77916a1d887..421f781483290 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -107,6 +107,7 @@ cdef class _Timestamp(datetime): cdef readonly: int64_t value, nanosecond object freq # frequency reference + list _date_attributes def __hash__(_Timestamp self): if self.nanosecond: @@ -425,6 +426,8 @@ class Timestamp(_Timestamp): .. versionadded:: 0.19.0 hour, minute, second, microsecond : int, optional, default 0 .. versionadded:: 0.19.0 + nanosecond : int, optional, default 0 + .. versionadded:: 0.23.0 tzinfo : datetime.tzinfo, optional, default None .. versionadded:: 0.19.0 @@ -556,7 +559,7 @@ class Timestamp(_Timestamp): object freq=None, tz=None, unit=None, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, - tzinfo=None): + nanosecond=None, tzinfo=None): # The parameter list folds together legacy parameter names (the first # four) and positional and keyword parameter names from pydatetime. # @@ -580,6 +583,9 @@ class Timestamp(_Timestamp): cdef _TSObject ts + _date_attributes = [year, month, day, hour, minute, second, + microsecond, nanosecond] + if tzinfo is not None: if not PyTZInfo_Check(tzinfo): # tzinfo must be a datetime.tzinfo object, GH#17690 @@ -588,7 +594,14 @@ class Timestamp(_Timestamp): elif tz is not None: raise ValueError('Can provide at most one of tz, tzinfo') - if ts_input is _no_input: + if is_string_object(ts_input): + # User passed a date string to parse. + # Check that the user didn't also pass a date attribute kwarg. + if any(arg is not None for arg in _date_attributes): + raise ValueError('Cannot pass a date attribute keyword ' + 'argument when passing a date string') + + elif ts_input is _no_input: # User passed keyword arguments. if tz is None: # Handle the case where the user passes `tz` and not `tzinfo` @@ -596,20 +609,20 @@ class Timestamp(_Timestamp): return Timestamp(datetime(year, month, day, hour or 0, minute or 0, second or 0, microsecond or 0, tzinfo), - tz=tz) + nanosecond=nanosecond, tz=tz) elif is_integer_object(freq): # User passed positional arguments: # Timestamp(year, month, day[, hour[, minute[, second[, - # microsecond[, tzinfo]]]]]) + # microsecond[, nanosecond[, tzinfo]]]]]]) return Timestamp(datetime(ts_input, freq, tz, unit or 0, year or 0, month or 0, day or 0, - hour), tz=hour) + minute), nanosecond=hour, tz=minute) if tzinfo is not None: # User passed tzinfo instead of tz; avoid silently ignoring tz, tzinfo = tzinfo, None - ts = convert_to_tsobject(ts_input, tz, unit, 0, 0) + ts = convert_to_tsobject(ts_input, tz, unit, 0, 0, nanosecond or 0) if ts.value == NPY_NAT: return NaT diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 7695c94409232..504a76f259e55 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -385,6 +385,27 @@ def test_constructor_fromordinal(self): ts = Timestamp.fromordinal(dt_tz.toordinal(), tz='US/Eastern') assert ts.to_pydatetime() == dt_tz + @pytest.mark.parametrize('result', [ + Timestamp(datetime(2000, 1, 2, 3, 4, 5, 6), nanosecond=1), + Timestamp(year=2000, month=1, day=2, hour=3, minute=4, second=5, + microsecond=6, nanosecond=1), + Timestamp(year=2000, month=1, day=2, hour=3, minute=4, second=5, + microsecond=6, nanosecond=1, tz='UTC'), + Timestamp(2000, 1, 2, 3, 4, 5, 6, 1, None), + Timestamp(2000, 1, 2, 3, 4, 5, 6, 1, pytz.UTC)]) + def test_constructor_nanosecond(self, result): + # GH 18898 + expected = Timestamp(datetime(2000, 1, 2, 3, 4, 5, 6), tz=result.tz) + expected = expected + Timedelta(nanoseconds=1) + assert result == expected + + @pytest.mark.parametrize('arg', ['year', 'month', 'day', 'hour', 'minute', + 'second', 'microsecond', 'nanosecond']) + def test_invalid_date_kwarg_with_string_input(self, arg): + kwarg = {arg: 1} + with pytest.raises(ValueError): + Timestamp('2010-10-10 12:59:59.999999999', **kwarg) + def test_out_of_bounds_value(self): one_us = np.timedelta64(1).astype('timedelta64[us]')
- [x] closes #18898 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Needed to add a new `nanos` argument to `convert_to_tsobject` arguments from `Timestamp.__new__` dispatches to this function (and `datetime.datetime` cannot take a nanosecond argument).
https://api.github.com/repos/pandas-dev/pandas/pulls/19889
2018-02-25T02:22:00Z
2018-03-01T01:32:25Z
2018-03-01T01:32:24Z
2018-03-01T02:05:05Z
CI: pin jemalloc=4.5.0.poast for 2.7 build per
diff --git a/ci/requirements-2.7.sh b/ci/requirements-2.7.sh index e3bd5e46026c5..95169e5dcce57 100644 --- a/ci/requirements-2.7.sh +++ b/ci/requirements-2.7.sh @@ -4,4 +4,4 @@ source activate pandas echo "install 27" -conda install -n pandas -c conda-forge feather-format pyarrow=0.4.1 fastparquet +conda install -n pandas -c conda-forge feather-format pyarrow=0.4.1 jemalloc=4.5.0.post fastparquet
https://issues.apache.org/jira/browse/ARROW-2208
https://api.github.com/repos/pandas-dev/pandas/pulls/19888
2018-02-25T01:15:06Z
2018-02-25T01:44:50Z
2018-02-25T01:44:50Z
2018-02-25T01:44:50Z
Assorted _libs cleanups
diff --git a/pandas/_libs/lib.pxd b/pandas/_libs/lib.pxd deleted file mode 100644 index b06c071c358c1..0000000000000 --- a/pandas/_libs/lib.pxd +++ /dev/null @@ -1,3 +0,0 @@ -# prototypes for sharing - -cpdef bint is_period(val) diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index e1d59f807a7fd..30521760327b4 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -21,11 +21,9 @@ from cpython cimport (Py_INCREF, PyTuple_SET_ITEM, PyBytes_Check, PyUnicode_Check, PyTuple_New, + Py_EQ, PyObject_RichCompareBool) -cimport cpython - - from cpython.datetime cimport (PyDateTime_Check, PyDate_Check, PyTime_Check, PyDelta_Check, PyDateTime_IMPORT) @@ -105,6 +103,14 @@ def item_from_zerodim(object val): """ If the value is a zerodim array, return the item it contains. + Parameters + ---------- + val : object + + Returns + ------- + result : object + Examples -------- >>> item_from_zerodim(1) @@ -117,7 +123,9 @@ def item_from_zerodim(object val): array([1]) """ - return util.unbox_if_zerodim(val) + if cnp.PyArray_IsZeroDim(val): + return cnp.PyArray_ToScalar(cnp.PyArray_DATA(val), val) + return val @cython.wraparound(False) @@ -405,72 +413,6 @@ def maybe_booleans_to_slice(ndarray[uint8_t] mask): return slice(start, end) -@cython.wraparound(False) -@cython.boundscheck(False) -def scalar_compare(ndarray[object] values, object val, object op): - cdef: - Py_ssize_t i, n = len(values) - ndarray[uint8_t, cast=True] result - bint isnull_val - int flag - object x - - if op is operator.lt: - flag = cpython.Py_LT - elif op is operator.le: - flag = cpython.Py_LE - elif op is operator.gt: - flag = cpython.Py_GT - elif op is operator.ge: - flag = cpython.Py_GE - elif op is operator.eq: - flag = cpython.Py_EQ - elif op is operator.ne: - flag = cpython.Py_NE - else: - raise ValueError('Unrecognized operator') - - result = np.empty(n, dtype=bool).view(np.uint8) - isnull_val = checknull(val) - - if flag == cpython.Py_NE: - for i in range(n): - x = values[i] - if checknull(x): - result[i] = True - elif isnull_val: - result[i] = True - else: - try: - result[i] = PyObject_RichCompareBool(x, val, flag) - except (TypeError): - result[i] = True - elif flag == cpython.Py_EQ: - for i in range(n): - x = values[i] - if checknull(x): - result[i] = False - elif isnull_val: - result[i] = False - else: - try: - result[i] = PyObject_RichCompareBool(x, val, flag) - except (TypeError): - result[i] = False - - else: - for i in range(n): - x = values[i] - if checknull(x): - result[i] = False - elif isnull_val: - result[i] = False - else: - result[i] = PyObject_RichCompareBool(x, val, flag) - - return result.view(bool) - - @cython.wraparound(False) @cython.boundscheck(False) cpdef bint array_equivalent_object(object[:] left, object[:] right): @@ -486,115 +428,12 @@ cpdef bint array_equivalent_object(object[:] left, object[:] right): # we are either not equal or both nan # I think None == None will be true here - if not (PyObject_RichCompareBool(x, y, cpython.Py_EQ) or + if not (PyObject_RichCompareBool(x, y, Py_EQ) or _checknull(x) and _checknull(y)): return False return True -@cython.wraparound(False) -@cython.boundscheck(False) -def vec_compare(ndarray[object] left, ndarray[object] right, object op): - cdef: - Py_ssize_t i, n = len(left) - ndarray[uint8_t, cast=True] result - int flag - - if n != len(right): - raise ValueError('Arrays were different lengths: %d vs %d' - % (n, len(right))) - - if op is operator.lt: - flag = cpython.Py_LT - elif op is operator.le: - flag = cpython.Py_LE - elif op is operator.gt: - flag = cpython.Py_GT - elif op is operator.ge: - flag = cpython.Py_GE - elif op is operator.eq: - flag = cpython.Py_EQ - elif op is operator.ne: - flag = cpython.Py_NE - else: - raise ValueError('Unrecognized operator') - - result = np.empty(n, dtype=bool).view(np.uint8) - - if flag == cpython.Py_NE: - for i in range(n): - x = left[i] - y = right[i] - - if checknull(x) or checknull(y): - result[i] = True - else: - result[i] = PyObject_RichCompareBool(x, y, flag) - else: - for i in range(n): - x = left[i] - y = right[i] - - if checknull(x) or checknull(y): - result[i] = False - else: - result[i] = PyObject_RichCompareBool(x, y, flag) - - return result.view(bool) - - -@cython.wraparound(False) -@cython.boundscheck(False) -def scalar_binop(ndarray[object] values, object val, object op): - cdef: - Py_ssize_t i, n = len(values) - ndarray[object] result - object x - - result = np.empty(n, dtype=object) - if _checknull(val): - result.fill(val) - return result - - for i in range(n): - x = values[i] - if _checknull(x): - result[i] = x - else: - result[i] = op(x, val) - - return maybe_convert_bool(result) - - -@cython.wraparound(False) -@cython.boundscheck(False) -def vec_binop(ndarray[object] left, ndarray[object] right, object op): - cdef: - Py_ssize_t i, n = len(left) - ndarray[object] result - - if n != len(right): - raise ValueError('Arrays were different lengths: %d vs %d' - % (n, len(right))) - - result = np.empty(n, dtype=object) - - for i in range(n): - x = left[i] - y = right[i] - try: - result[i] = op(x, y) - except TypeError: - if _checknull(x): - result[i] = x - elif _checknull(y): - result[i] = y - else: - raise - - return maybe_convert_bool(result) - - def astype_intsafe(ndarray[object] arr, new_dtype): cdef: Py_ssize_t i, n = len(arr) diff --git a/pandas/_libs/ops.pyx b/pandas/_libs/ops.pyx new file mode 100644 index 0000000000000..148018ece20e2 --- /dev/null +++ b/pandas/_libs/ops.pyx @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- +# cython: profile=False +import operator + +from cpython cimport (PyFloat_Check, PyBool_Check, + PyObject_RichCompareBool, + Py_EQ, Py_NE, Py_LT, Py_LE, Py_GT, Py_GE) + +cimport cython +from cython cimport Py_ssize_t + +import numpy as np +from numpy cimport ndarray, uint8_t + + +from util cimport UINT8_MAX, _checknull + +from missing cimport checknull + + +@cython.wraparound(False) +@cython.boundscheck(False) +def scalar_compare(ndarray[object] values, object val, object op): + """ + Compare each element of `values` array with the scalar `val`, with + the comparison operation described by `op`. + + Parameters + ---------- + values : ndarray[object] + val : object + op : {operator.eq, operator.ne, + operator.le, operator.lt, + operator.ge, operator.gt} + + Returns + ------- + result : ndarray[bool] + """ + cdef: + Py_ssize_t i, n = len(values) + ndarray[uint8_t, cast=True] result + bint isnull_val + int flag + object x + + if op is operator.lt: + flag = Py_LT + elif op is operator.le: + flag = Py_LE + elif op is operator.gt: + flag = Py_GT + elif op is operator.ge: + flag = Py_GE + elif op is operator.eq: + flag = Py_EQ + elif op is operator.ne: + flag = Py_NE + else: + raise ValueError('Unrecognized operator') + + result = np.empty(n, dtype=bool).view(np.uint8) + isnull_val = checknull(val) + + if flag == Py_NE: + for i in range(n): + x = values[i] + if checknull(x): + result[i] = True + elif isnull_val: + result[i] = True + else: + try: + result[i] = PyObject_RichCompareBool(x, val, flag) + except (TypeError): + result[i] = True + elif flag == Py_EQ: + for i in range(n): + x = values[i] + if checknull(x): + result[i] = False + elif isnull_val: + result[i] = False + else: + try: + result[i] = PyObject_RichCompareBool(x, val, flag) + except (TypeError): + result[i] = False + + else: + for i in range(n): + x = values[i] + if checknull(x): + result[i] = False + elif isnull_val: + result[i] = False + else: + result[i] = PyObject_RichCompareBool(x, val, flag) + + return result.view(bool) + + +@cython.wraparound(False) +@cython.boundscheck(False) +def vec_compare(ndarray[object] left, ndarray[object] right, object op): + """ + Compare the elements of `left` with the elements of `right` pointwise, + with the comparison operation described by `op`. + + Parameters + ---------- + left : ndarray[object] + right : ndarray[object] + op : {operator.eq, operator.ne, + operator.le, operator.lt, + operator.ge, operator.gt} + + Returns + ------- + result : ndarray[bool] + """ + cdef: + Py_ssize_t i, n = len(left) + ndarray[uint8_t, cast=True] result + int flag + + if n != len(right): + raise ValueError('Arrays were different lengths: %d vs %d' + % (n, len(right))) + + if op is operator.lt: + flag = Py_LT + elif op is operator.le: + flag = Py_LE + elif op is operator.gt: + flag = Py_GT + elif op is operator.ge: + flag = Py_GE + elif op is operator.eq: + flag = Py_EQ + elif op is operator.ne: + flag = Py_NE + else: + raise ValueError('Unrecognized operator') + + result = np.empty(n, dtype=bool).view(np.uint8) + + if flag == Py_NE: + for i in range(n): + x = left[i] + y = right[i] + + if checknull(x) or checknull(y): + result[i] = True + else: + result[i] = PyObject_RichCompareBool(x, y, flag) + else: + for i in range(n): + x = left[i] + y = right[i] + + if checknull(x) or checknull(y): + result[i] = False + else: + result[i] = PyObject_RichCompareBool(x, y, flag) + + return result.view(bool) + + +@cython.wraparound(False) +@cython.boundscheck(False) +def scalar_binop(ndarray[object] values, object val, object op): + """ + Apply the given binary operator `op` between each element of the array + `values` and the scalar `val`. + + Parameters + ---------- + values : ndarray[object] + val : object + op : binary operator + + Returns + ------- + result : ndarray[object] + """ + cdef: + Py_ssize_t i, n = len(values) + ndarray[object] result + object x + + result = np.empty(n, dtype=object) + if _checknull(val): + result.fill(val) + return result + + for i in range(n): + x = values[i] + if _checknull(x): + result[i] = x + else: + result[i] = op(x, val) + + return maybe_convert_bool(result) + + +@cython.wraparound(False) +@cython.boundscheck(False) +def vec_binop(ndarray[object] left, ndarray[object] right, object op): + """ + Apply the given binary operator `op` pointwise to the elements of + arrays `left` and `right`. + + Parameters + ---------- + left : ndarray[object] + right : ndarray[object] + op : binary operator + + Returns + ------- + result : ndarray[object] + """ + cdef: + Py_ssize_t i, n = len(left) + ndarray[object] result + + if n != len(right): + raise ValueError('Arrays were different lengths: %d vs %d' + % (n, len(right))) + + result = np.empty(n, dtype=object) + + for i in range(n): + x = left[i] + y = right[i] + try: + result[i] = op(x, y) + except TypeError: + if _checknull(x): + result[i] = x + elif _checknull(y): + result[i] = y + else: + raise + + return maybe_convert_bool(result) + + +def maybe_convert_bool(ndarray[object] arr, + true_values=None, false_values=None): + cdef: + Py_ssize_t i, n + ndarray[uint8_t] result + object val + set true_vals, false_vals + int na_count = 0 + + n = len(arr) + result = np.empty(n, dtype=np.uint8) + + # the defaults + true_vals = set(('True', 'TRUE', 'true')) + false_vals = set(('False', 'FALSE', 'false')) + + if true_values is not None: + true_vals = true_vals | set(true_values) + + if false_values is not None: + false_vals = false_vals | set(false_values) + + for i from 0 <= i < n: + val = arr[i] + + if PyBool_Check(val): + if val is True: + result[i] = 1 + else: + result[i] = 0 + elif val in true_vals: + result[i] = 1 + elif val in false_vals: + result[i] = 0 + elif PyFloat_Check(val): + result[i] = UINT8_MAX + na_count += 1 + else: + return arr + + if na_count > 0: + mask = result == UINT8_MAX + arr = result.view(np.bool_).astype(object) + np.putmask(arr, mask, np.nan) + return arr + else: + return result.view(np.bool_) diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx index 75bff34e4a391..1fa07dbed6822 100644 --- a/pandas/_libs/src/inference.pyx +++ b/pandas/_libs/src/inference.pyx @@ -752,7 +752,7 @@ cdef class IntegerFloatValidator(Validator): return issubclass(self.dtype.type, np.integer) -cpdef bint is_integer_float_array(ndarray values): +cdef bint is_integer_float_array(ndarray values): cdef: IntegerFloatValidator validator = IntegerFloatValidator( len(values), @@ -803,7 +803,7 @@ cdef class UnicodeValidator(Validator): return issubclass(self.dtype.type, np.unicode_) -cpdef bint is_unicode_array(ndarray values, bint skipna=False): +cdef bint is_unicode_array(ndarray values, bint skipna=False): cdef: UnicodeValidator validator = UnicodeValidator( len(values), @@ -822,7 +822,7 @@ cdef class BytesValidator(Validator): return issubclass(self.dtype.type, np.bytes_) -cpdef bint is_bytes_array(ndarray values, bint skipna=False): +cdef bint is_bytes_array(ndarray values, bint skipna=False): cdef: BytesValidator validator = BytesValidator( len(values), @@ -1090,7 +1090,7 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, cdef: int status, maybe_int Py_ssize_t i, n = values.size - Seen seen = Seen(coerce_numeric); + Seen seen = Seen(coerce_numeric) ndarray[float64_t] floats = np.empty(n, dtype='f8') ndarray[complex128_t] complexes = np.empty(n, dtype='c16') ndarray[int64_t] ints = np.empty(n, dtype='i8') @@ -1224,7 +1224,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0, ndarray[uint8_t] bools ndarray[int64_t] idatetimes ndarray[int64_t] itimedeltas - Seen seen = Seen(); + Seen seen = Seen() object val, onan float64_t fval, fnan @@ -1405,55 +1405,6 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0, return objects -def maybe_convert_bool(ndarray[object] arr, - true_values=None, false_values=None): - cdef: - Py_ssize_t i, n - ndarray[uint8_t] result - object val - set true_vals, false_vals - int na_count = 0 - - n = len(arr) - result = np.empty(n, dtype=np.uint8) - - # the defaults - true_vals = set(('True', 'TRUE', 'true')) - false_vals = set(('False', 'FALSE', 'false')) - - if true_values is not None: - true_vals = true_vals | set(true_values) - - if false_values is not None: - false_vals = false_vals | set(false_values) - - for i from 0 <= i < n: - val = arr[i] - - if cpython.PyBool_Check(val): - if val is True: - result[i] = 1 - else: - result[i] = 0 - elif val in true_vals: - result[i] = 1 - elif val in false_vals: - result[i] = 0 - elif PyFloat_Check(val): - result[i] = UINT8_MAX - na_count += 1 - else: - return arr - - if na_count > 0: - mask = result == UINT8_MAX - arr = result.view(np.bool_).astype(object) - np.putmask(arr, mask, np.nan) - return arr - else: - return result.view(np.bool_) - - def map_infer_mask(ndarray arr, object f, ndarray[uint8_t] mask, bint convert=1): """ diff --git a/pandas/_libs/src/util.pxd b/pandas/_libs/src/util.pxd index cf23df1279f34..5030b742849f8 100644 --- a/pandas/_libs/src/util.pxd +++ b/pandas/_libs/src/util.pxd @@ -164,22 +164,3 @@ cdef inline bint _checknan(object val): cdef inline bint is_period_object(object val): return getattr(val, '_typ', '_typ') == 'period' - - -cdef inline object unbox_if_zerodim(object arr): - """ - If arr is zerodim array, return a proper array scalar (e.g. np.int64). - Otherwise, return arr as is. - - Parameters - ---------- - arr : object - - Returns - ------- - result : object - """ - if cnp.PyArray_IsZeroDim(arr): - return cnp.PyArray_ToScalar(cnp.PyArray_DATA(arr), arr) - else: - return arr diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index beaca1a8483c7..4726bd7ea3629 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -543,7 +543,6 @@ cdef inline void localize_tso(_TSObject obj, tzinfo tz): ndarray[int64_t] trans, deltas int64_t delta, local_val Py_ssize_t posn - datetime dt assert obj.tzinfo is None @@ -679,7 +678,6 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): Py_ssize_t pos int64_t v, offset, utc_date pandas_datetimestruct dts - datetime dt # See GH#17734 We should always be converting either from UTC or to UTC assert (is_utc(tz1) or tz1 == 'UTC') or (is_utc(tz2) or tz2 == 'UTC') @@ -739,7 +737,6 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): ndarray[Py_ssize_t] posn int64_t v, offset, delta pandas_datetimestruct dts - datetime dt if len(vals) == 0: return np.array([], dtype=np.int64) @@ -844,7 +841,6 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, object ambiguous=None, pandas_datetimestruct dts bint infer_dst = False, is_dst = False, fill = False bint is_coerce = errors == 'coerce', is_raise = errors == 'raise' - datetime dt # Vectorized version of DstTzInfo.localize @@ -1086,7 +1082,6 @@ cdef ndarray[int64_t] _normalize_local(ndarray[int64_t] stamps, object tz): ndarray[int64_t] result = np.empty(n, dtype=np.int64) ndarray[int64_t] trans, deltas, pos pandas_datetimestruct dts - datetime dt if is_utc(tz): with nogil: diff --git a/pandas/core/ops.py b/pandas/core/ops.py index b20f208d14dc5..f75e3d7df8237 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -11,7 +11,7 @@ import pandas as pd from pandas._libs import (lib, index as libindex, - algos as libalgos) + algos as libalgos, ops as libops) from pandas import compat from pandas.util._decorators import Appender @@ -1040,9 +1040,9 @@ def _comp_method_OBJECT_ARRAY(op, x, y): if isinstance(y, (ABCSeries, ABCIndex)): y = y.values - result = lib.vec_compare(x, y, op) + result = libops.vec_compare(x, y, op) else: - result = lib.scalar_compare(x, y, op) + result = libops.scalar_compare(x, y, op) return result @@ -1205,13 +1205,13 @@ def na_op(x, y): else: x = _ensure_object(x) y = _ensure_object(y) - result = lib.vec_binop(x, y, op) + result = libops.vec_binop(x, y, op) else: # let null fall thru if not isna(y): y = bool(y) try: - result = lib.scalar_binop(x, y, op) + result = libops.scalar_binop(x, y, op) except: raise TypeError("cannot compare a dtyped [{dtype}] array " "with a scalar of type [{typ}]" diff --git a/pandas/core/strings.py b/pandas/core/strings.py index b1c1ede66236c..ce688f8b16fe5 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -20,6 +20,7 @@ from pandas.util._decorators import Appender import re import pandas._libs.lib as lib +import pandas._libs.ops as libops import warnings import textwrap import codecs @@ -461,7 +462,7 @@ def rep(x, r): return compat.text_type.__mul__(x, r) repeats = np.asarray(repeats, dtype=object) - result = lib.vec_binop(com._values_from_object(arr), repeats, rep) + result = libops.vec_binop(com._values_from_object(arr), repeats, rep) return result diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 4b1385514a0c4..469cd6d82e4b4 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -43,6 +43,7 @@ import pandas._libs.lib as lib import pandas._libs.parsers as parsers +import pandas._libs.ops as libops from pandas._libs.tslibs import parsing # BOM character (byte order mark) @@ -1616,9 +1617,9 @@ def _infer_types(self, values, na_values, try_num_bool=True): na_count = parsers.sanitize_objects(values, na_values, False) if result.dtype == np.object_ and try_num_bool: - result = lib.maybe_convert_bool(values, - true_values=self.true_values, - false_values=self.false_values) + result = libops.maybe_convert_bool(values, + true_values=self.true_values, + false_values=self.false_values) return result, na_count diff --git a/setup.py b/setup.py index c7784260d79ca..7fb5358d0950b 100755 --- a/setup.py +++ b/setup.py @@ -313,6 +313,7 @@ class CheckSDist(sdist_class): 'pandas/_libs/testing.pyx', 'pandas/_libs/skiplist.pyx', 'pandas/_libs/sparse.pyx', + 'pandas/_libs/ops.pyx', 'pandas/_libs/parsers.pyx', 'pandas/_libs/tslibs/ccalendar.pyx', 'pandas/_libs/tslibs/period.pyx', @@ -525,6 +526,10 @@ def pxd(name): '_libs.reduction': { 'pyxfile': '_libs/reduction', 'pxdfiles': ['_libs/src/util']}, + '_libs.ops': { + 'pyxfile': '_libs/ops', + 'pxdfiles': ['_libs/src/util', + '_libs/missing']}, '_libs.tslibs.period': { 'pyxfile': '_libs/tslibs/period', 'pxdfiles': ['_libs/src/util',
Moves a few functions only ever used in groupby/index to libgroupby and libindex, respectively.
https://api.github.com/repos/pandas-dev/pandas/pulls/19887
2018-02-24T21:42:55Z
2018-02-28T00:11:48Z
2018-02-28T00:11:48Z
2018-06-22T03:29:25Z
ENH: Let initialisation from dicts use insertion order for python >= 3.6 (part III)
diff --git a/doc/source/dsintro.rst b/doc/source/dsintro.rst index 1ba00b8fb6f23..ca6cefac9e842 100644 --- a/doc/source/dsintro.rst +++ b/doc/source/dsintro.rst @@ -81,9 +81,28 @@ index is passed, one will be created having values ``[0, ..., len(data) - 1]``. **From dict** -If ``data`` is a dict, if **index** is passed the values in data corresponding -to the labels in the index will be pulled out. Otherwise, an index will be -constructed from the sorted keys of the dict, if possible. +Series can be instantiated from dicts: + +.. ipython:: python + + d = {'b' : 1, 'a' : 0, 'c' : 2} + pd.Series(d) + +.. note:: + + When the data is a dict, and an index is not passed, the ``Series`` index + will be ordered by the dict's insertion order, if you're using Python + version >= 3.6 and Pandas version >= 0.23. + + If you're using Python < 3.6 or Pandas < 0.23, and an index is not passed, + the ``Series`` index will be the lexically ordered list of dict keys. + +In the example above, if you were on a Python version lower than 3.6 or a +Pandas version lower than 0.23, the ``Series`` would be ordered by the lexical +order of the dict keys (i.e. ``['a', 'b', 'c']`` rather than ``['b', 'a', 'c']``). + +If an index is passed, the values in data corresponding to the labels in the +index will be pulled out. .. ipython:: python @@ -243,12 +262,22 @@ not matching up to the passed index. If axis labels are not passed, they will be constructed from the input data based on common sense rules. +.. note:: + + When the data is a dict, and ``columns`` is not specified, the ``DataFrame`` + columns will be ordered by the dict's insertion order, if you are using + Python version >= 3.6 and Pandas >= 0.23. + + If you are using Python < 3.6 or Pandas < 0.23, and ``columns`` is not + specified, the ``DataFrame`` columns will be the lexically ordered list of dict + keys. + From dict of Series or dicts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The resulting **index** will be the **union** of the indexes of the various Series. If there are any nested dicts, these will first be converted to -Series. If no columns are passed, the columns will be the sorted list of dict +Series. If no columns are passed, the columns will be the ordered list of dict keys. .. ipython:: python diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 7a19f87051746..cf2a5de583878 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -3,7 +3,7 @@ v0.23.0 ------- -This is a major release from 0.21.1 and includes a number of API changes, +This is a major release from 0.22.0 and includes a number of API changes, deprecations, new features, enhancements, and performance improvements along with a large number of bug fixes. We recommend that all users upgrade to this version. @@ -249,7 +249,7 @@ The :func:`DataFrame.assign` now accepts dependent keyword arguments for python using ``.assign()`` to update an existing column. Previously, callables referring to other variables being updated would get the "old" values - Previous Behaviour: + Previous Behavior: .. code-block:: ipython @@ -262,7 +262,7 @@ The :func:`DataFrame.assign` now accepts dependent keyword arguments for python 1 3 -2 2 4 -3 - New Behaviour: + New Behavior: .. ipython:: python @@ -361,6 +361,57 @@ If installed, we now require: | openpyxl | 2.4.0 | | +-----------------+-----------------+----------+ +.. _whatsnew_0230.api_breaking.dict_insertion_order: + +Instantation from dicts preserves dict insertion order for python 3.6+ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Until Python 3.6, dicts in Python had no formally defined ordering. For Python +version 3.6 and later, dicts are ordered by insertion order, see +`PEP 468 <https://www.python.org/dev/peps/pep-0468/>`_. +Pandas will use the dict's insertion order, when creating a ``Series`` or +``DataFrame`` from a dict and you're using Python version 3.6 or +higher. (:issue:`19884`) + +Previous Behavior (and current behavior if on Python < 3.6): + +.. code-block:: ipython + + In [1]: pd.Series({'Income': 2000, + ... 'Expenses': -1500, + ... 'Taxes': -200, + ... 'Net result': 300}) + Expenses -1500 + Income 2000 + Net result 300 + Taxes -200 + dtype: int64 + +Note the Series above is ordered alphabetically by the index values. + +New Behavior (for Python >= 3.6): + +.. ipython:: python + + pd.Series({'Income': 2000, + 'Expenses': -1500, + 'Taxes': -200, + 'Net result': 300}) + +Notice that the Series is now ordered by insertion order. This new behavior is +used for all relevant pandas types (``Series``, ``DataFrame``, ``SparseSeries`` +and ``SparseDataFrame``). + +If you wish to retain the old behavior while using Python >= 3.6, you can use +``.sort_index()``: + +.. ipython:: python + + pd.Series({'Income': 2000, + 'Expenses': -1500, + 'Taxes': -200, + 'Net result': 300}).sort_index() + .. _whatsnew_0230.api_breaking.deprecate_panel: Deprecate Panel diff --git a/pandas/core/common.py b/pandas/core/common.py index c4fbcf28cbcae..c4890dbd39ef1 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -11,7 +11,7 @@ from pandas._libs import lib, tslib from pandas import compat -from pandas.compat import long, zip, iteritems +from pandas.compat import long, zip, iteritems, PY36, OrderedDict from pandas.core.config import get_option from pandas.core.dtypes.generic import ABCSeries, ABCIndex from pandas.core.dtypes.common import _NS_DTYPE @@ -186,6 +186,16 @@ def _try_sort(iterable): return listed +def _dict_keys_to_ordered_list(mapping): + # when pandas drops support for Python < 3.6, this function + # can be replaced by a simple list(mapping.keys()) + if PY36 or isinstance(mapping, OrderedDict): + keys = list(mapping.keys()) + else: + keys = _try_sort(mapping) + return keys + + def iterpairs(seq): """ Parameters diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ae8fb48a61fce..ff4064b3f8c56 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -252,6 +252,11 @@ class DataFrame(NDFrame): ---------- data : numpy ndarray (structured or homogeneous), dict, or DataFrame Dict can contain Series, arrays, constants, or list-like objects + + .. versionchanged :: 0.23.0 + If data is a dict, argument order is maintained for Python 3.6 + and later. + index : Index or array-like Index to use for resulting frame. Will default to RangeIndex if no indexing information part of input data and no index provided @@ -460,9 +465,7 @@ def _init_dict(self, data, index, columns, dtype=None): arrays.append(v) else: - keys = list(data.keys()) - if not isinstance(data, OrderedDict): - keys = com._try_sort(keys) + keys = com._dict_keys_to_ordered_list(data) columns = data_names = Index(keys) arrays = [data[k] for k in keys] diff --git a/pandas/core/panel.py b/pandas/core/panel.py index fc7fad861df44..052d555df76f1 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -204,10 +204,8 @@ def _init_dict(self, data, axes, dtype=None): for k, v in compat.iteritems(data) if k in haxis) else: - ks = list(data.keys()) - if not isinstance(data, OrderedDict): - ks = com._try_sort(ks) - haxis = Index(ks) + keys = com._dict_keys_to_ordered_list(data) + haxis = Index(keys) for k, v in compat.iteritems(data): if isinstance(v, dict): diff --git a/pandas/core/series.py b/pandas/core/series.py index 660bf3f5d4805..069f0372ab6e1 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -54,7 +54,7 @@ from pandas import compat from pandas.io.formats.terminal import get_terminal_size from pandas.compat import ( - zip, u, OrderedDict, StringIO, range, get_range_parameters) + zip, u, OrderedDict, StringIO, range, get_range_parameters, PY36) from pandas.compat.numpy import function as nv import pandas.core.ops as ops @@ -130,6 +130,11 @@ class Series(base.IndexOpsMixin, generic.NDFrame): ---------- data : array-like, dict, or scalar value Contains data stored in Series + + .. versionchanged :: 0.23.0 + If data is a dict, argument order is maintained for Python 3.6 + and later. + index : array-like or Index (1d) Values must be hashable and have the same length as `data`. Non-unique index values are allowed. Will default to @@ -297,7 +302,7 @@ def _init_dict(self, data, index=None, dtype=None): # Now we just make sure the order is respected, if any if index is not None: s = s.reindex(index, copy=False) - elif not isinstance(data, OrderedDict): + elif not PY36 and not isinstance(data, OrderedDict): try: s = s.sort_index() except TypeError: diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py index d89b1d681c478..2cefbea722098 100644 --- a/pandas/core/sparse/frame.py +++ b/pandas/core/sparse/frame.py @@ -39,6 +39,10 @@ class SparseDataFrame(DataFrame): Parameters ---------- data : same types as can be passed to DataFrame or scipy.sparse.spmatrix + .. versionchanged :: 0.23.0 + If data is a dict, argument order is maintained for Python 3.6 + and later. + index : array-like, optional column : array-like, optional default_kind : {'block', 'integer'}, default 'block' @@ -138,7 +142,8 @@ def _init_dict(self, data, index, columns, dtype=None): columns = _ensure_index(columns) data = {k: v for k, v in compat.iteritems(data) if k in columns} else: - columns = Index(com._try_sort(list(data.keys()))) + keys = com._dict_keys_to_ordered_list(data) + columns = Index(keys) if index is None: index = extract_index(list(data.values())) diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py index f8b98a1a40081..714cd09a27294 100644 --- a/pandas/core/sparse/series.py +++ b/pandas/core/sparse/series.py @@ -42,6 +42,10 @@ class SparseSeries(Series): Parameters ---------- data : {array-like, Series, SparseSeries, dict} + .. versionchanged :: 0.23.0 + If data is a dict, argument order is maintained for Python 3.6 + and later. + kind : {'block', 'integer'} fill_value : float Code for missing value. Defaults depends on dtype. diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index e0b94815878dd..499751e864331 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -15,7 +15,7 @@ from pandas.core.dtypes.common import is_integer_dtype from pandas.compat import (lmap, long, zip, range, lrange, lzip, - OrderedDict, is_platform_little_endian) + OrderedDict, is_platform_little_endian, PY36) from pandas import compat from pandas import (DataFrame, Index, Series, isna, MultiIndex, Timedelta, Timestamp, @@ -290,6 +290,24 @@ def test_constructor_dict(self): with tm.assert_raises_regex(ValueError, msg): DataFrame({'a': 0.7}, columns=['b']) + @pytest.mark.skipif(not PY36, reason='Insertion order for Python>=3.6') + def test_constructor_dict_order_insertion(self): + # GH19018 + # initialization ordering: by insertion order if python>= 3.6 + d = {'b': self.ts2, 'a': self.ts1} + frame = DataFrame(data=d) + expected = DataFrame(data=d, columns=list('ba')) + tm.assert_frame_equal(frame, expected) + + @pytest.mark.skipif(PY36, reason='order by value for Python<3.6') + def test_constructor_dict_order_by_values(self): + # GH19018 + # initialization ordering: by value if python<3.6 + d = {'b': self.ts2, 'a': self.ts1} + frame = DataFrame(data=d) + expected = DataFrame(data=d, columns=list('ab')) + tm.assert_frame_equal(frame, expected) + def test_constructor_multi_index(self): # GH 4078 # construction error with mi and all-nan frame diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index 15d3062394d6e..0b80af11520b5 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -762,17 +762,17 @@ def test_read_excel_multiindex_empty_level(self, ext): # GH 12453 with ensure_clean('.xlsx') as path: df = DataFrame({ - ('Zero', ''): {0: 0}, ('One', 'x'): {0: 1}, ('Two', 'X'): {0: 3}, - ('Two', 'Y'): {0: 7} + ('Two', 'Y'): {0: 7}, + ('Zero', ''): {0: 0} }) expected = DataFrame({ - ('Zero', 'Unnamed: 3_level_1'): {0: 0}, ('One', u'x'): {0: 1}, ('Two', u'X'): {0: 3}, - ('Two', u'Y'): {0: 7} + ('Two', u'Y'): {0: 7}, + ('Zero', 'Unnamed: 3_level_1'): {0: 0} }) df.to_excel(path) diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 04da6da74059b..e690b1e302d8b 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -2034,7 +2034,7 @@ def test_table_values_dtypes_roundtrip(self): 'bool': 1, 'int16': 1, 'int8': 1, 'int64': 1, 'object': 1, 'datetime64[ns]': 2}) result = result.sort_index() - result = expected.sort_index() + expected = expected.sort_index() tm.assert_series_equal(result, expected) def test_table_mixed_dtypes(self): diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 25f425ffa0021..e0bfe41645a3f 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -22,7 +22,7 @@ from pandas._libs import lib from pandas._libs.tslib import iNaT -from pandas.compat import lrange, range, zip, long +from pandas.compat import lrange, range, zip, long, PY36 from pandas.util.testing import assert_series_equal import pandas.util.testing as tm @@ -811,6 +811,18 @@ def test_constructor_dict(self): expected.iloc[1] = 1 assert_series_equal(result, expected) + def test_constructor_dict_order(self): + # GH19018 + # initialization ordering: by insertion order if python>= 3.6, else + # order by value + d = {'b': 1, 'a': 0, 'c': 2} + result = Series(d) + if PY36: + expected = Series([1, 0, 2], index=list('bac')) + else: + expected = Series([0, 1, 2], index=list('abc')) + tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("value", [2, np.nan, None, float('nan')]) def test_constructor_dict_nan_key(self, value): # GH 18480 diff --git a/pandas/tests/sparse/frame/test_frame.py b/pandas/tests/sparse/frame/test_frame.py index ee0d63aff7367..1062de3119efc 100644 --- a/pandas/tests/sparse/frame/test_frame.py +++ b/pandas/tests/sparse/frame/test_frame.py @@ -139,6 +139,18 @@ def test_constructor(self): repr(self.frame) + def test_constructor_dict_order(self): + # GH19018 + # initialization ordering: by insertion order if python>= 3.6, else + # order by value + d = {'b': [2, 3], 'a': [0, 1]} + frame = SparseDataFrame(data=d) + if compat.PY36: + expected = SparseDataFrame(data=d, columns=list('ba')) + else: + expected = SparseDataFrame(data=d, columns=list('ab')) + tm.assert_sp_frame_equal(frame, expected) + def test_constructor_ndarray(self): # no index or columns sp = SparseDataFrame(self.frame.values) diff --git a/pandas/tests/sparse/series/test_series.py b/pandas/tests/sparse/series/test_series.py index 3f5d5a59cc540..eb63c87820070 100644 --- a/pandas/tests/sparse/series/test_series.py +++ b/pandas/tests/sparse/series/test_series.py @@ -14,7 +14,7 @@ from pandas.tseries.offsets import BDay import pandas.util.testing as tm import pandas.util._test_decorators as td -from pandas.compat import range +from pandas.compat import range, PY36 from pandas.core.reshape.util import cartesian_product import pandas.core.sparse.frame as spf @@ -114,6 +114,18 @@ def test_constructor_dict_input(self): result = SparseSeries(constructor_dict) tm.assert_sp_series_equal(result, expected) + def test_constructor_dict_order(self): + # GH19018 + # initialization ordering: by insertion order if python>= 3.6, else + # order by value + d = {'b': 1, 'a': 0, 'c': 2} + result = SparseSeries(d) + if PY36: + expected = SparseSeries([1, 0, 2], index=list('bac')) + else: + expected = SparseSeries([0, 1, 2], index=list('abc')) + tm.assert_sp_series_equal(result, expected) + def test_constructor_dtype(self): arr = SparseSeries([np.nan, 1, 2, np.nan]) assert arr.dtype == np.float64 diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 1955fc301be9b..301a7fc437fcf 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -2368,14 +2368,16 @@ def test_update_from_dict(self): pan.update(other) expected = Panel( - {'two': DataFrame([[3.6, 2., 3], - [1.5, np.nan, 7], - [1.5, np.nan, 3.], - [1.5, np.nan, 3.]]), - 'one': DataFrame([[1.5, np.nan, 3.], + {'one': DataFrame([[1.5, np.nan, 3.], [1.5, np.nan, 3.], [1.5, np.nan, 3.], - [1.5, np.nan, 3.]])}) + [1.5, np.nan, 3.]]), + 'two': DataFrame([[3.6, 2., 3], + [1.5, np.nan, 7], + [1.5, np.nan, 3.], + [1.5, np.nan, 3.]]) + } + ) assert_panel_equal(pan, expected)
- [x] closes #19018 - [x] xref #19830 and #19859 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` This PR lets pandas allow initialisation using insertion order for python>=3.6. E.g. ``Series({'B': 1, 'A': 2})`` will retain order and not convert to ``Series({'A': 2, 'B': 1})``. As such this changes the API soemwhat fundamentally (but in a very good way, IMO). Some questions: * Should this change be at the top of the whatsnew, in order to increase visibility to this change? * Should an option be added to ``pd.options``, so user can revert back to the old behaviour? I'm thinking here of users who have made tests based on dict sort-by-values, and whose tests will break by this new change * Should there be a deprecation procedure, as asked by @gfyoung ? I also need to look thorugh the documentation if changes should be made there, but would appreciate getting the basic PR approved first.
https://api.github.com/repos/pandas-dev/pandas/pulls/19884
2018-02-24T17:10:42Z
2018-03-02T11:19:08Z
2018-03-02T11:19:07Z
2018-03-02T12:14:37Z
COMPAT: fixup decimal extension for indexing compat
diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index 31ed8b9e01225..566ba1721d13c 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -18,7 +18,8 @@ def test_iloc_series(self, data): self.assert_series_equal(result, expected) def test_iloc_frame(self, data): - df = pd.DataFrame({"A": data, 'B': np.arange(len(data))}) + df = pd.DataFrame({"A": data, 'B': + np.arange(len(data), dtype='int64')}) expected = pd.DataFrame({"A": data[:4]}) # slice -> frame @@ -49,7 +50,8 @@ def test_loc_series(self, data): self.assert_series_equal(result, expected) def test_loc_frame(self, data): - df = pd.DataFrame({"A": data, 'B': np.arange(len(data))}) + df = pd.DataFrame({"A": data, + 'B': np.arange(len(data), dtype='int64')}) expected = pd.DataFrame({"A": data[:4]}) # slice -> frame diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index f526ac5996a10..8b2eaadeca99e 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -8,6 +8,7 @@ import pandas as pd from pandas.core.arrays import ExtensionArray from pandas.core.dtypes.base import ExtensionDtype +from pandas.core.dtypes.common import _ensure_platform_int class DecimalDtype(ExtensionDtype): @@ -68,6 +69,7 @@ def isna(self): def take(self, indexer, allow_fill=True, fill_value=None): mask = indexer == -1 + indexer = _ensure_platform_int(indexer) out = self.values.take(indexer) out[mask] = self._na_value
https://api.github.com/repos/pandas-dev/pandas/pulls/19882
2018-02-24T15:38:30Z
2018-02-24T17:21:03Z
2018-02-24T17:21:03Z
2018-02-24T17:21:03Z
Include MultiIndex slice in non-reducing slices
diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index 1fe5e4e6e7087..da1ea62e6f49a 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -1538,6 +1538,7 @@ Missing MultiIndex ^^^^^^^^^^ +- Bug in :func:`io.formats.style.Styler.applymap` where ``subset=`` with :class:`MultiIndex` slice would reduce to :class:`Series` (:issue:`19861`) - Removed compatibility for :class:`MultiIndex` pickles prior to version 0.8.0; compatibility with :class:`MultiIndex` pickles from version 0.13 forward is maintained (:issue:`21654`) - :meth:`MultiIndex.get_loc_level` (and as a consequence, ``.loc`` on a ``Series`` or ``DataFrame`` with a :class:`MultiIndex` index) will now raise a ``KeyError``, rather than returning an empty ``slice``, if asked a label which is present in the ``levels`` but is unused (:issue:`22221`) - :class:`MultiIndex` has gained the :meth:`MultiIndex.from_frame`, it allows constructing a :class:`MultiIndex` object from a :class:`DataFrame` (:issue:`22420`) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index ab4ad693a462e..3504c6e12b896 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2732,8 +2732,10 @@ def _non_reducing_slice(slice_): slice_ = IndexSlice[:, slice_] def pred(part): - # true when slice does *not* reduce - return isinstance(part, slice) or is_list_like(part) + # true when slice does *not* reduce, False when part is a tuple, + # i.e. MultiIndex slice + return ((isinstance(part, slice) or is_list_like(part)) + and not isinstance(part, tuple)) if not is_list_like(slice_): if not isinstance(slice_, slice): diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 03f1975c50d2a..2224c3ab9935a 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -812,6 +812,23 @@ def test_non_reducing_slice(self): tslice_ = _non_reducing_slice(slice_) assert isinstance(df.loc[tslice_], DataFrame) + def test_non_reducing_slice_on_multiindex(self): + # GH 19861 + dic = { + ('a', 'd'): [1, 4], + ('a', 'c'): [2, 3], + ('b', 'c'): [3, 2], + ('b', 'd'): [4, 1] + } + df = pd.DataFrame(dic, index=[0, 1]) + idx = pd.IndexSlice + slice_ = idx[:, idx['b', 'd']] + tslice_ = _non_reducing_slice(slice_) + + result = df.loc[tslice_] + expected = pd.DataFrame({('b', 'd'): [4, 1]}) + tm.assert_frame_equal(result, expected) + def test_list_slice(self): # like dataframe getitem slices = [['A'], Series(['A']), np.array(['A'])] diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index fa8bd91dce939..3432d686a9fd6 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -274,6 +274,32 @@ def f(x): col in self.df.loc[slice_].columns} assert result == expected + def test_applymap_subset_multiindex(self): + # GH 19861 + # Smoke test for applymap + def color_negative_red(val): + """ + Takes a scalar and returns a string with + the css property `'color: red'` for negative + strings, black otherwise. + """ + color = 'red' if val < 0 else 'black' + return 'color: %s' % color + + dic = { + ('a', 'd'): [-1.12, 2.11], + ('a', 'c'): [2.78, -2.88], + ('b', 'c'): [-3.99, 3.77], + ('b', 'd'): [4.21, -1.22], + } + + idx = pd.IndexSlice + df = pd.DataFrame(dic, index=[0, 1]) + + (df.style + .applymap(color_negative_red, subset=idx[:, idx['b', 'd']]) + .render()) + def test_where_with_one_style(self): # GH 17474 def f(x):
Changes behaviour of user-passed IndexSlice to return DataFrame instead of reducing to Series. MultiIndex slices are tuples so this explicitly checks type and guards with braces. This seems deceptively simple. WDYT? - [x] closes #19861 - [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/19881
2018-02-24T15:22:36Z
2019-01-02T01:15:58Z
2019-01-02T01:15:58Z
2019-01-02T09:40:42Z
CLN: remove obsolete code in Categorical.fillna
diff --git a/.gitignore b/.gitignore index 4bbbcad0c97ad..96b1f945870de 100644 --- a/.gitignore +++ b/.gitignore @@ -61,6 +61,7 @@ dist .coverage coverage.xml coverage_html_report +*.pytest_cache # OS generated files # ###################### @@ -90,7 +91,6 @@ scikits # Unit / Performance Testing # ############################## -.pytest_cache/ asv_bench/env/ asv_bench/html/ asv_bench/results/ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index b37f88d8bfdce..1e5e2d1163060 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1627,14 +1627,6 @@ def fillna(self, value=None, method=None, limit=None): values = self._codes - # Make sure that we also get NA in categories - if self.categories.dtype.kind in ['S', 'O', 'f']: - if np.nan in self.categories: - values = values.copy() - nan_pos = np.where(isna(self.categories))[0] - # we only have one NA in categories - values[values == nan_pos] = -1 - # pad / bfill if method is not None:
closes #19787 - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Deleted code and tested block of code associated with NaN that should be unreachable.
https://api.github.com/repos/pandas-dev/pandas/pulls/19880
2018-02-24T08:54:13Z
2018-03-15T23:02:40Z
2018-03-15T23:02:40Z
2018-03-15T23:02:44Z
Fixed issue with leftover test.json file
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index ba24c93121dcb..c6156c5310e99 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -214,13 +214,22 @@ Please note that the string `index` is not supported with the round trip format, :okwarning: df.index.name = 'index' + df.to_json('test.json', orient='table') new_df = pd.read_json('test.json', orient='table') new_df - print(new_df.index.name) + new_df.dtypes + +.. ipython:: python + :suppress: + + import os + os.remove('test.json') + .. _whatsnew_0230.enhancements.assign_dependent: + ``.assign()`` accepts dependent arguments ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- [ ] closes #19815 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/19879
2018-02-24T07:56:42Z
2018-02-25T16:17:11Z
2018-02-25T16:17:10Z
2018-02-25T16:17:13Z
DOC: misc. typos
diff --git a/doc/source/basics.rst b/doc/source/basics.rst index 749d4be11ad45..e1b36a6acad70 100644 --- a/doc/source/basics.rst +++ b/doc/source/basics.rst @@ -2312,4 +2312,4 @@ All NumPy dtypes are subclasses of ``numpy.generic``: .. note:: Pandas also defines the types ``category``, and ``datetime64[ns, tz]``, which are not integrated into the normal - NumPy hierarchy and wont show up with the above function. + NumPy hierarchy and won't show up with the above function. diff --git a/doc/source/dsintro.rst b/doc/source/dsintro.rst index 582750b16f40d..e8f73a9ec2e8a 100644 --- a/doc/source/dsintro.rst +++ b/doc/source/dsintro.rst @@ -539,7 +539,7 @@ To write code compatible with all versions of Python, split the assignment in tw you'll need to take care when passing ``assign`` expressions that * Updating an existing column - * Refering to the newly updated column in the same ``assign`` + * Referring to the newly updated column in the same ``assign`` For example, we'll update column "A" and then refer to it when creating "B". diff --git a/doc/source/whatsnew/v0.14.1.txt b/doc/source/whatsnew/v0.14.1.txt index d8a6dc1793612..4674cbc846722 100644 --- a/doc/source/whatsnew/v0.14.1.txt +++ b/doc/source/whatsnew/v0.14.1.txt @@ -145,7 +145,7 @@ Performance ~~~~~~~~~~~ - Improvements in dtype inference for numeric operations involving yielding performance gains for dtypes: ``int64``, ``timedelta64``, ``datetime64`` (:issue:`7223`) - Improvements in Series.transform for significant performance gains (:issue:`6496`) -- Improvements in DataFrame.transform with ufuncs and built-in grouper functions for signifcant performance gains (:issue:`7383`) +- Improvements in DataFrame.transform with ufuncs and built-in grouper functions for significant performance gains (:issue:`7383`) - Regression in groupby aggregation of datetime64 dtypes (:issue:`7555`) - Improvements in `MultiIndex.from_product` for large iterables (:issue:`7627`) diff --git a/pandas/_libs/groupby_helper.pxi.in b/pandas/_libs/groupby_helper.pxi.in index 93fbb4477e2d0..e03e3af65755b 100644 --- a/pandas/_libs/groupby_helper.pxi.in +++ b/pandas/_libs/groupby_helper.pxi.in @@ -426,7 +426,7 @@ def group_rank_{{name}}(ndarray[float64_t, ndim=2] out, labels : array containing unique label for each group, with its ordering matching up to the corresponding record in `values` is_datetimelike : bool - unused in this method but provided for call compatability with other + unused in this method but provided for call compatibility with other Cython transformations ties_method : {'keep', 'top', 'bottom'} * keep: leave NA values where they are diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 493b2e5bd899b..c6eeabf0148d0 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -521,7 +521,7 @@ def _from_inferred_categories(cls, inferred_categories, inferred_codes, cats = to_timedelta(inferred_categories, errors='coerce') if known_categories: - # recode from observation oder to dtype.categories order + # recode from observation order to dtype.categories order categories = dtype.categories codes = _recode_for_categories(inferred_codes, cats, categories) elif not cats.is_monotonic_increasing: diff --git a/pandas/core/internals.py b/pandas/core/internals.py index bad0626206e80..d385185fbb558 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -2600,12 +2600,12 @@ def __init__(self, values, placement, ndim=None): def _maybe_coerce_values(self, values): """Input validation for values passed to __init__. Ensure that - we have datetime64ns, coercing if nescessary. + we have datetime64ns, coercing if necessary. Parametetrs ----------- values : array-like - Must be convertable to datetime64 + Must be convertible to datetime64 Returns ------- @@ -2760,12 +2760,12 @@ def __init__(self, values, placement, ndim=2, dtype=None): def _maybe_coerce_values(self, values, dtype=None): """Input validation for values passed to __init__. Ensure that - we have datetime64TZ, coercing if nescessary. + we have datetime64TZ, coercing if necessary. Parametetrs ----------- values : array-like - Must be convertable to datetime64 + Must be convertible to datetime64 dtype : string or DatetimeTZDtype, optional Does a shallow copy to this tz diff --git a/pandas/plotting/_converter.py b/pandas/plotting/_converter.py index 9ca06475290e4..f413e4177b386 100644 --- a/pandas/plotting/_converter.py +++ b/pandas/plotting/_converter.py @@ -197,7 +197,7 @@ def __call__(self, x, pos=0): ---------- x : float The time of day specified as seconds since 00:00 (midnight), - with upto microsecond precision. + with up to microsecond precision. pos Unused diff --git a/pandas/tests/extension/category/test_categorical.py b/pandas/tests/extension/category/test_categorical.py index ec548fca6d901..8f413b4a19730 100644 --- a/pandas/tests/extension/category/test_categorical.py +++ b/pandas/tests/extension/category/test_categorical.py @@ -60,7 +60,7 @@ def test_align_frame(self, data, na_value): class TestGetitem(base.BaseGetitemTests): - @pytest.mark.skip(reason="Backwards compatability") + @pytest.mark.skip(reason="Backwards compatibility") def test_getitem_scalar(self): # CategoricalDtype.type isn't "correct" since it should # be a parent of the elements (object). But don't want diff --git a/pandas/tests/extension/conftest.py b/pandas/tests/extension/conftest.py index f86849b9cbd61..21ed8894e8ebb 100644 --- a/pandas/tests/extension/conftest.py +++ b/pandas/tests/extension/conftest.py @@ -37,7 +37,7 @@ def na_cmp(): Should return a function of two arguments that returns True if both arguments are (scalar) NA for your type. - By defult, uses ``operator.or`` + By default, uses ``operator.or`` """ return operator.is_ diff --git a/pandas/tests/frame/test_mutate_columns.py b/pandas/tests/frame/test_mutate_columns.py index 4c560129bfa45..51ffe2966b4e5 100644 --- a/pandas/tests/frame/test_mutate_columns.py +++ b/pandas/tests/frame/test_mutate_columns.py @@ -95,7 +95,7 @@ def test_assign_bad(self): def test_assign_dependent_old_python(self): df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) - # Key C does not exist at defition time of df + # Key C does not exist at definition time of df with pytest.raises(KeyError): df.assign(C=lambda df: df.A, D=lambda df: df['A'] + df['C']) diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py index 8c46dc30a0f5f..3e5aae10618e9 100644 --- a/pandas/tests/frame/test_repr_info.py +++ b/pandas/tests/frame/test_repr_info.py @@ -307,7 +307,7 @@ def test_info_memory_usage(self): res = buf.getvalue().splitlines() assert "memory usage: " in res[-1] - # do not display memory usage cas + # do not display memory usage case df.info(buf=buf, memory_usage=False) res = buf.getvalue().splitlines() assert "memory usage: " not in res[-1] diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index 4c790a0f0f64a..86cee54665781 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -1786,7 +1786,7 @@ def roundtrip(df, header=True, parser_hdr=0, index=True): nrows = 5 ncols = 3 for use_headers in (True, False): - for i in range(1, 4): # row multindex upto nlevel=3 + for i in range(1, 4): # row multindex up to nlevel=3 for j in range(1, 4): # col "" df = mkdf(nrows, ncols, r_idx_nlevels=i, c_idx_nlevels=j) diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 4e259d0994bdb..49ad07b79d111 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -336,7 +336,7 @@ def test_read_write_dta10(self): with tm.ensure_clean() as path: original.to_stata(path, {'datetime': 'tc'}) written_and_read_again = self.read_dta(path) - # original.index is np.int32, readed index is np.int64 + # original.index is np.int32, read index is np.int64 tm.assert_frame_equal(written_and_read_again.set_index('index'), original, check_index_type=False) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 7e126dd56775b..cc4eb6b475ae5 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -473,7 +473,7 @@ def test_concat_categorical(self): tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - # completelly different categories (same dtype) => not-category + # completely different categories (same dtype) => not-category s1 = pd.Series([10, 11, np.nan], dtype='category') s2 = pd.Series([np.nan, 1, 3, 2], dtype='category') @@ -518,7 +518,7 @@ def test_concat_categorical_coercion(self): tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) - # completelly different categories => not-category + # completely different categories => not-category s1 = pd.Series([10, 11, np.nan], dtype='category') s2 = pd.Series([1, 3, 2]) diff --git a/pandas/tests/sparse/frame/test_frame.py b/pandas/tests/sparse/frame/test_frame.py index 0e8b2161cafc4..ee0d63aff7367 100644 --- a/pandas/tests/sparse/frame/test_frame.py +++ b/pandas/tests/sparse/frame/test_frame.py @@ -247,10 +247,10 @@ def test_constructor_preserve_attr(self): def test_constructor_nan_dataframe(self): # GH 10079 trains = np.arange(100) - tresholds = [10, 20, 30, 40, 50, 60] - tuples = [(i, j) for i in trains for j in tresholds] + thresholds = [10, 20, 30, 40, 50, 60] + tuples = [(i, j) for i in trains for j in thresholds] index = pd.MultiIndex.from_tuples(tuples, - names=['trains', 'tresholds']) + names=['trains', 'thresholds']) matrix = np.empty((len(index), len(trains))) matrix.fill(np.nan) df = pd.DataFrame(matrix, index=index, columns=trains, dtype=float)
Found via `codespell -q 3 -I ../pandas-whitelist.txt` Where whitelists consists of: ``` ans behaviour doubleclick indicies initialise initialised initialising nd resetted splitted thru valu ```
https://api.github.com/repos/pandas-dev/pandas/pulls/19876
2018-02-24T01:31:42Z
2018-02-24T13:26:06Z
2018-02-24T13:26:06Z
2018-03-11T15:29:29Z
Fixed pct_change with 'fill_method' returning NaN instead of 0
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index fd3c3a5a7a301..ed37892aeff9e 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -807,6 +807,7 @@ Numeric - Bug in :class:`Index` constructor with ``dtype='uint64'`` where int-like floats were not coerced to :class:`UInt64Index` (:issue:`18400`) - Bug in :class:`DataFrame` flex arithmetic (e.g. ``df.add(other, fill_value=foo)``) with a ``fill_value`` other than ``None`` failed to raise ``NotImplementedError`` in corner cases where either the frame or ``other`` has length zero (:issue:`19522`) - Multiplication and division of numeric-dtyped :class:`Index` objects with timedelta-like scalars returns ``TimedeltaIndex`` instead of raising ``TypeError`` (:issue:`19333`) +- Bug where ``NaN`` was returned instead of 0 by :func:`Series.pct_change` and :func:`DataFrame.pct_change` when ``fill_method`` is not ``None`` (provided) (:issue:`19873`) Indexing diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 85e2ce475ffa2..e1ed6ae9c8a6c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7488,7 +7488,7 @@ def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None, **kwargs)) - 1) rs = rs.reindex_like(data) if freq is None: - mask = isna(com._values_from_object(self)) + mask = isna(com._values_from_object(data)) np.putmask(rs.values, mask, np.nan) return rs diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index f2b8387072c8d..de4a132e0d613 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1941,12 +1941,9 @@ def test_pct_change(self): pnl.iat[1, 1] = np.nan pnl.iat[2, 3] = 60 - mask = pnl.isnull() - for axis in range(2): expected = pnl.ffill(axis=axis) / pnl.ffill(axis=axis).shift( axis=axis) - 1 - expected[mask] = np.nan result = pnl.pct_change(axis=axis, fill_method='pad') tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index 25dd285e883a0..9f94439a71a57 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -118,7 +118,7 @@ def test_pct_change_shift_over_nas(self): df = DataFrame({'a': s, 'b': s}) chg = df.pct_change() - expected = Series([np.nan, 0.5, np.nan, 2.5 / 1.5 - 1, .2]) + expected = Series([np.nan, 0.5, 0., 2.5 / 1.5 - 1, .2]) edf = DataFrame({'a': expected, 'b': expected}) assert_frame_equal(chg, edf) diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 3868bdf7d4620..311c71f734945 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -592,6 +592,26 @@ def test_copy_and_deepcopy(self): assert obj_copy is not obj self._compare(obj_copy, obj) + @pytest.mark.parametrize("periods,fill_method,limit,exp", [ + (1, "ffill", None, [np.nan, np.nan, np.nan, 1, 1, 1.5, 0, 0]), + (1, "ffill", 1, [np.nan, np.nan, np.nan, 1, 1, 1.5, 0, np.nan]), + (1, "bfill", None, [np.nan, 0, 0, 1, 1, 1.5, np.nan, np.nan]), + (1, "bfill", 1, [np.nan, np.nan, 0, 1, 1, 1.5, np.nan, np.nan]), + (-1, "ffill", None, [np.nan, np.nan, -.5, -.5, -.6, 0, 0, np.nan]), + (-1, "ffill", 1, [np.nan, np.nan, -.5, -.5, -.6, 0, np.nan, np.nan]), + (-1, "bfill", None, [0, 0, -.5, -.5, -.6, np.nan, np.nan, np.nan]), + (-1, "bfill", 1, [np.nan, 0, -.5, -.5, -.6, np.nan, np.nan, np.nan]) + ]) + def test_pct_change(self, periods, fill_method, limit, exp): + vals = [np.nan, np.nan, 1, 2, 4, 10, np.nan, np.nan] + obj = self._typ(vals) + func = getattr(obj, 'pct_change') + res = func(periods=periods, fill_method=fill_method, limit=limit) + if type(obj) is DataFrame: + tm.assert_frame_equal(res, DataFrame(exp)) + else: + tm.assert_series_equal(res, Series(exp)) + class TestNDFrame(object): # tests that don't fit elsewhere diff --git a/pandas/tests/generic/test_panel.py b/pandas/tests/generic/test_panel.py index 4cbd5cb2aa69f..49cb773a1bd10 100644 --- a/pandas/tests/generic/test_panel.py +++ b/pandas/tests/generic/test_panel.py @@ -45,7 +45,7 @@ def test_to_xarray(self): 'test_stat_non_defaults_args', 'test_truncate_out_of_bounds', 'test_metadata_propagation', 'test_copy_and_deepcopy', - 'test_sample']: + 'test_pct_change', 'test_sample']: def f(): def tester(self): diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 7a1aff1cc223c..63a05ef7de565 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -352,7 +352,7 @@ def test_pct_change_shift_over_nas(self): s = Series([1., 1.5, np.nan, 2.5, 3.]) chg = s.pct_change() - expected = Series([np.nan, 0.5, np.nan, 2.5 / 1.5 - 1, .2]) + expected = Series([np.nan, 0.5, 0., 2.5 / 1.5 - 1, .2]) assert_series_equal(chg, expected) def test_pct_change_periods_freq(self):
- [X] closes #19873 - [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/19875
2018-02-24T00:20:28Z
2018-02-25T16:07:00Z
2018-02-25T16:06:59Z
2018-05-14T21:11:44Z
Use pandas_datetimestruct instead of date_info
diff --git a/pandas/_libs/src/period_helper.c b/pandas/_libs/src/period_helper.c index e3d250aa44f17..19a7282f38049 100644 --- a/pandas/_libs/src/period_helper.c +++ b/pandas/_libs/src/period_helper.c @@ -89,14 +89,12 @@ static npy_int64 daytime_conversion_factor_matrix[7][7] = { {0, 0, 0, 0, 0, 1, 1000}, {0, 0, 0, 0, 0, 0, 1}}; -PANDAS_INLINE int max_value(int a, int b) { return a > b ? a : b; } +int max_value(int a, int b) { return a > b ? a : b; } PANDAS_INLINE int min_value(int a, int b) { return a < b ? a : b; } PANDAS_INLINE int get_freq_group(int freq) { return (freq / 1000) * 1000; } -PANDAS_INLINE int get_freq_group_index(int freq) { return freq / 1000; } - npy_int64 get_daytime_conversion_factor(int from_index, int to_index) { int row = min_value(from_index, to_index); @@ -227,16 +225,6 @@ static npy_int64 asfreq_DTtoB(npy_int64 ordinal, asfreq_info *af_info) { return DtoB(&dinfo, roll_back, ordinal); } -// all intra day calculations are now done within one function -static npy_int64 asfreq_DownsampleWithinDay(npy_int64 ordinal, - asfreq_info *af_info) { - return downsample_daytime(ordinal, af_info); -} - -static npy_int64 asfreq_UpsampleWithinDay(npy_int64 ordinal, - asfreq_info *af_info) { - return upsample_daytime(ordinal, af_info); -} //************ FROM BUSINESS *************** static npy_int64 asfreq_BtoDT(npy_int64 ordinal, asfreq_info *af_info) { @@ -288,26 +276,26 @@ static npy_int64 asfreq_WtoW(npy_int64 ordinal, asfreq_info *af_info) { static npy_int64 asfreq_WtoB(npy_int64 ordinal, asfreq_info *af_info) { struct date_info dinfo; npy_int64 unix_date = asfreq_WtoDT(ordinal, af_info); + int roll_back = af_info->is_end; dInfoCalc_SetFromAbsDate(&dinfo, unix_date); - return DtoB(&dinfo, roll_back, unix_date); } //************ FROM MONTHLY *************** -static void MtoD_ym(npy_int64 ordinal, int *y, int *m) { - *y = floordiv(ordinal, 12) + 1970; - *m = mod_compat(ordinal, 12) + 1; +static void MtoD_ym(npy_int64 ordinal, int *year, int *month) { + *year = floordiv(ordinal, 12) + 1970; + *month = mod_compat(ordinal, 12) + 1; } static npy_int64 asfreq_MtoDT(npy_int64 ordinal, asfreq_info *af_info) { npy_int64 unix_date; - int y, m; + int year, month; ordinal += af_info->is_end; - MtoD_ym(ordinal, &y, &m); - unix_date = unix_date_from_ymd(y, m, 1); + MtoD_ym(ordinal, &year, &month); + unix_date = unix_date_from_ymd(year, month, 1); unix_date -= af_info->is_end; return upsample_daytime(unix_date, af_info); } @@ -327,38 +315,37 @@ static npy_int64 asfreq_MtoW(npy_int64 ordinal, asfreq_info *af_info) { static npy_int64 asfreq_MtoB(npy_int64 ordinal, asfreq_info *af_info) { struct date_info dinfo; npy_int64 unix_date = asfreq_MtoDT(ordinal, af_info); - int roll_back = af_info->is_end; + int roll_back = af_info->is_end; dInfoCalc_SetFromAbsDate(&dinfo, unix_date); - return DtoB(&dinfo, roll_back, unix_date); } //************ FROM QUARTERLY *************** -static void QtoD_ym(npy_int64 ordinal, int *y, int *m, asfreq_info *af_info) { - *y = floordiv(ordinal, 4) + 1970; - *m = mod_compat(ordinal, 4) * 3 + 1; +static void QtoD_ym(npy_int64 ordinal, int *year, int *month, + asfreq_info *af_info) { + *year = floordiv(ordinal, 4) + 1970; + *month = mod_compat(ordinal, 4) * 3 + 1; if (af_info->from_q_year_end != 12) { - *m += af_info->from_q_year_end; - if (*m > 12) { - *m -= 12; + *month += af_info->from_q_year_end; + if (*month > 12) { + *month -= 12; } else { - *y -= 1; + *year -= 1; } } } static npy_int64 asfreq_QtoDT(npy_int64 ordinal, asfreq_info *af_info) { npy_int64 unix_date; - int y, m; + int year, month; ordinal += af_info->is_end; - QtoD_ym(ordinal, &y, &m, af_info); - - unix_date = unix_date_from_ymd(y, m, 1); + QtoD_ym(ordinal, &year, &month, af_info); + unix_date = unix_date_from_ymd(year, month, 1); unix_date -= af_info->is_end; return upsample_daytime(unix_date, af_info); } @@ -382,29 +369,39 @@ static npy_int64 asfreq_QtoW(npy_int64 ordinal, asfreq_info *af_info) { static npy_int64 asfreq_QtoB(npy_int64 ordinal, asfreq_info *af_info) { struct date_info dinfo; npy_int64 unix_date = asfreq_QtoDT(ordinal, af_info); - int roll_back = af_info->is_end; + int roll_back = af_info->is_end; dInfoCalc_SetFromAbsDate(&dinfo, unix_date); - return DtoB(&dinfo, roll_back, unix_date); } //************ FROM ANNUAL *************** -static npy_int64 asfreq_AtoDT(npy_int64 ordinal, asfreq_info *af_info) { - npy_int64 unix_date; +static void AtoD_ym(npy_int64 ordinal, int *year, int *month, + asfreq_info *af_info) { + *year = ordinal + 1970; + *month = 1; - // start from 1970 - npy_int64 year = ordinal + 1970; - - int month = (af_info->from_a_year_end % 12) + 1; if (af_info->from_a_year_end != 12) { - year -= 1; + *month += af_info->from_a_year_end; + if (*month > 12) { + // This case is never reached, but is kept for symmetry + // with QtoD_ym + *month -= 12; + } else { + *year -= 1; + } } +} - year += af_info->is_end; - unix_date = unix_date_from_ymd(year, month, 1); +static npy_int64 asfreq_AtoDT(npy_int64 ordinal, asfreq_info *af_info) { + npy_int64 unix_date; + int year, month; + + ordinal += af_info->is_end; + AtoD_ym(ordinal, &year, &month, af_info); + unix_date = unix_date_from_ymd(year, month, 1); unix_date -= af_info->is_end; return upsample_daytime(unix_date, af_info); } @@ -428,9 +425,9 @@ static npy_int64 asfreq_AtoW(npy_int64 ordinal, asfreq_info *af_info) { static npy_int64 asfreq_AtoB(npy_int64 ordinal, asfreq_info *af_info) { struct date_info dinfo; npy_int64 unix_date = asfreq_AtoDT(ordinal, af_info); + int roll_back = af_info->is_end; dInfoCalc_SetFromAbsDate(&dinfo, unix_date); - return DtoB(&dinfo, roll_back, unix_date); } @@ -443,57 +440,6 @@ static npy_int64 no_op(npy_int64 ordinal, asfreq_info *af_info) { // end of frequency specific conversion routines -static int calc_a_year_end(int freq, int group) { - int result = (freq - group) % 12; - if (result == 0) { - return 12; - } else { - return result; - } -} - -static int calc_week_end(int freq, int group) { return freq - group; } - -void get_asfreq_info(int fromFreq, int toFreq, char relation, - asfreq_info *af_info) { - int fromGroup = get_freq_group(fromFreq); - int toGroup = get_freq_group(toFreq); - - if (relation == 'E') { - af_info->is_end = 1; - } else { - af_info->is_end = 0; - } - - af_info->intraday_conversion_factor = get_daytime_conversion_factor( - get_freq_group_index(max_value(fromGroup, FR_DAY)), - get_freq_group_index(max_value(toGroup, FR_DAY))); - - switch (fromGroup) { - case FR_WK: - af_info->from_week_end = calc_week_end(fromFreq, fromGroup); - break; - case FR_ANN: - af_info->from_a_year_end = calc_a_year_end(fromFreq, fromGroup); - break; - case FR_QTR: - af_info->from_q_year_end = calc_a_year_end(fromFreq, fromGroup); - break; - } - - switch (toGroup) { - case FR_WK: - af_info->to_week_end = calc_week_end(toFreq, toGroup); - break; - case FR_ANN: - af_info->to_a_year_end = calc_a_year_end(toFreq, toGroup); - break; - case FR_QTR: - af_info->to_q_year_end = calc_a_year_end(toFreq, toGroup); - break; - } -} - freq_conv_func get_asfreq_func(int fromFreq, int toFreq) { int fromGroup = get_freq_group(fromFreq); int toGroup = get_freq_group(toFreq); @@ -650,9 +596,9 @@ freq_conv_func get_asfreq_func(int fromFreq, int toFreq) { case FR_US: case FR_NS: if (fromGroup > toGroup) { - return &asfreq_DownsampleWithinDay; + return &downsample_daytime; } else { - return &asfreq_UpsampleWithinDay; + return &upsample_daytime; } default: return &nofunc; @@ -662,20 +608,3 @@ freq_conv_func get_asfreq_func(int fromFreq, int toFreq) { return &nofunc; } } - -/* ------------------------------------------------------------------ - * New pandas API-helper code, to expose to cython - * ------------------------------------------------------------------*/ - -npy_int64 asfreq(npy_int64 period_ordinal, int freq1, int freq2, - char relation) { - npy_int64 val; - freq_conv_func func; - asfreq_info finfo; - - func = get_asfreq_func(freq1, freq2); - - get_asfreq_info(freq1, freq2, relation, &finfo); - val = (*func)(period_ordinal, &finfo); - return val; -} diff --git a/pandas/_libs/src/period_helper.h b/pandas/_libs/src/period_helper.h index 7163dc960d152..c6313924adddd 100644 --- a/pandas/_libs/src/period_helper.h +++ b/pandas/_libs/src/period_helper.h @@ -108,12 +108,9 @@ typedef npy_int64 (*freq_conv_func)(npy_int64, asfreq_info *af_info); * new pandas API helper functions here */ -npy_int64 asfreq(npy_int64 period_ordinal, int freq1, int freq2, char relation); - freq_conv_func get_asfreq_func(int fromFreq, int toFreq); -void get_asfreq_info(int fromFreq, int toFreq, char relation, - asfreq_info *af_info); npy_int64 get_daytime_conversion_factor(int from_index, int to_index); +int max_value(int a, int b); #endif // PANDAS__LIBS_SRC_PERIOD_HELPER_H_ diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index f1a193706144f..9cf7e39791f2b 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -75,15 +75,8 @@ cdef extern from "period_helper.h": int FR_BUS int FR_UND - ctypedef struct date_info: - double second - int minute - int hour - int day - int month - int year - ctypedef struct asfreq_info: + int64_t intraday_conversion_factor int is_end int from_week_end @@ -97,24 +90,21 @@ cdef extern from "period_helper.h": ctypedef int64_t (*freq_conv_func)(int64_t, asfreq_info*) nogil - int64_t asfreq(int64_t dtordinal, int freq1, int freq2, - char relation) except INT32_MIN freq_conv_func get_asfreq_func(int fromFreq, int toFreq) nogil - void get_asfreq_info(int fromFreq, int toFreq, char relation, - asfreq_info *af_info) nogil int64_t get_daytime_conversion_factor(int from_index, int to_index) nogil + int max_value(int left, int right) nogil @cython.cdivision -cdef char* c_strftime(date_info *dinfo, char *fmt): +cdef char* c_strftime(pandas_datetimestruct *dts, char *fmt): """ Generate a nice string representation of the period object, originally from DateObject_strftime Parameters ---------- - dinfo : date_info* + dts : pandas_datetimestruct* fmt : char* Returns @@ -126,14 +116,14 @@ cdef char* c_strftime(date_info *dinfo, char *fmt): char *result int result_len = strlen(fmt) + 50 - c_date.tm_sec = <int>dinfo.second - c_date.tm_min = dinfo.minute - c_date.tm_hour = dinfo.hour - c_date.tm_mday = dinfo.day - c_date.tm_mon = dinfo.month - 1 - c_date.tm_year = dinfo.year - 1900 - c_date.tm_wday = (dayofweek(dinfo.year, dinfo.month, dinfo.day) + 1) % 7 - c_date.tm_yday = get_day_of_year(dinfo.year, dinfo.month, dinfo.day) - 1 + c_date.tm_sec = dts.sec + c_date.tm_min = dts.min + c_date.tm_hour = dts.hour + c_date.tm_mday = dts.day + c_date.tm_mon = dts.month - 1 + c_date.tm_year = dts.year - 1900 + c_date.tm_wday = (dayofweek(dts.year, dts.month, dts.day) + 1) % 7 + c_date.tm_yday = get_day_of_year(dts.year, dts.month, dts.day) - 1 c_date.tm_isdst = -1 result = <char*>malloc(result_len * sizeof(char)) @@ -150,6 +140,10 @@ cdef inline int get_freq_group(int freq) nogil: return (freq // 1000) * 1000 +cdef inline int get_freq_group_index(int freq) nogil: + return freq // 1000 + + # specifically _dont_ use cdvision or else ordinals near -1 are assigned to # incorrect dates GH#19643 @cython.cdivision(False) @@ -261,7 +255,8 @@ cdef int64_t get_period_ordinal(int year, int month, int day, # raise ValueError -cdef void get_date_info(int64_t ordinal, int freq, date_info *dinfo) nogil: +cdef void get_date_info(int64_t ordinal, int freq, + pandas_datetimestruct *dts) nogil: cdef: int64_t unix_date double abstime @@ -277,7 +272,7 @@ cdef void get_date_info(int64_t ordinal, int freq, date_info *dinfo) nogil: abstime -= 86400 unix_date += 1 - date_info_from_days_and_time(dinfo, unix_date, abstime) + date_info_from_days_and_time(dts, unix_date, abstime) cdef int64_t get_unix_date(int64_t period_ordinal, int freq) nogil: @@ -304,12 +299,12 @@ cdef int64_t get_unix_date(int64_t period_ordinal, int freq) nogil: return period_ordinal toDaily = get_asfreq_func(freq, FR_DAY) - get_asfreq_info(freq, FR_DAY, 'E', &af_info) + get_asfreq_info(freq, FR_DAY, True, &af_info) return toDaily(period_ordinal, &af_info) @cython.cdivision -cdef void date_info_from_days_and_time(date_info *dinfo, +cdef void date_info_from_days_and_time(pandas_datetimestruct *dts, int64_t unix_date, double abstime) nogil: """ @@ -317,7 +312,7 @@ cdef void date_info_from_days_and_time(date_info *dinfo, Parameters ---------- - dinfo : date_info* + dts : pandas_datetimestruct* unix_date : int64_t days elapsed since datetime(1970, 1, 1) abstime : double @@ -325,23 +320,19 @@ cdef void date_info_from_days_and_time(date_info *dinfo, Notes ----- - Updates dinfo inplace + Updates dts inplace """ cdef: - pandas_datetimestruct dts int inttime int hour, minute - double second + double second, subsecond_fraction # Bounds check # The calling function is responsible for ensuring that # abstime >= 0.0 and abstime <= 86400 # Calculate the date - pandas_datetime_to_datetimestruct(unix_date, PANDAS_FR_D, &dts) - dinfo.year = dts.year - dinfo.month = dts.month - dinfo.day = dts.day + pandas_datetime_to_datetimestruct(unix_date, PANDAS_FR_D, dts) # Calculate the time inttime = <int>abstime @@ -349,9 +340,13 @@ cdef void date_info_from_days_and_time(date_info *dinfo, minute = (inttime % 3600) / 60 second = abstime - <double>(hour * 3600 + minute * 60) - dinfo.hour = hour - dinfo.minute = minute - dinfo.second = second + dts.hour = hour + dts.min = minute + dts.sec = <int>second + + subsecond_fraction = second - dts.sec + dts.us = int((subsecond_fraction) * 1e6) + dts.ps = int(((subsecond_fraction) * 1e6 - dts.us) * 1e6) @cython.cdivision @@ -439,7 +434,7 @@ cdef int get_yq(int64_t ordinal, int freq, int *quarter, int *year): else: qtr_freq = FR_QTR - get_asfreq_info(FR_DAY, qtr_freq, 'E', &af_info) + get_asfreq_info(FR_DAY, qtr_freq, True, &af_info) quarter[0] = DtoQ_yq(unix_date, &af_info, year) return qtr_freq @@ -447,20 +442,20 @@ cdef int get_yq(int64_t ordinal, int freq, int *quarter, int *year): cdef int DtoQ_yq(int64_t unix_date, asfreq_info *af_info, int *year): cdef: - date_info dinfo + pandas_datetimestruct dts int quarter - date_info_from_days_and_time(&dinfo, unix_date, 0) + date_info_from_days_and_time(&dts, unix_date, 0) if af_info.to_q_year_end != 12: - dinfo.month -= af_info.to_q_year_end - if dinfo.month <= 0: - dinfo.month += 12 + dts.month -= af_info.to_q_year_end + if dts.month <= 0: + dts.month += 12 else: - dinfo.year += 1 + dts.year += 1 - year[0] = dinfo.year - quarter = month_to_quarter(dinfo.month) + year[0] = dts.year + quarter = month_to_quarter(dts.month) return quarter @@ -528,10 +523,6 @@ def periodarr_to_dt64arr(ndarray[int64_t] periodarr, int freq): return out -cdef char START = 'S' -cdef char END = 'E' - - cpdef int64_t period_asfreq(int64_t ordinal, int freq1, int freq2, bint end): """ Convert period ordinal from one frequency to another, and if upsampling, @@ -539,14 +530,15 @@ cpdef int64_t period_asfreq(int64_t ordinal, int freq1, int freq2, bint end): """ cdef: int64_t retval + freq_conv_func func + asfreq_info af_info if ordinal == iNaT: return iNaT - if end: - retval = asfreq(ordinal, freq1, freq2, END) - else: - retval = asfreq(ordinal, freq1, freq2, START) + func = get_asfreq_func(freq1, freq2) + get_asfreq_info(freq1, freq2, end, &af_info) + retval = func(ordinal, &af_info) if retval == INT32_MIN: raise ValueError('Frequency conversion failed') @@ -554,6 +546,58 @@ cpdef int64_t period_asfreq(int64_t ordinal, int freq1, int freq2, bint end): return retval +cdef void get_asfreq_info(int from_freq, int to_freq, + bint is_end, asfreq_info *af_info) nogil: + """ + Construct the `asfreq_info` object used to convert an ordinal from + `from_freq` to `to_freq`. + + Parameters + ---------- + from_freq : int + to_freq int + is_end : bool + af_info : *asfreq_info + """ + cdef: + int from_group = get_freq_group(from_freq) + int to_group = get_freq_group(to_freq) + + af_info.is_end = is_end + + af_info.intraday_conversion_factor = get_daytime_conversion_factor( + get_freq_group_index(max_value(from_group, FR_DAY)), + get_freq_group_index(max_value(to_group, FR_DAY))) + + if from_group == FR_WK: + af_info.from_week_end = calc_week_end(from_freq, from_group) + elif from_group == FR_ANN: + af_info.from_a_year_end = calc_a_year_end(from_freq, from_group) + elif from_group == FR_QTR: + af_info.from_q_year_end = calc_a_year_end(from_freq, from_group) + + if to_group == FR_WK: + af_info.to_week_end = calc_week_end(to_freq, to_group) + elif to_group == FR_ANN: + af_info.to_a_year_end = calc_a_year_end(to_freq, to_group) + elif to_group == FR_QTR: + af_info.to_q_year_end = calc_a_year_end(to_freq, to_group) + + +@cython.cdivision +cdef int calc_a_year_end(int freq, int group) nogil: + cdef: + int result = (freq - group) % 12 + if result == 0: + return 12 + else: + return result + + +cdef inline int calc_week_end(int freq, int group) nogil: + return freq - group + + def period_asfreq_arr(ndarray[int64_t] arr, int freq1, int freq2, bint end): """ Convert int64-array of period ordinals from one frequency to another, and @@ -565,18 +609,12 @@ def period_asfreq_arr(ndarray[int64_t] arr, int freq1, int freq2, bint end): freq_conv_func func asfreq_info af_info int64_t val - char relation n = len(arr) result = np.empty(n, dtype=np.int64) - if end: - relation = END - else: - relation = START - func = get_asfreq_func(freq1, freq2) - get_asfreq_info(freq1, freq2, relation, &af_info) + get_asfreq_info(freq1, freq2, end, &af_info) mask = arr == iNaT if mask.any(): # NaT process @@ -605,24 +643,12 @@ def period_ordinal(int y, int m, int d, int h, int min, cpdef int64_t period_ordinal_to_dt64(int64_t ordinal, int freq) nogil: cdef: pandas_datetimestruct dts - date_info dinfo float subsecond_fraction if ordinal == NPY_NAT: return NPY_NAT - get_date_info(ordinal, freq, &dinfo) - - dts.year = dinfo.year - dts.month = dinfo.month - dts.day = dinfo.day - dts.hour = dinfo.hour - dts.min = dinfo.minute - dts.sec = int(dinfo.second) - subsecond_fraction = dinfo.second - dts.sec - dts.us = int((subsecond_fraction) * 1e6) - dts.ps = int(((subsecond_fraction) * 1e6 - dts.us) * 1e6) - + get_date_info(ordinal, freq, &dts) return dtstruct_to_dt64(&dts) @@ -680,7 +706,7 @@ cdef list str_extra_fmts = ["^`AB`^", "^`CD`^", "^`EF`^", cdef object _period_strftime(int64_t value, int freq, object fmt): cdef: Py_ssize_t i - date_info dinfo + pandas_datetimestruct dts char *formatted object pat, repl, result list found_pat = [False] * len(extra_fmts) @@ -689,7 +715,7 @@ cdef object _period_strftime(int64_t value, int freq, object fmt): if PyUnicode_Check(fmt): fmt = fmt.encode('utf-8') - get_date_info(value, freq, &dinfo) + get_date_info(value, freq, &dts) for i in range(len(extra_fmts)): pat = extra_fmts[i][0] repl = extra_fmts[i][1] @@ -697,7 +723,7 @@ cdef object _period_strftime(int64_t value, int freq, object fmt): fmt = fmt.replace(pat, repl) found_pat[i] = True - formatted = c_strftime(&dinfo, <char*> fmt) + formatted = c_strftime(&dts, <char*> fmt) result = util.char_to_string(formatted) free(formatted) @@ -736,9 +762,9 @@ ctypedef int (*accessor)(int64_t ordinal, int freq) except INT32_MIN cdef int pyear(int64_t ordinal, int freq): cdef: - date_info dinfo - get_date_info(ordinal, freq, &dinfo) - return dinfo.year + pandas_datetimestruct dts + get_date_info(ordinal, freq, &dts) + return dts.year @cython.cdivision @@ -762,65 +788,65 @@ cdef int pquarter(int64_t ordinal, int freq): cdef int pmonth(int64_t ordinal, int freq): cdef: - date_info dinfo - get_date_info(ordinal, freq, &dinfo) - return dinfo.month + pandas_datetimestruct dts + get_date_info(ordinal, freq, &dts) + return dts.month cdef int pday(int64_t ordinal, int freq): cdef: - date_info dinfo - get_date_info(ordinal, freq, &dinfo) - return dinfo.day + pandas_datetimestruct dts + get_date_info(ordinal, freq, &dts) + return dts.day cdef int pweekday(int64_t ordinal, int freq): cdef: - date_info dinfo - get_date_info(ordinal, freq, &dinfo) - return dayofweek(dinfo.year, dinfo.month, dinfo.day) + pandas_datetimestruct dts + get_date_info(ordinal, freq, &dts) + return dayofweek(dts.year, dts.month, dts.day) cdef int pday_of_year(int64_t ordinal, int freq): cdef: - date_info dinfo - get_date_info(ordinal, freq, &dinfo) - return get_day_of_year(dinfo.year, dinfo.month, dinfo.day) + pandas_datetimestruct dts + get_date_info(ordinal, freq, &dts) + return get_day_of_year(dts.year, dts.month, dts.day) cdef int pweek(int64_t ordinal, int freq): cdef: - date_info dinfo - get_date_info(ordinal, freq, &dinfo) - return ccalendar.get_week_of_year(dinfo.year, dinfo.month, dinfo.day) + pandas_datetimestruct dts + get_date_info(ordinal, freq, &dts) + return ccalendar.get_week_of_year(dts.year, dts.month, dts.day) cdef int phour(int64_t ordinal, int freq): cdef: - date_info dinfo - get_date_info(ordinal, freq, &dinfo) - return dinfo.hour + pandas_datetimestruct dts + get_date_info(ordinal, freq, &dts) + return dts.hour cdef int pminute(int64_t ordinal, int freq): cdef: - date_info dinfo - get_date_info(ordinal, freq, &dinfo) - return dinfo.minute + pandas_datetimestruct dts + get_date_info(ordinal, freq, &dts) + return dts.min cdef int psecond(int64_t ordinal, int freq): cdef: - date_info dinfo - get_date_info(ordinal, freq, &dinfo) - return <int>dinfo.second + pandas_datetimestruct dts + get_date_info(ordinal, freq, &dts) + return <int>dts.sec cdef int pdays_in_month(int64_t ordinal, int freq): cdef: - date_info dinfo - get_date_info(ordinal, freq, &dinfo) - return ccalendar.get_days_in_month(dinfo.year, dinfo.month) + pandas_datetimestruct dts + get_date_info(ordinal, freq, &dts) + return ccalendar.get_days_in_month(dts.year, dts.month) def get_period_field_arr(int code, ndarray[int64_t] arr, int freq): diff --git a/pandas/tests/scalar/period/test_period_asfreq.py b/pandas/tests/scalar/period/test_asfreq.py similarity index 100% rename from pandas/tests/scalar/period/test_period_asfreq.py rename to pandas/tests/scalar/period/test_asfreq.py
Changes test file name from previous pass
https://api.github.com/repos/pandas-dev/pandas/pulls/19874
2018-02-23T23:32:46Z
2018-02-25T16:09:36Z
2018-02-25T16:09:36Z
2018-06-22T03:29:20Z
templatize timedelta arith ops
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index c4578a289b020..7aeff9bec75b5 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -471,9 +471,12 @@ def _binary_op_method_timedeltalike(op, name): # define a binary operation that only works if the other argument is # timedelta like or an array of timedeltalike def f(self, other): - if hasattr(other, 'delta') and not PyDelta_Check(other): - # offsets.Tick - return op(self, other.delta) + if hasattr(other, '_typ'): + # Series, DataFrame, ... + if other._typ == 'dateoffset' and hasattr(other, 'delta'): + # Tick offset + return op(self, other.delta) + return NotImplemented elif other is NaT: return NaT @@ -1052,7 +1055,14 @@ class Timedelta(_Timedelta): __rsub__ = _binary_op_method_timedeltalike(lambda x, y: y - x, '__rsub__') def __mul__(self, other): - if hasattr(other, 'dtype'): + if hasattr(other, '_typ'): + # Series, DataFrame, ... + if other._typ == 'dateoffset' and hasattr(other, 'delta'): + # Tick offset; this op will raise TypeError + return other.delta * self + return NotImplemented + + elif hasattr(other, 'dtype'): # ndarray-like return other * self.to_timedelta64() @@ -1068,7 +1078,18 @@ class Timedelta(_Timedelta): __rmul__ = __mul__ def __truediv__(self, other): - if hasattr(other, 'dtype'): + if hasattr(other, '_typ'): + # Series, DataFrame, ... + if other._typ == 'dateoffset' and hasattr(other, 'delta'): + # Tick offset + return self / other.delta + return NotImplemented + + elif is_timedelta64_object(other): + # convert to Timedelta below + pass + + elif hasattr(other, 'dtype'): return self.to_timedelta64() / other elif is_integer_object(other) or is_float_object(other): @@ -1084,7 +1105,18 @@ class Timedelta(_Timedelta): return self.value / float(other.value) def __rtruediv__(self, other): - if hasattr(other, 'dtype'): + if hasattr(other, '_typ'): + # Series, DataFrame, ... + if other._typ == 'dateoffset' and hasattr(other, 'delta'): + # Tick offset + return other.delta / self + return NotImplemented + + elif is_timedelta64_object(other): + # convert to Timedelta below + pass + + elif hasattr(other, 'dtype'): return other / self.to_timedelta64() elif not _validate_ops_compat(other): @@ -1160,9 +1192,10 @@ class Timedelta(_Timedelta): '{op}'.format(dtype=other.dtype, op='__floordiv__')) - if is_float_object(other) and util._checknull(other): + elif is_float_object(other) and util._checknull(other): # i.e. np.nan return NotImplemented + elif not _validate_ops_compat(other): return NotImplemented
Some Timedelta operations are constructed using `_binary_op_method_timedeltalike`, while a bunch of others re-implement shared logic. This PR is an attempt to get rid of the small differences in this shared logic so they can eventually use a single template.
https://api.github.com/repos/pandas-dev/pandas/pulls/19871
2018-02-23T17:45:06Z
2018-02-24T16:38:23Z
2018-02-24T16:38:23Z
2018-06-22T03:29:14Z
ENH: ExtensionArray.unique
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index d616e3f92aa4d..9101fca58d5fa 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -10,8 +10,9 @@ maybe_promote, construct_1d_object_array_from_listlike) from pandas.core.dtypes.generic import ( ABCSeries, ABCIndex, - ABCIndexClass, ABCCategorical) + ABCIndexClass) from pandas.core.dtypes.common import ( + is_array_like, is_unsigned_integer_dtype, is_signed_integer_dtype, is_integer_dtype, is_complex_dtype, is_object_dtype, @@ -168,8 +169,7 @@ def _ensure_arraylike(values): """ ensure that we are arraylike if not already """ - if not isinstance(values, (np.ndarray, ABCCategorical, - ABCIndexClass, ABCSeries)): + if not is_array_like(values): inferred = lib.infer_dtype(values) if inferred in ['mixed', 'string', 'unicode']: if isinstance(values, tuple): @@ -353,11 +353,8 @@ def unique(values): values = _ensure_arraylike(values) - # categorical is a fast-path - # this will coerce Categorical, CategoricalIndex, - # and category dtypes Series to same return of Category - if is_categorical_dtype(values): - values = getattr(values, '.values', values) + if is_extension_array_dtype(values): + # Dispatch to extension dtype's unique. return values.unique() original = values diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 37074b563efbd..1f33081a5f610 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -236,6 +236,18 @@ def isna(self): """ raise AbstractMethodError(self) + def unique(self): + """Compute the ExtensionArray of unique values. + + Returns + ------- + uniques : ExtensionArray + """ + from pandas import unique + + uniques = unique(self.astype(object)) + return self._constructor_from_sequence(uniques) + # ------------------------------------------------------------------------ # Indexing methods # ------------------------------------------------------------------------ diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index 74e5d180b1aa3..7ce80e25d8cf6 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -31,3 +31,14 @@ def test_count(self, data_missing): def test_apply_simple_series(self, data): result = pd.Series(data).apply(id) assert isinstance(result, pd.Series) + + @pytest.mark.parametrize('box', [pd.Series, lambda x: x]) + @pytest.mark.parametrize('method', [lambda x: x.unique(), pd.unique]) + def test_unique(self, data, box, method): + duplicated = box(data._constructor_from_sequence([data[0], data[0]])) + + result = method(duplicated) + + assert len(result) == 1 + assert isinstance(result, type(data)) + assert result[0] == duplicated[0] diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 21addf9d1549f..322944129146a 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -88,6 +88,13 @@ def take(self, indexer, allow_fill=True, fill_value=None): def copy(self, deep=False): return type(self)(self.data[:]) + def unique(self): + # Parent method doesn't work since np.array will try to infer + # a 2-dim object. + return type(self)([ + dict(x) for x in list(set(tuple(d.items()) for d in self.data)) + ]) + @property def _na_value(self): return {}
https://api.github.com/repos/pandas-dev/pandas/pulls/19869
2018-02-23T17:26:26Z
2018-03-13T10:17:19Z
2018-03-13T10:17:19Z
2018-05-02T13:10:18Z
BUG: Decrement start date with a negative, non-Tick frequency
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index d0aa156cf5059..7dc86b9c1e608 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -914,6 +914,7 @@ Datetimelike - Bug in rounding methods of :class:`DatetimeIndex` (:meth:`~DatetimeIndex.round`, :meth:`~DatetimeIndex.ceil`, :meth:`~DatetimeIndex.floor`) and :class:`Timestamp` (:meth:`~Timestamp.round`, :meth:`~Timestamp.ceil`, :meth:`~Timestamp.floor`) could give rise to loss of precision (:issue:`22591`) - Bug in :func:`to_datetime` with an :class:`Index` argument that would drop the ``name`` from the result (:issue:`21697`) - Bug in :class:`PeriodIndex` where adding or subtracting a :class:`timedelta` or :class:`Tick` object produced incorrect results (:issue:`22988`) +- Bug in :func:`date_range` when decrementing a start date to a past end date by a negative frequency (:issue:`23270`) Timedelta ^^^^^^^^^ diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 7481c4a710083..c05c80df29dac 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -510,6 +510,16 @@ def test_timezone_comparaison_assert(self): with tm.assert_raises_regex(AssertionError, msg): date_range(start, periods=2, tz='Europe/Berlin') + def test_negative_non_tick_frequency_descending_dates(self, + tz_aware_fixture): + # GH 23270 + tz = tz_aware_fixture + result = pd.date_range(start='2011-06-01', end='2011-01-01', + freq='-1MS', tz=tz) + expected = pd.date_range(end='2011-06-01', start='2011-01-01', + freq='1MS', tz=tz)[::-1] + tm.assert_index_equal(result, expected) + class TestGenRangeGeneration(object): diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index e6d73fc45c502..650c4d5b21d7f 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -2388,7 +2388,7 @@ def generate_range(start=None, end=None, periods=None, elif end and not offset.onOffset(end): end = offset.rollback(end) - if periods is None and end < start: + if periods is None and end < start and offset.n >= 0: end = None periods = 0
- [x] closes #23270 - [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/23278
2018-10-22T17:34:06Z
2018-10-23T03:09:10Z
2018-10-23T03:09:10Z
2018-10-23T16:52:36Z
TST: Condense tests in test_interval_new.py and add new test based on TODO
diff --git a/pandas/tests/indexes/interval/test_interval_new.py b/pandas/tests/indexes/interval/test_interval_new.py index c5daa7271926f..02801f6bbc7ee 100644 --- a/pandas/tests/indexes/interval/test_interval_new.py +++ b/pandas/tests/indexes/interval/test_interval_new.py @@ -12,13 +12,6 @@ class TestIntervalIndex(object): - 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("side", ['right', 'left', 'both', 'neither']) def test_get_loc_interval(self, closed, side): @@ -149,107 +142,94 @@ def test_slice_locs_with_ints_and_floats_errors(self, tuples, query): index.slice_locs(query) @pytest.mark.parametrize('query, expected', [ - (Interval(1, 3, closed='right'), 1), - (Interval(1, 3, closed='left'), -1), - (Interval(1, 3, closed='both'), -1), - (Interval(1, 3, closed='neither'), -1), - (Interval(1, 4, closed='right'), -1), - (Interval(0, 4, closed='right'), -1), - (Interval(1, 2, closed='right'), -1)]) - def test_get_indexer_with_interval_single_queries(self, query, expected): - - index = IntervalIndex.from_tuples( - [(0, 2.5), (1, 3), (2, 4)], closed='right') - - result = index.get_indexer([query]) - expected = np.array([expected], dtype='intp') - tm.assert_numpy_array_equal(result, expected) - - @pytest.mark.parametrize('query, expected', [ + ([Interval(1, 3, closed='right')], [1]), + ([Interval(1, 3, closed='left')], [-1]), + ([Interval(1, 3, closed='both')], [-1]), + ([Interval(1, 3, closed='neither')], [-1]), + ([Interval(1, 4, closed='right')], [-1]), + ([Interval(0, 4, closed='right')], [-1]), + ([Interval(1, 2, closed='right')], [-1]), ([Interval(2, 4, closed='right'), Interval(1, 3, closed='right')], [2, 1]), ([Interval(1, 3, closed='right'), Interval(0, 2, closed='right')], [1, -1]), ([Interval(1, 3, closed='right'), Interval(1, 3, closed='left')], [1, -1])]) - def test_get_indexer_with_interval_multiple_queries(self, query, expected): + def test_get_indexer_with_interval(self, query, expected): - index = IntervalIndex.from_tuples( - [(0, 2.5), (1, 3), (2, 4)], closed='right') + tuples = [(0, 2.5), (1, 3), (2, 4)] + index = IntervalIndex.from_tuples(tuples, closed='right') result = index.get_indexer(query) expected = np.array(expected, dtype='intp') tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize('query, expected', [ - (-0.5, -1), (0, -1), (0.5, 0), (1, 0), (1.5, 1), (2, 1), - (2.5, -1), (3, -1), (3.5, 2), (4, 2), (4.5, -1)]) - def test_get_indexer_with_ints_and_floats_single_queries( - self, query, expected): - - index = IntervalIndex.from_tuples( - [(0, 1), (1, 2), (3, 4)], closed='right') - - result = index.get_indexer([query]) - expected = np.array([expected], dtype='intp') - tm.assert_numpy_array_equal(result, expected) - - @pytest.mark.parametrize('query, expected', [ + ([-0.5], [-1]), + ([0], [-1]), + ([0.5], [0]), + ([1], [0]), + ([1.5], [1]), + ([2], [1]), + ([2.5], [-1]), + ([3], [-1]), + ([3.5], [2]), + ([4], [2]), + ([4.5], [-1]), ([1, 2], [0, 1]), ([1, 2, 3], [0, 1, -1]), ([1, 2, 3, 4], [0, 1, -1, 2]), ([1, 2, 3, 4, 2], [0, 1, -1, 2, 1])]) - def test_get_indexer_with_ints_and_floats_multiple_queries( - self, query, expected): + def test_get_indexer_with_int_and_float(self, query, expected): - index = IntervalIndex.from_tuples( - [(0, 1), (1, 2), (3, 4)], closed='right') + tuples = [(0, 1), (1, 2), (3, 4)] + index = IntervalIndex.from_tuples(tuples, closed='right') result = index.get_indexer(query) expected = np.array(expected, dtype='intp') tm.assert_numpy_array_equal(result, expected) - index = IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)]) - # TODO: @shoyer believes this should raise, master branch doesn't + @pytest.mark.parametrize('tuples, closed', [ + ([(0, 2), (1, 3), (3, 4)], 'neither'), + ([(0, 5), (1, 4), (6, 7)], 'left'), + ([(0, 1), (0, 1), (1, 2)], 'right'), + ([(0, 1), (2, 3), (3, 4)], 'both')]) + def test_get_indexer_errors(self, tuples, closed): + # IntervalIndex needs non-overlapping for uniqueness when querying + index = IntervalIndex.from_tuples(tuples, closed=closed) - @pytest.mark.parametrize('query, expected', [ - (-0.5, (Int64Index([], dtype='int64'), np.array([0]))), - (0, (Int64Index([0], dtype='int64'), np.array([]))), - (0.5, (Int64Index([0], dtype='int64'), np.array([]))), - (1, (Int64Index([0, 1], dtype='int64'), np.array([]))), - (1.5, (Int64Index([0, 1], dtype='int64'), np.array([]))), - (2, (Int64Index([0, 1, 2], dtype='int64'), np.array([]))), - (2.5, (Int64Index([1, 2], dtype='int64'), np.array([]))), - (3, (Int64Index([2], dtype='int64'), np.array([]))), - (3.5, (Int64Index([2], dtype='int64'), np.array([]))), - (4, (Int64Index([], dtype='int64'), np.array([0]))), - (4.5, (Int64Index([], dtype='int64'), np.array([0])))]) - def test_get_indexer_non_unique_with_ints_and_floats_single_queries( - self, query, expected): - - 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) + msg = ('cannot handle overlapping indices; use ' + 'IntervalIndex.get_indexer_non_unique') + with tm.assert_raises_regex(ValueError, msg): + index.get_indexer([0, 2]) @pytest.mark.parametrize('query, expected', [ - ([1, 2], (Int64Index([0, 1, 0, 1, 2], dtype='int64'), np.array([]))), - ([1, 2, 3], - (Int64Index([0, 1, 0, 1, 2, 2], dtype='int64'), np.array([]))), - ([1, 2, 3, 4], - (Int64Index([0, 1, 0, 1, 2, 2, -1], dtype='int64'), np.array([3]))), - ([1, 2, 3, 4, 2], - (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): - - 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) + ([-0.5], ([-1], [0])), + ([0], ([0], [])), + ([0.5], ([0], [])), + ([1], ([0, 1], [])), + ([1.5], ([0, 1], [])), + ([2], ([0, 1, 2], [])), + ([2.5], ([1, 2], [])), + ([3], ([2], [])), + ([3.5], ([2], [])), + ([4], ([-1], [0])), + ([4.5], ([-1], [0])), + ([1, 2], ([0, 1, 0, 1, 2], [])), + ([1, 2, 3], ([0, 1, 0, 1, 2, 2], [])), + ([1, 2, 3, 4], ([0, 1, 0, 1, 2, 2, -1], [3])), + ([1, 2, 3, 4, 2], ([0, 1, 0, 1, 2, 2, -1, 0, 1, 2], [3]))]) + def test_get_indexer_non_unique_with_int_and_float(self, query, expected): + + tuples = [(0, 2.5), (1, 3), (2, 4)] + index = IntervalIndex.from_tuples(tuples, closed='left') + + result_indexer, result_missing = index.get_indexer_non_unique(query) + expected_indexer = Int64Index(expected[0]) + expected_missing = np.array(expected[1], dtype='intp') + + tm.assert_index_equal(result_indexer, expected_indexer) + tm.assert_numpy_array_equal(result_missing, expected_missing) # TODO we may also want to test get_indexer for the case when # the intervals are duplicated, decreasing, non-monotonic, etc..
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Combined a some pairs of similar tests into single tests, e.g. `test_get_indexer_with_interval_multiple_queries` and `test_get_indexer_with_interval_single_queries` are essentially testing the same functionality but with different input to `get_indexer`, so just needed a couple of superficial changes to combine into a single test. I also added one test based on a TODO, `test_get_indexer_errors`, which verifies that `get_indexer` raises if the `IntervalIndex` is overlapping. Note that this is consistent with `get_indexer` raising for other indexes if the index is non-unique; for intervals uniqueness is not enough to ensure unique query results, as a scalar query against an overlapping `IntervalIndex` can return non-unique indices. I've got all these tests to pass on my WIP branch implementing the new behavior, with the exception of the `slice_locs` tests, so will hopefully have a PR for that soon.
https://api.github.com/repos/pandas-dev/pandas/pulls/23275
2018-10-22T14:48:17Z
2018-10-23T03:08:46Z
2018-10-23T03:08:46Z
2018-10-25T03:42:01Z
Implement Series.__rdivmod__, un-xfail tests
diff --git a/pandas/core/ops.py b/pandas/core/ops.py index daa87ad173772..c14e9edcc75d7 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -518,7 +518,7 @@ def _get_op_name(op, special): 'df_examples': None}, 'divmod': {'op': 'divmod', 'desc': 'Integer division and modulo', - 'reverse': None, + 'reverse': 'rdivmod', 'df_examples': None}, # Comparison Operators @@ -1039,6 +1039,7 @@ def _create_methods(cls, arith_method, comp_method, bool_method, special): if have_divmod: # divmod doesn't have an op that is supported by numexpr new_methods['divmod'] = arith_method(cls, divmod, special) + new_methods['rdivmod'] = arith_method(cls, rdivmod, special) new_methods.update(dict( eq=comp_method(cls, operator.eq, special), @@ -1224,7 +1225,7 @@ def dispatch_to_extension_op(op, left, right): res_values = op(new_left, new_right) res_name = get_op_result_name(left, right) - if op.__name__ == 'divmod': + if op.__name__ in ['divmod', 'rdivmod']: return _construct_divmod_result( left, res_values, left.index, res_name) @@ -1241,7 +1242,7 @@ def _arith_method_SERIES(cls, op, special): eval_kwargs = _gen_eval_kwargs(op_name) fill_zeros = _gen_fill_zeros(op_name) construct_result = (_construct_divmod_result - if op is divmod else _construct_result) + if op in [divmod, rdivmod] else _construct_result) def na_op(x, y): import pandas.core.computation.expressions as expressions @@ -1871,8 +1872,8 @@ def f(self, other, axis=default_axis, level=None, fill_value=None): if fill_value is not None: self = self.fillna(fill_value) - pass_op = op if lib.is_scalar(other) else na_op - return self._combine_const(other, pass_op, try_cast=True) + assert np.ndim(other) == 0 + return self._combine_const(other, op, try_cast=True) f.__name__ = op_name diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index e9316221b125b..25845dd8b3151 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -516,33 +516,38 @@ def test_modulo(self, numeric_idx, box): result = idx % 2 tm.assert_equal(result, expected) - def test_divmod(self, numeric_idx): + def test_divmod_scalar(self, numeric_idx): idx = numeric_idx + result = divmod(idx, 2) with np.errstate(all='ignore'): div, mod = divmod(idx.values, 2) - expected = Index(div), Index(mod) + + expected = Index(div), Index(mod) for r, e in zip(result, expected): tm.assert_index_equal(r, e) + def test_divmod_ndarray(self, numeric_idx): + idx = numeric_idx other = np.ones(idx.values.shape, dtype=idx.values.dtype) * 2 + result = divmod(idx, other) with np.errstate(all='ignore'): div, mod = divmod(idx.values, other) - expected = Index(div), Index(mod) + + expected = Index(div), Index(mod) for r, e in zip(result, expected): tm.assert_index_equal(r, e) - @pytest.mark.xfail(reason='GH#19252 Series has no __rdivmod__', - strict=True) def test_divmod_series(self, numeric_idx): idx = numeric_idx other = np.ones(idx.values.shape, dtype=idx.values.dtype) * 2 + result = divmod(idx, Series(other)) with np.errstate(all='ignore'): div, mod = divmod(idx.values, other) - expected = Series(div), Series(mod) + expected = Series(div), Series(mod) for r, e in zip(result, expected): tm.assert_series_equal(r, e) diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index fa1a2d9df9a58..14a55785c243b 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -553,12 +553,6 @@ def test_td64arr_add_intlike(self, box_df_broadcast_failure): @pytest.mark.parametrize('scalar', [1, 1.5, np.array(2)]) def test_td64arr_add_sub_numeric_scalar_invalid(self, box, scalar, tdser): - - if box is pd.DataFrame and isinstance(scalar, np.ndarray): - # raises ValueError - pytest.xfail(reason="reversed ops return incorrect answers " - "instead of raising.") - tdser = tm.box_expected(tdser, box) err = TypeError if box is pd.Index and not isinstance(scalar, float):
- [x] closes #19252 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/23271
2018-10-22T04:35:44Z
2018-10-23T02:56:49Z
2018-10-23T02:56:49Z
2018-10-23T02:59:57Z
CLN: Removed all occurances of `goal_time` and enabled linting for benchmarks
diff --git a/asv_bench/benchmarks/algorithms.py b/asv_bench/benchmarks/algorithms.py index baac179355022..1ab88dc9f9e6d 100644 --- a/asv_bench/benchmarks/algorithms.py +++ b/asv_bench/benchmarks/algorithms.py @@ -15,8 +15,6 @@ class Factorize(object): - goal_time = 0.2 - params = [True, False] param_names = ['sort'] @@ -38,8 +36,6 @@ def time_factorize_string(self, sort): class Duplicated(object): - goal_time = 0.2 - params = ['first', 'last', False] param_names = ['keep'] @@ -61,8 +57,6 @@ def time_duplicated_string(self, keep): class DuplicatedUniqueIndex(object): - goal_time = 0.2 - def setup(self): N = 10**5 self.idx_int_dup = pd.Int64Index(np.arange(N * 5)) @@ -75,8 +69,6 @@ def time_duplicated_unique_int(self): class Match(object): - goal_time = 0.2 - def setup(self): self.uniques = tm.makeStringIndex(1000).values self.all = self.uniques.repeat(10) @@ -88,8 +80,6 @@ def time_match_string(self): class Hashing(object): - goal_time = 0.2 - def setup_cache(self): N = 10**5 diff --git a/asv_bench/benchmarks/attrs_caching.py b/asv_bench/benchmarks/attrs_caching.py index 7fb9fd26ad8ba..d061755208c9e 100644 --- a/asv_bench/benchmarks/attrs_caching.py +++ b/asv_bench/benchmarks/attrs_caching.py @@ -8,8 +8,6 @@ class DataFrameAttributes(object): - goal_time = 0.2 - def setup(self): self.df = DataFrame(np.random.randn(10, 6)) self.cur_index = self.df.index @@ -23,8 +21,6 @@ def time_set_index(self): class CacheReadonly(object): - goal_time = 0.2 - def setup(self): class Foo: diff --git a/asv_bench/benchmarks/binary_ops.py b/asv_bench/benchmarks/binary_ops.py index 35787920dc789..dfdebec86d67c 100644 --- a/asv_bench/benchmarks/binary_ops.py +++ b/asv_bench/benchmarks/binary_ops.py @@ -9,8 +9,6 @@ class Ops(object): - goal_time = 0.2 - params = [[True, False], ['default', 1]] param_names = ['use_numexpr', 'threads'] @@ -42,8 +40,6 @@ def teardown(self, use_numexpr, threads): class Ops2(object): - goal_time = 0.2 - def setup(self): N = 10**3 self.df = DataFrame(np.random.randn(N, N)) @@ -81,8 +77,6 @@ def time_frame_float_mod(self): class Timeseries(object): - goal_time = 0.2 - params = [None, 'US/Eastern'] param_names = ['tz'] @@ -109,8 +103,6 @@ def time_timestamp_ops_diff_with_shift(self, tz): class AddOverflowScalar(object): - goal_time = 0.2 - params = [1, -1, 0] param_names = ['scalar'] @@ -124,8 +116,6 @@ def time_add_overflow_scalar(self, scalar): class AddOverflowArray(object): - goal_time = 0.2 - def setup(self): N = 10**6 self.arr = np.arange(N) diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py index 418e60eb6d6d3..8a0fbc48755b5 100644 --- a/asv_bench/benchmarks/categoricals.py +++ b/asv_bench/benchmarks/categoricals.py @@ -14,8 +14,6 @@ class Concat(object): - goal_time = 0.2 - def setup(self): N = 10**5 self.s = pd.Series(list('aabbcd') * N).astype('category') @@ -32,8 +30,6 @@ def time_union(self): class Constructor(object): - goal_time = 0.2 - def setup(self): N = 10**5 self.categories = list('abcde') @@ -75,8 +71,6 @@ def time_from_codes_all_int8(self): class ValueCounts(object): - goal_time = 0.2 - params = [True, False] param_names = ['dropna'] @@ -91,8 +85,6 @@ def time_value_counts(self, dropna): class Repr(object): - goal_time = 0.2 - def setup(self): self.sel = pd.Series(['s1234']).astype('category') @@ -102,8 +94,6 @@ def time_rendering(self): class SetCategories(object): - goal_time = 0.2 - def setup(self): n = 5 * 10**5 arr = ['s%04d' % i for i in np.random.randint(0, n // 10, size=n)] @@ -115,8 +105,6 @@ def time_set_categories(self): class Rank(object): - goal_time = 0.2 - def setup(self): N = 10**5 ncats = 100 @@ -154,8 +142,6 @@ def time_rank_int_cat_ordered(self): class Isin(object): - goal_time = 0.2 - params = ['object', 'int64'] param_names = ['dtype'] @@ -195,8 +181,6 @@ def time_categorical_series_is_monotonic_decreasing(self): class Contains(object): - goal_time = 0.2 - def setup(self): N = 10**5 self.ci = tm.makeCategoricalIndex(N) @@ -212,7 +196,6 @@ def time_categorical_contains(self): class CategoricalSlicing(object): - goal_time = 0.2 params = ['monotonic_incr', 'monotonic_decr', 'non_monotonic'] param_names = ['index'] diff --git a/asv_bench/benchmarks/ctors.py b/asv_bench/benchmarks/ctors.py index 94dbd05917455..198ed1c90a2e9 100644 --- a/asv_bench/benchmarks/ctors.py +++ b/asv_bench/benchmarks/ctors.py @@ -5,8 +5,6 @@ class SeriesConstructors(object): - goal_time = 0.2 - param_names = ["data_fmt", "with_index"] params = [[lambda x: x, list, @@ -30,8 +28,6 @@ def time_series_constructor(self, data_fmt, with_index): class SeriesDtypesConstructors(object): - goal_time = 0.2 - def setup(self): N = 10**4 self.arr = np.random.randn(N, N) @@ -54,8 +50,6 @@ def time_dtindex_from_index_with_series(self): class MultiIndexConstructor(object): - goal_time = 0.2 - def setup(self): N = 10**4 self.iterables = [tm.makeStringIndex(N), range(20)] diff --git a/asv_bench/benchmarks/eval.py b/asv_bench/benchmarks/eval.py index da2d7dc7c4492..837478efbad64 100644 --- a/asv_bench/benchmarks/eval.py +++ b/asv_bench/benchmarks/eval.py @@ -8,8 +8,6 @@ class Eval(object): - goal_time = 0.2 - params = [['numexpr', 'python'], [1, 'all']] param_names = ['engine', 'threads'] @@ -41,8 +39,6 @@ def teardown(self, engine, threads): class Query(object): - goal_time = 0.2 - def setup(self): N = 10**6 halfway = (N // 2) - 1 diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py index d3f1a416a7cc1..60f6a66e07a7b 100644 --- a/asv_bench/benchmarks/frame_ctor.py +++ b/asv_bench/benchmarks/frame_ctor.py @@ -10,8 +10,6 @@ class FromDicts(object): - goal_time = 0.2 - def setup(self): N, K = 5000, 50 self.index = tm.makeStringIndex(N) @@ -45,8 +43,6 @@ def time_nested_dict_int64(self): class FromSeries(object): - goal_time = 0.2 - def setup(self): mi = MultiIndex.from_product([range(100), range(100)]) self.s = Series(np.random.randn(10000), index=mi) @@ -57,7 +53,6 @@ def time_mi_series(self): class FromDictwithTimestamp(object): - goal_time = 0.2 params = [Nano(1), Hour(1)] param_names = ['offset'] @@ -74,7 +69,6 @@ def time_dict_with_timestamp_offsets(self, offset): class FromRecords(object): - goal_time = 0.2 params = [None, 1000] param_names = ['nrows'] @@ -89,8 +83,6 @@ def time_frame_from_records_generator(self, nrows): class FromNDArray(object): - goal_time = 0.2 - def setup(self): N = 100000 self.data = np.random.randn(N) diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index 89fd879746f68..b60b45cc29f7d 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -9,8 +9,6 @@ class GetNumericData(object): - goal_time = 0.2 - def setup(self): self.df = DataFrame(np.random.randn(10000, 25)) self.df['foo'] = 'bar' @@ -24,8 +22,6 @@ def time_frame_get_numeric_data(self): class Lookup(object): - goal_time = 0.2 - def setup(self): self.df = DataFrame(np.random.randn(10000, 8), columns=list('abcdefgh')) @@ -46,8 +42,6 @@ def time_frame_fancy_lookup_all(self): class Reindex(object): - goal_time = 0.2 - def setup(self): N = 10**3 self.df = DataFrame(np.random.randn(N * 10, N)) @@ -77,8 +71,6 @@ def time_reindex_upcast(self): class Iteration(object): - goal_time = 0.2 - def setup(self): N = 1000 self.df = DataFrame(np.random.randn(N * 10, N)) @@ -112,8 +104,6 @@ def time_iterrows(self): class ToString(object): - goal_time = 0.2 - def setup(self): self.df = DataFrame(np.random.randn(100, 10)) @@ -123,8 +113,6 @@ def time_to_string_floats(self): class ToHTML(object): - goal_time = 0.2 - def setup(self): nrows = 500 self.df2 = DataFrame(np.random.randn(nrows, 10)) @@ -137,8 +125,6 @@ def time_to_html_mixed(self): class Repr(object): - goal_time = 0.2 - def setup(self): nrows = 10000 data = np.random.randn(nrows, 10) @@ -164,8 +150,6 @@ def time_frame_repr_wide(self): class MaskBool(object): - goal_time = 0.2 - def setup(self): data = np.random.randn(1000, 500) df = DataFrame(data) @@ -182,8 +166,6 @@ def time_frame_mask_floats(self): class Isnull(object): - goal_time = 0.2 - def setup(self): N = 10**3 self.df_no_null = DataFrame(np.random.randn(N, N)) @@ -216,7 +198,6 @@ def time_isnull_obj(self): class Fillna(object): - goal_time = 0.2 params = ([True, False], ['pad', 'bfill']) param_names = ['inplace', 'method'] @@ -231,7 +212,6 @@ def time_frame_fillna(self, inplace, method): class Dropna(object): - goal_time = 0.2 params = (['all', 'any'], [0, 1]) param_names = ['how', 'axis'] @@ -252,8 +232,6 @@ def time_dropna_axis_mixed_dtypes(self, how, axis): class Count(object): - goal_time = 0.2 - params = [0, 1] param_names = ['axis'] @@ -282,8 +260,6 @@ def time_count_level_mixed_dtypes_multi(self, axis): class Apply(object): - goal_time = 0.2 - def setup(self): self.df = DataFrame(np.random.randn(1000, 100)) @@ -312,8 +288,6 @@ def time_apply_ref_by_name(self): class Dtypes(object): - goal_time = 0.2 - def setup(self): self.df = DataFrame(np.random.randn(1000, 1000)) @@ -323,8 +297,6 @@ def time_frame_dtypes(self): class Equals(object): - goal_time = 0.2 - def setup(self): N = 10**3 self.float_df = DataFrame(np.random.randn(N, N)) @@ -361,7 +333,6 @@ def time_frame_object_unequal(self): class Interpolate(object): - goal_time = 0.2 params = [None, 'infer'] param_names = ['downcast'] @@ -387,7 +358,6 @@ def time_interpolate_some_good(self, downcast): class Shift(object): # frame shift speedup issue-5609 - goal_time = 0.2 params = [0, 1] param_names = ['axis'] @@ -409,8 +379,6 @@ def time_frame_nunique(self): class Duplicated(object): - goal_time = 0.2 - def setup(self): n = (1 << 20) t = date_range('2015-01-01', freq='S', periods=(n // 64)) @@ -429,7 +397,6 @@ def time_frame_duplicated_wide(self): class XS(object): - goal_time = 0.2 params = [0, 1] param_names = ['axis'] @@ -443,7 +410,6 @@ def time_frame_xs(self, axis): class SortValues(object): - goal_time = 0.2 params = [True, False] param_names = ['ascending'] @@ -456,8 +422,6 @@ def time_frame_sort_values(self, ascending): class SortIndexByColumns(object): - goal_time = 0.2 - def setup(self): N = 10000 K = 10 @@ -471,7 +435,6 @@ def time_frame_sort_values_by_columns(self): class Quantile(object): - goal_time = 0.2 params = [0, 1] param_names = ['axis'] @@ -484,8 +447,6 @@ def time_frame_quantile(self, axis): class GetDtypeCounts(object): # 2807 - goal_time = 0.2 - def setup(self): self.df = DataFrame(np.random.randn(10, 10000)) @@ -498,7 +459,6 @@ def time_info(self): class NSort(object): - goal_time = 0.2 params = ['first', 'last', 'all'] param_names = ['keep'] @@ -521,8 +481,6 @@ def time_nsmallest_two_columns(self, keep): class Describe(object): - goal_time = 0.2 - def setup(self): self.df = DataFrame({ 'a': np.random.randint(0, 100, int(1e6)), diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py index 32cb60be3f485..6819a296c81df 100644 --- a/asv_bench/benchmarks/gil.py +++ b/asv_bench/benchmarks/gil.py @@ -28,7 +28,6 @@ def wrapper(fname): class ParallelGroupbyMethods(object): - goal_time = 0.2 params = ([2, 4, 8], ['count', 'last', 'max', 'mean', 'min', 'prod', 'sum', 'var']) param_names = ['threads', 'method'] @@ -60,7 +59,6 @@ def time_loop(self, threads, method): class ParallelGroups(object): - goal_time = 0.2 params = [2, 4, 8] param_names = ['threads'] @@ -82,7 +80,6 @@ def time_get_groups(self, threads): class ParallelTake1D(object): - goal_time = 0.2 params = ['int64', 'float64'] param_names = ['dtype'] @@ -126,8 +123,6 @@ def time_kth_smallest(self): class ParallelDatetimeFields(object): - goal_time = 0.2 - def setup(self): if not have_real_test_parallel: raise NotImplementedError @@ -174,7 +169,6 @@ def run(period): class ParallelRolling(object): - goal_time = 0.2 params = ['median', 'mean', 'min', 'max', 'var', 'skew', 'kurt', 'std'] param_names = ['method'] diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index be09bba97bea3..dbd79185ec006 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -20,8 +20,6 @@ class ApplyDictReturn(object): - goal_time = 0.2 - def setup(self): self.labels = np.arange(1000).repeat(10) self.data = Series(np.random.randn(len(self.labels))) @@ -33,8 +31,6 @@ def time_groupby_apply_dict_return(self): class Apply(object): - goal_time = 0.2 - def setup_cache(self): N = 10**4 labels = np.random.randint(0, 2000, size=N) @@ -67,8 +63,6 @@ def time_copy_overhead_single_col(self, df): class Groups(object): - goal_time = 0.2 - param_names = ['key'] params = ['int64_small', 'int64_large', 'object_small', 'object_large'] @@ -93,7 +87,6 @@ def time_series_groups(self, data, key): class GroupManyLabels(object): - goal_time = 0.2 params = [1, 1000] param_names = ['ncols'] @@ -109,8 +102,6 @@ def time_sum(self, ncols): class Nth(object): - goal_time = 0.2 - param_names = ['dtype'] params = ['float32', 'float64', 'datetime', 'object'] @@ -149,8 +140,6 @@ def time_series_nth(self, dtype): class DateAttributes(object): - goal_time = 0.2 - def setup(self): rng = date_range('1/1/2000', '12/31/2005', freq='H') self.year, self.month, self.day = rng.year, rng.month, rng.day @@ -162,8 +151,6 @@ def time_len_groupby_object(self): class Int64(object): - goal_time = 0.2 - def setup(self): arr = np.random.randint(-1 << 12, 1 << 12, (1 << 17, 5)) i = np.random.choice(len(arr), len(arr) * 5) @@ -180,8 +167,6 @@ def time_overflow(self): class CountMultiDtype(object): - goal_time = 0.2 - def setup_cache(self): n = 10000 offsets = np.random.randint(n, size=n).astype('timedelta64[ns]') @@ -208,8 +193,6 @@ def time_multi_count(self, df): class CountMultiInt(object): - goal_time = 0.2 - def setup_cache(self): n = 10000 df = DataFrame({'key1': np.random.randint(0, 500, size=n), @@ -227,8 +210,6 @@ def time_multi_int_nunique(self, df): class AggFunctions(object): - goal_time = 0.2 - def setup_cache(): N = 10**5 fac1 = np.array(['A', 'B', 'C'], dtype='O') @@ -259,8 +240,6 @@ def time_different_python_functions_singlecol(self, df): class GroupStrings(object): - goal_time = 0.2 - def setup(self): n = 2 * 10**5 alpha = list(map(''.join, product(ascii_letters, repeat=4))) @@ -276,8 +255,6 @@ def time_multi_columns(self): class MultiColumn(object): - goal_time = 0.2 - def setup_cache(self): N = 10**5 key1 = np.tile(np.arange(100, dtype=object), 1000) @@ -305,8 +282,6 @@ def time_col_select_numpy_sum(self, df): class Size(object): - goal_time = 0.2 - def setup(self): n = 10**5 offsets = np.random.randint(n, size=n).astype('timedelta64[ns]') @@ -334,8 +309,6 @@ def time_category_size(self): class GroupByMethods(object): - goal_time = 0.2 - param_names = ['dtype', 'method', 'application'] params = [['int', 'float', 'object', 'datetime'], ['all', 'any', 'bfill', 'count', 'cumcount', 'cummax', 'cummin', @@ -385,7 +358,6 @@ def time_dtype_as_field(self, dtype, method, application): class RankWithTies(object): # GH 21237 - goal_time = 0.2 param_names = ['dtype', 'tie_method'] params = [['float64', 'float32', 'int64', 'datetime64'], ['first', 'average', 'dense', 'min', 'max']] @@ -404,8 +376,6 @@ def time_rank_ties(self, dtype, tie_method): class Float32(object): # GH 13335 - goal_time = 0.2 - def setup(self): tmp1 = (np.random.random(10000) * 0.1).astype(np.float32) tmp2 = (np.random.random(10000) * 10.0).astype(np.float32) @@ -419,8 +389,6 @@ def time_sum(self): class Categories(object): - goal_time = 0.2 - def setup(self): N = 10**5 arr = np.random.random(N) @@ -457,7 +425,6 @@ def time_groupby_extra_cat_nosort(self): class Datelike(object): # GH 14338 - goal_time = 0.2 params = ['period_range', 'date_range', 'date_range_tz'] param_names = ['grouper'] @@ -475,8 +442,6 @@ def time_sum(self, grouper): class SumBools(object): # GH 2692 - goal_time = 0.2 - def setup(self): N = 500 self.df = DataFrame({'ii': range(N), @@ -488,7 +453,6 @@ def time_groupby_sum_booleans(self): class SumMultiLevel(object): # GH 9049 - goal_time = 0.2 timeout = 120.0 def setup(self): @@ -503,8 +467,6 @@ def time_groupby_sum_multiindex(self): class Transform(object): - goal_time = 0.2 - def setup(self): n1 = 400 n2 = 250 @@ -551,8 +513,6 @@ def time_transform_multi_key4(self): class TransformBools(object): - goal_time = 0.2 - def setup(self): N = 120000 transition_points = np.sort(np.random.choice(np.arange(N), 1400)) @@ -567,8 +527,6 @@ def time_transform_mean(self): class TransformNaN(object): # GH 12737 - goal_time = 0.2 - def setup(self): self.df_nans = DataFrame({'key': np.repeat(np.arange(1000), 10), 'B': np.nan, diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py index c1bc53823a342..f76040921393f 100644 --- a/asv_bench/benchmarks/index_object.py +++ b/asv_bench/benchmarks/index_object.py @@ -6,7 +6,6 @@ class SetOperations(object): - goal_time = 0.2 params = (['datetime', 'date_string', 'int', 'strings'], ['intersection', 'union', 'symmetric_difference']) param_names = ['dtype', 'method'] @@ -32,8 +31,6 @@ def time_operation(self, dtype, method): class SetDisjoint(object): - goal_time = 0.2 - def setup(self): N = 10**5 B = N + 20000 @@ -46,8 +43,6 @@ def time_datetime_difference_disjoint(self): class Datetime(object): - goal_time = 0.2 - def setup(self): self.dr = date_range('20000101', freq='D', periods=10000) @@ -84,8 +79,6 @@ def time_modulo(self, dtype): class Range(object): - goal_time = 0.2 - def setup(self): self.idx_inc = RangeIndex(start=0, stop=10**7, step=3) self.idx_dec = RangeIndex(start=10**7, stop=-1, step=-3) @@ -105,8 +98,6 @@ def time_min_trivial(self): class IndexAppend(object): - goal_time = 0.2 - def setup(self): N = 10000 @@ -136,7 +127,6 @@ def time_append_obj_list(self): class Indexing(object): - goal_time = 0.2 params = ['String', 'Float', 'Int'] param_names = ['dtype'] @@ -181,8 +171,6 @@ def time_get_loc_non_unique_sorted(self, dtype): class Float64IndexMethod(object): # GH 13166 - goal_time = 0.2 - def setup(self): N = 100000 a = np.arange(N) diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 49d6311a7bb66..57ba9cd80e55c 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -10,7 +10,6 @@ class NumericSeriesIndexing(object): - goal_time = 0.2 params = [ (Int64Index, UInt64Index, Float64Index), ('unique_monotonic_inc', 'nonunique_monotonic_inc'), @@ -82,7 +81,6 @@ def time_loc_slice(self, index, index_structure): class NonNumericSeriesIndexing(object): - goal_time = 0.2 params = [ ('string', 'datetime'), ('unique_monotonic_inc', 'nonunique_monotonic_inc'), @@ -118,8 +116,6 @@ def time_getitem_list_like(self, index, index_structure): class DataFrameStringIndexing(object): - goal_time = 0.2 - def setup(self): index = tm.makeStringIndex(1000) columns = tm.makeStringIndex(30) @@ -152,8 +148,6 @@ def time_boolean_rows_object(self): class DataFrameNumericIndexing(object): - goal_time = 0.2 - def setup(self): self.idx_dupe = np.array(range(30)) * 99 self.df = DataFrame(np.random.randn(10000, 5)) @@ -178,7 +172,6 @@ def time_bool_indexer(self): class Take(object): - goal_time = 0.2 params = ['int', 'datetime'] param_names = ['index'] @@ -196,8 +189,6 @@ def time_take(self, index): class MultiIndexing(object): - goal_time = 0.2 - def setup(self): mi = MultiIndex.from_product([range(1000), range(1000)]) self.s = Series(np.random.randn(1000000), index=mi) @@ -226,8 +217,6 @@ def time_index_slice(self): class IntervalIndexing(object): - goal_time = 0.2 - def setup_cache(self): idx = IntervalIndex.from_breaks(np.arange(1000001)) monotonic = Series(np.arange(1000000), index=idx) @@ -248,7 +237,6 @@ def time_loc_list(self, monotonic): class CategoricalIndexIndexing(object): - goal_time = 0.2 params = ['monotonic_incr', 'monotonic_decr', 'non_monotonic'] param_names = ['index'] @@ -291,8 +279,6 @@ def time_get_indexer_list(self, index): class PanelIndexing(object): - goal_time = 0.2 - def setup(self): with warnings.catch_warnings(record=True): self.p = Panel(np.random.randn(100, 100, 100)) @@ -305,8 +291,6 @@ def time_subset(self): class MethodLookup(object): - goal_time = 0.2 - def setup_cache(self): s = Series() return s @@ -323,8 +307,6 @@ def time_lookup_loc(self, s): class GetItemSingleColumn(object): - goal_time = 0.2 - def setup(self): self.df_string_col = DataFrame(np.random.randn(3000, 1), columns=['A']) self.df_int_col = DataFrame(np.random.randn(3000, 1)) @@ -338,8 +320,6 @@ def time_frame_getitem_single_column_int(self): class AssignTimeseriesIndex(object): - goal_time = 0.2 - def setup(self): N = 100000 idx = date_range('1/1/2000', periods=N, freq='H') @@ -351,8 +331,6 @@ def time_frame_assign_timeseries_index(self): class InsertColumns(object): - goal_time = 0.2 - def setup(self): self.N = 10**3 self.df = DataFrame(index=range(self.N)) diff --git a/asv_bench/benchmarks/indexing_engines.py b/asv_bench/benchmarks/indexing_engines.py index 243f2ada7be32..1e9283c7fb92b 100644 --- a/asv_bench/benchmarks/indexing_engines.py +++ b/asv_bench/benchmarks/indexing_engines.py @@ -6,7 +6,6 @@ class NumericEngineIndexing(object): - goal_time = 0.2 params = [[Int64Engine, UInt64Engine, Float64Engine], [np.int64, np.uint64, np.float64], ['monotonic_incr', 'monotonic_decr', 'non_monotonic'], @@ -33,7 +32,6 @@ def time_get_loc(self, engine, dtype, index_type): class ObjectEngineIndexing(object): - goal_time = 0.2 params = [('monotonic_incr', 'monotonic_decr', 'non_monotonic')] param_names = ['index_type'] diff --git a/asv_bench/benchmarks/inference.py b/asv_bench/benchmarks/inference.py index 7fb57991c99bc..423bd02b93596 100644 --- a/asv_bench/benchmarks/inference.py +++ b/asv_bench/benchmarks/inference.py @@ -7,7 +7,6 @@ class NumericInferOps(object): # from GH 7332 - goal_time = 0.2 params = numeric_dtypes param_names = ['dtype'] @@ -34,8 +33,6 @@ def time_modulo(self, dtype): class DateInferOps(object): # from GH 7332 - goal_time = 0.2 - def setup_cache(self): N = 5 * 10**5 df = DataFrame({'datetime64': np.arange(N).astype('datetime64[ms]')}) @@ -54,7 +51,6 @@ def time_add_timedeltas(self, df): class ToNumeric(object): - goal_time = 0.2 params = ['ignore', 'coerce'] param_names = ['errors'] diff --git a/asv_bench/benchmarks/io/csv.py b/asv_bench/benchmarks/io/csv.py index ac2370fe85e5a..771f2795334e1 100644 --- a/asv_bench/benchmarks/io/csv.py +++ b/asv_bench/benchmarks/io/csv.py @@ -11,7 +11,6 @@ class ToCSV(BaseIO): - goal_time = 0.2 fname = '__test__.csv' params = ['wide', 'long', 'mixed'] param_names = ['kind'] @@ -41,7 +40,6 @@ def time_frame(self, kind): class ToCSVDatetime(BaseIO): - goal_time = 0.2 fname = '__test__.csv' def setup(self): @@ -61,7 +59,6 @@ def data(self, stringio_object): class ReadCSVDInferDatetimeFormat(StringIORewind): - goal_time = 0.2 params = ([True, False], ['custom', 'iso8601', 'ymd']) param_names = ['infer_datetime_format', 'format'] @@ -82,7 +79,6 @@ def time_read_csv(self, infer_datetime_format, format): class ReadCSVSkipRows(BaseIO): - goal_time = 0.2 fname = '__test__.csv' params = [None, 10000] param_names = ['skiprows'] @@ -104,8 +100,6 @@ def time_skipprows(self, skiprows): class ReadUint64Integers(StringIORewind): - goal_time = 0.2 - def setup(self): self.na_values = [2**63 + 500] arr = np.arange(10000).astype('uint64') + 2**63 @@ -127,7 +121,6 @@ def time_read_uint64_na_values(self): class ReadCSVThousands(BaseIO): - goal_time = 0.2 fname = '__test__.csv' params = ([',', '|'], [None, ',']) param_names = ['sep', 'thousands'] @@ -149,8 +142,6 @@ def time_thousands(self, sep, thousands): class ReadCSVComment(StringIORewind): - goal_time = 0.2 - def setup(self): data = ['A,B,C'] + (['1,2,3 # comment'] * 100000) self.StringIO_input = StringIO('\n'.join(data)) @@ -162,7 +153,6 @@ def time_comment(self): class ReadCSVFloatPrecision(StringIORewind): - goal_time = 0.2 params = ([',', ';'], ['.', '_'], [None, 'high', 'round_trip']) param_names = ['sep', 'decimal', 'float_precision'] @@ -185,7 +175,6 @@ def time_read_csv_python_engine(self, sep, decimal, float_precision): class ReadCSVCategorical(BaseIO): - goal_time = 0.2 fname = '__test__.csv' def setup(self): @@ -203,8 +192,6 @@ def time_convert_direct(self): class ReadCSVParseDates(StringIORewind): - goal_time = 0.2 - def setup(self): data = """{},19:00:00,18:56:00,0.8100,2.8100,7.2000,0.0000,280.0000\n {},20:00:00,19:56:00,0.0100,2.2100,7.2000,0.0000,260.0000\n diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py index b873dc1040a66..1bee864fbcf2d 100644 --- a/asv_bench/benchmarks/io/excel.py +++ b/asv_bench/benchmarks/io/excel.py @@ -3,12 +3,9 @@ from pandas.compat import BytesIO import pandas.util.testing as tm -from ..pandas_vb_common import BaseIO - class Excel(object): - goal_time = 0.2 params = ['openpyxl', 'xlsxwriter', 'xlwt'] param_names = ['engine'] diff --git a/asv_bench/benchmarks/io/hdf.py b/asv_bench/benchmarks/io/hdf.py index c150d82450770..f08904ba70a5f 100644 --- a/asv_bench/benchmarks/io/hdf.py +++ b/asv_bench/benchmarks/io/hdf.py @@ -9,8 +9,6 @@ class HDFStoreDataFrame(BaseIO): - goal_time = 0.2 - def setup(self): N = 25000 index = tm.makeStringIndex(N) @@ -103,8 +101,6 @@ def time_store_info(self): class HDFStorePanel(BaseIO): - goal_time = 0.2 - def setup(self): self.fname = '__test__.h5' with warnings.catch_warnings(record=True): @@ -130,7 +126,6 @@ def time_write_store_table_panel(self): class HDF(BaseIO): - goal_time = 0.2 params = ['table', 'fixed'] param_names = ['format'] diff --git a/asv_bench/benchmarks/io/json.py b/asv_bench/benchmarks/io/json.py index df5bf7341c303..ec2ddc11b7c1d 100644 --- a/asv_bench/benchmarks/io/json.py +++ b/asv_bench/benchmarks/io/json.py @@ -7,7 +7,6 @@ class ReadJSON(BaseIO): - goal_time = 0.2 fname = "__test__.json" params = (['split', 'index', 'records'], ['int', 'datetime']) param_names = ['orient', 'index'] @@ -27,7 +26,6 @@ def time_read_json(self, orient, index): class ReadJSONLines(BaseIO): - goal_time = 0.2 fname = "__test_lines__.json" params = ['int', 'datetime'] param_names = ['index'] @@ -58,7 +56,6 @@ def peakmem_read_json_lines_concat(self, index): class ToJSON(BaseIO): - goal_time = 0.2 fname = "__test__.json" params = ['split', 'columns', 'index'] param_names = ['orient'] diff --git a/asv_bench/benchmarks/io/msgpack.py b/asv_bench/benchmarks/io/msgpack.py index 7033aa9ce3c40..dc2642d920fd0 100644 --- a/asv_bench/benchmarks/io/msgpack.py +++ b/asv_bench/benchmarks/io/msgpack.py @@ -7,8 +7,6 @@ class MSGPack(BaseIO): - goal_time = 0.2 - def setup(self): self.fname = '__test__.msg' N = 100000 diff --git a/asv_bench/benchmarks/io/pickle.py b/asv_bench/benchmarks/io/pickle.py index 0960d721281c7..74a58bbb946aa 100644 --- a/asv_bench/benchmarks/io/pickle.py +++ b/asv_bench/benchmarks/io/pickle.py @@ -7,8 +7,6 @@ class Pickle(BaseIO): - goal_time = 0.2 - def setup(self): self.fname = '__test__.pkl' N = 100000 diff --git a/asv_bench/benchmarks/io/sas.py b/asv_bench/benchmarks/io/sas.py index 526c524de7fff..2783f42cad895 100644 --- a/asv_bench/benchmarks/io/sas.py +++ b/asv_bench/benchmarks/io/sas.py @@ -5,7 +5,6 @@ class SAS(object): - goal_time = 0.2 params = ['sas7bdat', 'xport'] param_names = ['format'] diff --git a/asv_bench/benchmarks/io/sql.py b/asv_bench/benchmarks/io/sql.py index 6a8529cad592b..075d3bdda5ed9 100644 --- a/asv_bench/benchmarks/io/sql.py +++ b/asv_bench/benchmarks/io/sql.py @@ -8,7 +8,6 @@ class SQL(object): - goal_time = 0.2 params = ['sqlalchemy', 'sqlite'] param_names = ['connection'] @@ -41,7 +40,6 @@ def time_read_sql_query(self, connection): class WriteSQLDtypes(object): - goal_time = 0.2 params = (['sqlalchemy', 'sqlite'], ['float', 'float_with_nan', 'string', 'bool', 'int', 'datetime']) param_names = ['connection', 'dtype'] @@ -75,8 +73,6 @@ def time_read_sql_query_select_column(self, connection, dtype): class ReadSQLTable(object): - goal_time = 0.2 - def setup(self): N = 10000 self.table_name = 'test' @@ -104,8 +100,6 @@ def time_read_sql_table_parse_dates(self): class ReadSQLTableDtypes(object): - goal_time = 0.2 - params = ['float', 'float_with_nan', 'string', 'bool', 'int', 'datetime'] param_names = ['dtype'] diff --git a/asv_bench/benchmarks/io/stata.py b/asv_bench/benchmarks/io/stata.py index d74a531877e18..a7f854a853f50 100644 --- a/asv_bench/benchmarks/io/stata.py +++ b/asv_bench/benchmarks/io/stata.py @@ -7,7 +7,6 @@ class Stata(BaseIO): - goal_time = 0.2 params = ['tc', 'td', 'tm', 'tw', 'th', 'tq', 'ty'] param_names = ['convert_dates'] diff --git a/asv_bench/benchmarks/join_merge.py b/asv_bench/benchmarks/join_merge.py index 3524a5adb5450..5b28d8a4eec62 100644 --- a/asv_bench/benchmarks/join_merge.py +++ b/asv_bench/benchmarks/join_merge.py @@ -14,8 +14,6 @@ class Append(object): - goal_time = 0.2 - def setup(self): self.df1 = DataFrame(np.random.randn(10000, 4), columns=['A', 'B', 'C', 'D']) @@ -42,7 +40,6 @@ def time_append_mixed(self): class Concat(object): - goal_time = 0.2 params = [0, 1] param_names = ['axis'] @@ -71,7 +68,6 @@ def time_concat_empty_left(self, axis): class ConcatPanels(object): - goal_time = 0.2 params = ([0, 1, 2], [True, False]) param_names = ['axis', 'ignore_index'] @@ -97,7 +93,6 @@ def time_f_ordered(self, axis, ignore_index): class ConcatDataFrames(object): - goal_time = 0.2 params = ([0, 1], [True, False]) param_names = ['axis', 'ignore_index'] @@ -118,7 +113,6 @@ def time_f_ordered(self, axis, ignore_index): class Join(object): - goal_time = 0.2 params = [True, False] param_names = ['sort'] @@ -166,8 +160,6 @@ def time_join_dataframe_index_shuffle_key_bigger_sort(self, sort): class JoinIndex(object): - goal_time = 0.2 - def setup(self): N = 50000 self.left = DataFrame(np.random.randint(1, N / 500, (N, 2)), @@ -182,8 +174,6 @@ def time_left_outer_join_index(self): class JoinNonUnique(object): # outer join of non-unique # GH 6329 - goal_time = 0.2 - def setup(self): date_index = date_range('01-Jan-2013', '23-Jan-2013', freq='T') daily_dates = date_index.to_period('D').to_timestamp('S', 'S') @@ -200,7 +190,6 @@ def time_join_non_unique_equal(self): class Merge(object): - goal_time = 0.2 params = [True, False] param_names = ['sort'] @@ -235,7 +224,6 @@ def time_merge_dataframe_integer_key(self, sort): class I8Merge(object): - goal_time = 0.2 params = ['inner', 'outer', 'left', 'right'] param_names = ['how'] @@ -254,8 +242,6 @@ def time_i8merge(self, how): class MergeCategoricals(object): - goal_time = 0.2 - def setup(self): self.left_object = DataFrame( {'X': np.random.choice(range(0, 10), size=(10000,)), @@ -343,8 +329,6 @@ def time_multiby(self): class Align(object): - goal_time = 0.2 - def setup(self): size = 5 * 10**5 rng = np.arange(0, 10**13, 10**7) diff --git a/asv_bench/benchmarks/multiindex_object.py b/asv_bench/benchmarks/multiindex_object.py index eaf2bbbe510c2..ff202322dbe84 100644 --- a/asv_bench/benchmarks/multiindex_object.py +++ b/asv_bench/benchmarks/multiindex_object.py @@ -7,8 +7,6 @@ class GetLoc(object): - goal_time = 0.2 - def setup(self): self.mi_large = MultiIndex.from_product( [np.arange(1000), np.arange(20), list(string.ascii_letters)], @@ -44,8 +42,6 @@ def time_small_get_loc_warm(self): class Duplicates(object): - goal_time = 0.2 - def setup(self): size = 65536 arrays = [np.random.randint(0, 8192, size), @@ -60,8 +56,6 @@ def time_remove_unused_levels(self): class Integer(object): - goal_time = 0.2 - def setup(self): self.mi_int = MultiIndex.from_product([np.arange(1000), np.arange(1000)], @@ -80,8 +74,6 @@ def time_is_monotonic(self): class Duplicated(object): - goal_time = 0.2 - def setup(self): n, k = 200, 5000 levels = [np.arange(n), @@ -96,8 +88,6 @@ def time_duplicated(self): class Sortlevel(object): - goal_time = 0.2 - def setup(self): n = 1182720 low, high = -4096, 4096 @@ -122,8 +112,6 @@ def time_sortlevel_one(self): class Values(object): - goal_time = 0.2 - def setup_cache(self): level1 = range(1000) diff --git a/asv_bench/benchmarks/offset.py b/asv_bench/benchmarks/offset.py index e161b887ee86f..4570e73cccc71 100644 --- a/asv_bench/benchmarks/offset.py +++ b/asv_bench/benchmarks/offset.py @@ -34,8 +34,6 @@ class ApplyIndex(object): - goal_time = 0.2 - params = other_offsets param_names = ['offset'] @@ -49,8 +47,6 @@ def time_apply_index(self, offset): class OnOffset(object): - goal_time = 0.2 - params = offsets param_names = ['offset'] @@ -67,7 +63,6 @@ def time_on_offset(self, offset): class OffsetSeriesArithmetic(object): - goal_time = 0.2 params = offsets param_names = ['offset'] @@ -83,7 +78,6 @@ def time_add_offset(self, offset): class OffsetDatetimeIndexArithmetic(object): - goal_time = 0.2 params = offsets param_names = ['offset'] @@ -98,7 +92,6 @@ def time_add_offset(self, offset): class OffestDatetimeArithmetic(object): - goal_time = 0.2 params = offsets param_names = ['offset'] diff --git a/asv_bench/benchmarks/panel_ctor.py b/asv_bench/benchmarks/panel_ctor.py index c2e5bfa175feb..47b3ad612f9b1 100644 --- a/asv_bench/benchmarks/panel_ctor.py +++ b/asv_bench/benchmarks/panel_ctor.py @@ -5,8 +5,6 @@ class DifferentIndexes(object): - goal_time = 0.2 - def setup(self): self.data_frames = {} start = datetime(1990, 1, 1) @@ -24,8 +22,6 @@ def time_from_dict(self): class SameIndexes(object): - goal_time = 0.2 - def setup(self): idx = DatetimeIndex(start=datetime(1990, 1, 1), end=datetime(2012, 1, 1), @@ -40,8 +36,6 @@ def time_from_dict(self): class TwoIndexes(object): - goal_time = 0.2 - def setup(self): start = datetime(1990, 1, 1) end = datetime(2012, 1, 1) diff --git a/asv_bench/benchmarks/panel_methods.py b/asv_bench/benchmarks/panel_methods.py index 542af44a78ffe..a4c12c082236e 100644 --- a/asv_bench/benchmarks/panel_methods.py +++ b/asv_bench/benchmarks/panel_methods.py @@ -6,7 +6,6 @@ class PanelMethods(object): - goal_time = 0.2 params = ['items', 'major', 'minor'] param_names = ['axis'] diff --git a/asv_bench/benchmarks/period.py b/asv_bench/benchmarks/period.py index 29b8c7efda40c..fc34a47fee3e1 100644 --- a/asv_bench/benchmarks/period.py +++ b/asv_bench/benchmarks/period.py @@ -37,8 +37,6 @@ def time_asfreq(self, freq): class PeriodIndexConstructor(object): - goal_time = 0.2 - params = ['D'] param_names = ['freq'] @@ -55,8 +53,6 @@ def time_from_pydatetime(self, freq): class DataFramePeriodColumn(object): - goal_time = 0.2 - def setup(self): self.rng = period_range(start='1/1/1990', freq='S', periods=20000) self.df = DataFrame(index=range(len(self.rng))) @@ -72,8 +68,6 @@ def time_set_index(self): class Algorithms(object): - goal_time = 0.2 - params = ['index', 'series'] param_names = ['typ'] @@ -95,8 +89,6 @@ def time_value_counts(self, typ): class Indexing(object): - goal_time = 0.2 - def setup(self): self.index = PeriodIndex(start='1985', periods=1000, freq='D') self.series = Series(range(1000), index=self.index) diff --git a/asv_bench/benchmarks/plotting.py b/asv_bench/benchmarks/plotting.py index 68dc39b648152..1373d5f0b4258 100644 --- a/asv_bench/benchmarks/plotting.py +++ b/asv_bench/benchmarks/plotting.py @@ -10,8 +10,6 @@ class Plotting(object): - goal_time = 0.2 - def setup(self): self.s = Series(np.random.randn(1000000)) self.df = DataFrame({'col': self.s}) @@ -25,8 +23,6 @@ def time_frame_plot(self): class TimeseriesPlotting(object): - goal_time = 0.2 - def setup(self): N = 2000 M = 5 @@ -50,8 +46,6 @@ def time_plot_irregular(self): class Misc(object): - goal_time = 0.6 - def setup(self): N = 500 M = 10 diff --git a/asv_bench/benchmarks/reindex.py b/asv_bench/benchmarks/reindex.py index 13f2877e6048d..82c61a98e2c34 100644 --- a/asv_bench/benchmarks/reindex.py +++ b/asv_bench/benchmarks/reindex.py @@ -7,8 +7,6 @@ class Reindex(object): - goal_time = 0.2 - def setup(self): rng = DatetimeIndex(start='1/1/1970', periods=10000, freq='1min') self.df = DataFrame(np.random.rand(10000, 10), index=rng, @@ -37,7 +35,6 @@ def time_reindex_multiindex(self): class ReindexMethod(object): - goal_time = 0.2 params = ['pad', 'backfill'] param_names = ['method'] @@ -52,7 +49,6 @@ def time_reindex_method(self, method): class Fillna(object): - goal_time = 0.2 params = ['pad', 'backfill'] param_names = ['method'] @@ -72,8 +68,6 @@ def time_float_32(self, method): class LevelAlign(object): - goal_time = 0.2 - def setup(self): self.index = MultiIndex( levels=[np.arange(10), np.arange(100), np.arange(100)], @@ -94,7 +88,6 @@ def time_reindex_level(self): class DropDuplicates(object): - goal_time = 0.2 params = [True, False] param_names = ['inplace'] @@ -139,8 +132,6 @@ def time_frame_drop_dups_bool(self, inplace): class Align(object): # blog "pandas escaped the zoo" - goal_time = 0.2 - def setup(self): n = 50000 indices = tm.makeStringIndex(n) @@ -156,8 +147,6 @@ def time_align_series_irregular_string(self): class LibFastZip(object): - goal_time = 0.2 - def setup(self): N = 10000 K = 10 diff --git a/asv_bench/benchmarks/replace.py b/asv_bench/benchmarks/replace.py index 3236b09acec37..d8efaf99e2c4d 100644 --- a/asv_bench/benchmarks/replace.py +++ b/asv_bench/benchmarks/replace.py @@ -4,7 +4,6 @@ class FillNa(object): - goal_time = 0.2 params = [True, False] param_names = ['inplace'] @@ -24,7 +23,6 @@ def time_replace(self, inplace): class ReplaceDict(object): - goal_time = 0.2 params = [True, False] param_names = ['inplace'] @@ -40,7 +38,6 @@ def time_replace_series(self, inplace): class Convert(object): - goal_time = 0.5 params = (['DataFrame', 'Series'], ['Timestamp', 'Timedelta']) param_names = ['constructor', 'replace_data'] diff --git a/asv_bench/benchmarks/reshape.py b/asv_bench/benchmarks/reshape.py index 3140f6fc81cbb..bda486dba3b0f 100644 --- a/asv_bench/benchmarks/reshape.py +++ b/asv_bench/benchmarks/reshape.py @@ -8,8 +8,6 @@ class Melt(object): - goal_time = 0.2 - def setup(self): self.df = DataFrame(np.random.randn(10000, 3), columns=['A', 'B', 'C']) self.df['id1'] = np.random.randint(0, 10, 10000) @@ -21,8 +19,6 @@ def time_melt_dataframe(self): class Pivot(object): - goal_time = 0.2 - def setup(self): N = 10000 index = date_range('1/1/2000', periods=N, freq='h') @@ -37,8 +33,6 @@ def time_reshape_pivot_time_series(self): class SimpleReshape(object): - goal_time = 0.2 - def setup(self): arrays = [np.arange(100).repeat(100), np.roll(np.tile(np.arange(100), 100), 25)] @@ -55,8 +49,6 @@ def time_unstack(self): class Unstack(object): - goal_time = 0.2 - def setup(self): m = 100 n = 1000 @@ -77,8 +69,6 @@ def time_without_last_row(self): class SparseIndex(object): - goal_time = 0.2 - def setup(self): NUM_ROWS = 1000 self.df = DataFrame({'A': np.random.randint(50, size=NUM_ROWS), @@ -95,8 +85,6 @@ def time_unstack(self): class WideToLong(object): - goal_time = 0.2 - def setup(self): nyrs = 20 nidvars = 20 @@ -115,8 +103,6 @@ def time_wide_to_long_big(self): class PivotTable(object): - goal_time = 0.2 - def setup(self): N = 100000 fac1 = np.array(['A', 'B', 'C'], dtype='O') @@ -135,8 +121,6 @@ def time_pivot_table(self): class GetDummies(object): - goal_time = 0.2 - def setup(self): categories = list(string.ascii_letters[:12]) s = pd.Series(np.random.choice(categories, size=1000000), diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index 2388acbc2d33f..46fb5011cc1a5 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -7,7 +7,6 @@ class SeriesConstructor(object): - goal_time = 0.2 params = [None, 'dict'] param_names = ['data'] @@ -24,7 +23,6 @@ def time_constructor(self, data): class IsIn(object): - goal_time = 0.2 params = ['int64', 'object'] param_names = ['dtype'] @@ -96,7 +94,6 @@ def time_isin_long_series_long_values_floats(self): class NSort(object): - goal_time = 0.2 params = ['first', 'last', 'all'] param_names = ['keep'] @@ -112,7 +109,6 @@ def time_nsmallest(self, keep): class Dropna(object): - goal_time = 0.2 params = ['int', 'datetime'] param_names = ['dtype'] @@ -130,7 +126,6 @@ def time_dropna(self, dtype): class Map(object): - goal_time = 0.2 params = ['dict', 'Series'] param_names = 'mapper' @@ -146,8 +141,6 @@ def time_map(self, mapper): class Clip(object): - goal_time = 0.2 - def setup(self): self.s = Series(np.random.randn(50)) @@ -157,7 +150,6 @@ def time_clip(self): class ValueCounts(object): - goal_time = 0.2 params = ['int', 'float', 'object'] param_names = ['dtype'] @@ -170,8 +162,6 @@ def time_value_counts(self, dtype): class Dir(object): - goal_time = 0.2 - def setup(self): self.s = Series(index=tm.makeStringIndex(10000)) @@ -181,8 +171,6 @@ def time_dir_strings(self): class SeriesGetattr(object): # https://github.com/pandas-dev/pandas/issues/19764 - goal_time = 0.2 - def setup(self): self.s = Series(1, index=date_range("2012-01-01", freq='s', diff --git a/asv_bench/benchmarks/sparse.py b/asv_bench/benchmarks/sparse.py index bbc076790a923..64f87c1670170 100644 --- a/asv_bench/benchmarks/sparse.py +++ b/asv_bench/benchmarks/sparse.py @@ -16,8 +16,6 @@ def make_array(size, dense_proportion, fill_value, dtype): class SparseSeriesToFrame(object): - goal_time = 0.2 - def setup(self): K = 50 N = 50001 @@ -35,7 +33,6 @@ def time_series_to_frame(self): class SparseArrayConstructor(object): - goal_time = 0.2 params = ([0.1, 0.01], [0, np.nan], [np.int64, np.float64, np.object]) param_names = ['dense_proportion', 'fill_value', 'dtype'] @@ -50,8 +47,6 @@ def time_sparse_array(self, dense_proportion, fill_value, dtype): class SparseDataFrameConstructor(object): - goal_time = 0.2 - def setup(self): N = 1000 self.arr = np.arange(N) @@ -70,8 +65,6 @@ def time_from_dict(self): class FromCoo(object): - goal_time = 0.2 - def setup(self): self.matrix = scipy.sparse.coo_matrix(([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), @@ -83,8 +76,6 @@ def time_sparse_series_from_coo(self): class ToCoo(object): - goal_time = 0.2 - def setup(self): s = Series([np.nan] * 10000) s[0] = 3.0 @@ -101,7 +92,6 @@ def time_sparse_series_to_coo(self): class Arithmetic(object): - goal_time = 0.2 params = ([0.1, 0.01], [0, np.nan]) param_names = ['dense_proportion', 'fill_value'] @@ -127,7 +117,6 @@ def time_divide(self, dense_proportion, fill_value): class ArithmeticBlock(object): - goal_time = 0.2 params = [np.nan, 0] param_names = ['fill_value'] diff --git a/asv_bench/benchmarks/stat_ops.py b/asv_bench/benchmarks/stat_ops.py index 3a6223d283073..5c777c00261e1 100644 --- a/asv_bench/benchmarks/stat_ops.py +++ b/asv_bench/benchmarks/stat_ops.py @@ -8,7 +8,6 @@ class FrameOps(object): - goal_time = 0.2 params = [ops, ['float', 'int'], [0, 1], [True, False]] param_names = ['op', 'dtype', 'axis', 'use_bottleneck'] @@ -27,7 +26,6 @@ def time_op(self, op, dtype, axis, use_bottleneck): class FrameMultiIndexOps(object): - goal_time = 0.2 params = ([0, 1, [0, 1]], ops) param_names = ['level', 'op'] @@ -46,7 +44,6 @@ def time_op(self, level, op): class SeriesOps(object): - goal_time = 0.2 params = [ops, ['float', 'int'], [True, False]] param_names = ['op', 'dtype', 'use_bottleneck'] @@ -65,7 +62,6 @@ def time_op(self, op, dtype, use_bottleneck): class SeriesMultiIndexOps(object): - goal_time = 0.2 params = ([0, 1, [0, 1]], ops) param_names = ['level', 'op'] @@ -84,7 +80,6 @@ def time_op(self, level, op): class Rank(object): - goal_time = 0.2 params = [['DataFrame', 'Series'], [True, False]] param_names = ['constructor', 'pct'] @@ -101,7 +96,6 @@ def time_average_old(self, constructor, pct): class Correlation(object): - goal_time = 0.2 params = ['spearman', 'kendall', 'pearson'] param_names = ['method'] diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py index ccfac2f73f14d..d880fb258560d 100644 --- a/asv_bench/benchmarks/strings.py +++ b/asv_bench/benchmarks/strings.py @@ -7,8 +7,6 @@ class Methods(object): - goal_time = 0.2 - def setup(self): self.s = Series(tm.makeStringIndex(10**5)) @@ -70,7 +68,6 @@ def time_lower(self): class Repeat(object): - goal_time = 0.2 params = ['int', 'array'] param_names = ['repeats'] @@ -86,7 +83,6 @@ def time_repeat(self, repeats): class Cat(object): - goal_time = 0.2 params = ([0, 3], [None, ','], [None, '-'], [0.0, 0.001, 0.15]) param_names = ['other_cols', 'sep', 'na_rep', 'na_frac'] @@ -112,7 +108,6 @@ def time_cat(self, other_cols, sep, na_rep, na_frac): class Contains(object): - goal_time = 0.2 params = [True, False] param_names = ['regex'] @@ -125,7 +120,6 @@ def time_contains(self, regex): class Split(object): - goal_time = 0.2 params = [True, False] param_names = ['expand'] @@ -138,8 +132,6 @@ def time_split(self, expand): class Dummies(object): - goal_time = 0.2 - def setup(self): self.s = Series(tm.makeStringIndex(10**5)).str.join('|') @@ -149,8 +141,6 @@ def time_get_dummies(self): class Encode(object): - goal_time = 0.2 - def setup(self): self.ser = Series(tm.makeUnicodeIndex()) @@ -160,8 +150,6 @@ def time_encode_decode(self): class Slice(object): - goal_time = 0.2 - def setup(self): self.s = Series(['abcdefg', np.nan] * 500000) diff --git a/asv_bench/benchmarks/timedelta.py b/asv_bench/benchmarks/timedelta.py index 3fe75b3c34299..01d53fb9cbbd9 100644 --- a/asv_bench/benchmarks/timedelta.py +++ b/asv_bench/benchmarks/timedelta.py @@ -6,8 +6,6 @@ class TimedeltaConstructor(object): - goal_time = 0.2 - def time_from_int(self): Timedelta(123456789) @@ -36,8 +34,6 @@ def time_from_missing(self): class ToTimedelta(object): - goal_time = 0.2 - def setup(self): self.ints = np.random.randint(0, 60, size=10000) self.str_days = [] @@ -58,7 +54,6 @@ def time_convert_string_seconds(self): class ToTimedeltaErrors(object): - goal_time = 0.2 params = ['coerce', 'ignore'] param_names = ['errors'] @@ -73,8 +68,6 @@ def time_convert(self, errors): class TimedeltaOps(object): - goal_time = 0.2 - def setup(self): self.td = to_timedelta(np.arange(1000000)) self.ts = Timestamp('2000') @@ -85,8 +78,6 @@ def time_add_td_ts(self): class TimedeltaProperties(object): - goal_time = 0.2 - def setup_cache(self): td = Timedelta(days=365, minutes=35, seconds=25, milliseconds=35) return td @@ -106,8 +97,6 @@ def time_timedelta_nanoseconds(self, td): class DatetimeAccessor(object): - goal_time = 0.2 - def setup_cache(self): N = 100000 series = Series(timedelta_range('1 days', periods=N, freq='h')) diff --git a/asv_bench/benchmarks/timeseries.py b/asv_bench/benchmarks/timeseries.py index 11a789453c2df..84bdcc5fa30f2 100644 --- a/asv_bench/benchmarks/timeseries.py +++ b/asv_bench/benchmarks/timeseries.py @@ -11,7 +11,6 @@ class DatetimeIndex(object): - goal_time = 0.2 params = ['dst', 'repeated', 'tz_aware', 'tz_naive'] param_names = ['index_type'] @@ -58,8 +57,6 @@ def time_to_pydatetime(self, index_type): class TzLocalize(object): - goal_time = 0.2 - def setup(self): dst_rng = date_range(start='10/29/2000 1:00:00', end='10/29/2000 1:59:59', freq='S') @@ -77,7 +74,6 @@ def time_infer_dst(self): class ResetIndex(object): - goal_time = 0.2 params = [None, 'US/Eastern'] param_names = 'tz' @@ -91,7 +87,6 @@ def time_reest_datetimeindex(self, tz): class Factorize(object): - goal_time = 0.2 params = [None, 'Asia/Tokyo'] param_names = 'tz' @@ -106,7 +101,6 @@ def time_factorize(self, tz): class InferFreq(object): - goal_time = 0.2 params = [None, 'D', 'B'] param_names = ['freq'] @@ -123,8 +117,6 @@ def time_infer_freq(self, freq): class TimeDatetimeConverter(object): - goal_time = 0.2 - def setup(self): N = 100000 self.rng = date_range(start='1/1/2000', periods=N, freq='T') @@ -135,7 +127,6 @@ def time_convert(self): class Iteration(object): - goal_time = 0.2 params = [date_range, period_range] param_names = ['time_index'] @@ -156,7 +147,6 @@ def time_iter_preexit(self, time_index): class ResampleDataFrame(object): - goal_time = 0.2 params = ['max', 'mean', 'min'] param_names = ['method'] @@ -171,7 +161,6 @@ def time_method(self, method): class ResampleSeries(object): - goal_time = 0.2 params = (['period', 'datetime'], ['5min', '1D'], ['mean', 'ohlc']) param_names = ['index', 'freq', 'method'] @@ -192,8 +181,6 @@ def time_resample(self, index, freq, method): class ResampleDatetetime64(object): # GH 7754 - goal_time = 0.2 - def setup(self): rng3 = date_range(start='2000-01-01 00:00:00', end='2000-01-01 10:00:00', freq='555000U') @@ -205,7 +192,6 @@ def time_resample(self): class AsOf(object): - goal_time = 0.2 params = ['DataFrame', 'Series'] param_names = ['constructor'] @@ -253,7 +239,6 @@ def time_asof_nan_single(self, constructor): class SortIndex(object): - goal_time = 0.2 params = [True, False] param_names = ['monotonic'] @@ -273,8 +258,6 @@ def time_get_slice(self, monotonic): class IrregularOps(object): - goal_time = 0.2 - def setup(self): N = 10**5 idx = date_range(start='1/1/2000', periods=N, freq='s') @@ -288,8 +271,6 @@ def time_add(self): class Lookup(object): - goal_time = 0.2 - def setup(self): N = 1500000 rng = date_range(start='1/1/2000', periods=N, freq='S') @@ -303,8 +284,6 @@ def time_lookup_and_cleanup(self): class ToDatetimeYYYYMMDD(object): - goal_time = 0.2 - def setup(self): rng = date_range(start='1/1/2000', periods=10000, freq='D') self.stringsD = Series(rng.strftime('%Y%m%d')) @@ -315,8 +294,6 @@ def time_format_YYYYMMDD(self): class ToDatetimeISO8601(object): - goal_time = 0.2 - def setup(self): rng = date_range(start='1/1/2000', periods=20000, freq='H') self.strings = rng.strftime('%Y-%m-%d %H:%M:%S').tolist() @@ -342,8 +319,6 @@ def time_iso8601_tz_spaceformat(self): class ToDatetimeNONISO8601(object): - goal_time = 0.2 - def setup(self): N = 10000 half = int(N / 2) @@ -361,8 +336,6 @@ def time_different_offset(self): class ToDatetimeFormat(object): - goal_time = 0.2 - def setup(self): self.s = Series(['19MAY11', '19MAY11:00:00:00'] * 100000) self.s2 = self.s.str.replace(':\\S+$', '') @@ -376,7 +349,6 @@ def time_no_exact(self): class ToDatetimeCache(object): - goal_time = 0.2 params = [True, False] param_names = ['cache'] diff --git a/asv_bench/benchmarks/timestamp.py b/asv_bench/benchmarks/timestamp.py index c142a9b59fc43..8eaf815eaa962 100644 --- a/asv_bench/benchmarks/timestamp.py +++ b/asv_bench/benchmarks/timestamp.py @@ -29,8 +29,6 @@ def time_fromtimestamp(self): class TimestampProperties(object): - goal_time = 0.2 - _tzs = [None, pytz.timezone('Europe/Amsterdam')] _freqs = [None, 'B'] params = [_tzs, _freqs] @@ -89,8 +87,6 @@ def time_microsecond(self, tz, freq): class TimestampOps(object): - goal_time = 0.2 - params = [None, 'US/Eastern'] param_names = ['tz'] @@ -108,8 +104,6 @@ def time_to_pydatetime(self, tz): class TimestampAcrossDst(object): - goal_time = 0.2 - def setup(self): dt = datetime.datetime(2016, 3, 27, 1) self.tzinfo = pytz.timezone('CET').localize(dt, is_dst=False).tzinfo diff --git a/setup.cfg b/setup.cfg index 84f19e56ad3bc..ee39844996025 100644 --- a/setup.cfg +++ b/setup.cfg @@ -23,7 +23,6 @@ ignore = C408, # Unnecessary dict call - rewrite as a literal. C409 # Unnecessary list passed to tuple() - rewrite as a tuple literal. exclude = - asv_bench/*.py, # TODO we should fix linting in those files instead of excluding doc/sphinxext/*.py, doc/build/*.py, doc/temp/*.py,
- [X] closes #23075 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry The following changes were made: - All occurances of `goal_time` have been removed. Running `grep -rnw asv_bench/benchmarks/ -e goal_time --include "*.py"` should no longer return anything. - The benchmark folder is no longer excluded in `setup.cfg` - Removed one unused import in `asv_bench/benchmarks/io/excel.py` to pass flake8.
https://api.github.com/repos/pandas-dev/pandas/pulls/23265
2018-10-21T20:05:04Z
2018-10-23T03:07:42Z
2018-10-23T03:07:42Z
2018-10-23T03:07:48Z
DEPR: Add Deprecated warning for timedelta with passed units M and Y
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index cbefae07b07f1..c9efe43c35adf 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -42,10 +42,7 @@ Other API Changes Deprecations ~~~~~~~~~~~~ -- -- -- - +- Deprecated the `M (months)` and `Y (year)` `units` parameter of :func: `pandas.to_timedelta`, :func: `pandas.Timedelta` and :func: `pandas.TimedeltaIndex` (:issue:`16344`) .. _whatsnew_0250.prior_deprecations: diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 0a19d8749fc7c..f08a57375a301 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -1158,6 +1158,11 @@ class Timedelta(_Timedelta): "[weeks, days, hours, minutes, seconds, " "milliseconds, microseconds, nanoseconds]") + if unit in {'Y', 'y', 'M'}: + warnings.warn("M and Y units are deprecated and " + "will be removed in a future version.", + FutureWarning, stacklevel=1) + if isinstance(value, Timedelta): value = value.value elif is_string_object(value): diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index cbe5ae198838f..830925535dab1 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -207,6 +207,11 @@ def __new__(cls, data=None, unit=None, freq=None, start=None, end=None, 'collection of some kind, {data} was passed' .format(cls=cls.__name__, data=repr(data))) + if unit in {'Y', 'y', 'M'}: + warnings.warn("M and Y units are deprecated and " + "will be removed in a future version.", + FutureWarning, stacklevel=2) + if isinstance(data, TimedeltaArray): if copy: data = data.copy() diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index ddd21d0f62d08..30cb15f311b9f 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -2,6 +2,8 @@ timedelta support tools """ +import warnings + import numpy as np from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit @@ -90,6 +92,11 @@ def to_timedelta(arg, unit='ns', box=True, errors='raise'): raise ValueError("errors must be one of 'ignore', " "'raise', or 'coerce'}") + if unit in {'Y', 'y', 'M'}: + warnings.warn("M and Y units are deprecated and " + "will be removed in a future version.", + FutureWarning, stacklevel=2) + if arg is None: return arg elif isinstance(arg, ABCSeries): diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 79210705103ab..3cbd9942f9d84 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -1,4 +1,5 @@ from datetime import timedelta +import re import numpy as np import pytest @@ -325,6 +326,13 @@ def test_freq_conversion(self): result = td.astype('timedelta64[s]') assert_index_equal(result, expected) + @pytest.mark.parametrize('unit', ['Y', 'y', 'M']) + def test_unit_m_y_deprecated(self, unit): + with tm.assert_produces_warning(FutureWarning) as w: + TimedeltaIndex([1, 3, 7], unit) + msg = r'.* units are deprecated .*' + assert re.match(msg, str(w[0].message)) + class TestTimeSeries(object): diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index e1838e0160fec..7d5b479810205 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -1,5 +1,6 @@ """ test the scalar Timedelta """ from datetime import timedelta +import re import numpy as np import pytest @@ -317,6 +318,7 @@ def test_nat_converters(self): assert result.dtype.kind == 'm' assert result.astype('int64') == iNaT + @pytest.mark.filterwarnings("ignore:M and Y units are deprecated") @pytest.mark.parametrize('units, np_unit', [(['Y', 'y'], 'Y'), (['M'], 'M'), @@ -376,6 +378,24 @@ def test_unit_parser(self, units, np_unit, wrapper): result = Timedelta('2{}'.format(unit)) assert result == expected + @pytest.mark.skipif(compat.PY2, reason="requires python3.5 or higher") + @pytest.mark.parametrize('unit', ['Y', 'y', 'M']) + def test_unit_m_y_deprecated(self, unit): + with tm.assert_produces_warning(FutureWarning) as w1: + Timedelta(10, unit) + msg = r'.* units are deprecated .*' + assert re.match(msg, str(w1[0].message)) + with tm.assert_produces_warning(FutureWarning, + check_stacklevel=False) as w2: + to_timedelta(10, unit) + msg = r'.* units are deprecated .*' + assert re.match(msg, str(w2[0].message)) + with tm.assert_produces_warning(FutureWarning, + check_stacklevel=False) as w3: + to_timedelta([1, 2], unit) + msg = r'.* units are deprecated .*' + assert re.match(msg, str(w3[0].message)) + def test_numeric_conversions(self): assert Timedelta(0) == np.timedelta64(0, 'ns') assert Timedelta(10) == np.timedelta64(10, 'ns')
- [x] closes #16344 - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] tests passed locally - `pytest pandas/tests/scalar/timedelta/test_timedelta.py -k test_unit_m_y_deprecated` and `pytest pandas/tests/indexes/timedeltas/test_timedelta.py -k test_unit_m_y_deprecated` - [x] checked import format to pass linter - `isort`
https://api.github.com/repos/pandas-dev/pandas/pulls/23264
2018-10-21T17:36:32Z
2019-02-08T23:37:38Z
2019-02-08T23:37:38Z
2019-02-08T23:42:59Z
BUG: merging an Integer EA rasises
diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index 0bd695f5a40ea..7a6d7fed6fae8 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -1051,6 +1051,7 @@ update the ``ExtensionDtype._metadata`` tuple to match the signature of your - :meth:`DataFrame.stack` no longer converts to object dtype for DataFrames where each column has the same extension dtype. The output Series will have the same dtype as the columns (:issue:`23077`). - :meth:`Series.unstack` and :meth:`DataFrame.unstack` no longer convert extension arrays to object-dtype ndarrays. Each column in the output ``DataFrame`` will now have the same dtype as the input (:issue:`23077`). - Bug when grouping :meth:`Dataframe.groupby()` and aggregating on ``ExtensionArray`` it was not returning the actual ``ExtensionArray`` dtype (:issue:`23227`). +- Bug in :func:`pandas.merge` when merging on an extension array-backed column (:issue:`23020`). - A default repr for :class:`pandas.api.extensions.ExtensionArray` is now provided (:issue:`23601`). .. _whatsnew_0240.api.incompatibilities: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index e6e6c1c99b509..0adeb7997a888 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -17,9 +17,10 @@ from pandas.core.dtypes.common import ( ensure_float64, ensure_int64, ensure_object, is_array_like, is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64_dtype, - is_datetime64tz_dtype, is_datetimelike, is_dtype_equal, is_float_dtype, - is_int64_dtype, is_integer, is_integer_dtype, is_list_like, is_number, - is_numeric_dtype, needs_i8_conversion) + is_datetime64tz_dtype, is_datetimelike, is_dtype_equal, + is_extension_array_dtype, is_float_dtype, is_int64_dtype, is_integer, + is_integer_dtype, is_list_like, is_number, is_numeric_dtype, + needs_i8_conversion) from pandas.core.dtypes.missing import isnull, na_value_for_dtype from pandas import Categorical, DataFrame, Index, MultiIndex, Series, Timedelta @@ -1589,17 +1590,16 @@ def _right_outer_join(x, y, max_groups): def _factorize_keys(lk, rk, sort=True): + # Some pre-processing for non-ndarray lk / rk if is_datetime64tz_dtype(lk) and is_datetime64tz_dtype(rk): lk = lk.values rk = rk.values - # if we exactly match in categories, allow us to factorize on codes - if (is_categorical_dtype(lk) and + elif (is_categorical_dtype(lk) and is_categorical_dtype(rk) and lk.is_dtype_equal(rk)): - klass = libhashtable.Int64Factorizer - if lk.categories.equals(rk.categories): + # if we exactly match in categories, allow us to factorize on codes rk = rk.codes else: # Same categories in different orders -> recode @@ -1607,7 +1607,14 @@ def _factorize_keys(lk, rk, sort=True): lk = ensure_int64(lk.codes) rk = ensure_int64(rk) - elif is_integer_dtype(lk) and is_integer_dtype(rk): + + elif (is_extension_array_dtype(lk.dtype) and + is_extension_array_dtype(rk.dtype) and + lk.dtype == rk.dtype): + lk, _ = lk._values_for_factorize() + rk, _ = rk._values_for_factorize() + + if is_integer_dtype(lk) and is_integer_dtype(rk): # GH#23917 TODO: needs tests for case where lk is integer-dtype # and rk is datetime-dtype klass = libhashtable.Int64Factorizer diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py index 42e481d974295..ee22ffb3ccf97 100644 --- a/pandas/tests/extension/base/reshaping.py +++ b/pandas/tests/extension/base/reshaping.py @@ -173,6 +173,38 @@ def test_merge(self, data, na_value): dtype=data.dtype)}) self.assert_frame_equal(res, exp[['ext', 'int1', 'key', 'int2']]) + def test_merge_on_extension_array(self, data): + # GH 23020 + a, b = data[:2] + key = type(data)._from_sequence([a, b], dtype=data.dtype) + + df = pd.DataFrame({"key": key, "val": [1, 2]}) + result = pd.merge(df, df, on='key') + expected = pd.DataFrame({"key": key, + "val_x": [1, 2], + "val_y": [1, 2]}) + self.assert_frame_equal(result, expected) + + # order + result = pd.merge(df.iloc[[1, 0]], df, on='key') + expected = expected.iloc[[1, 0]].reset_index(drop=True) + self.assert_frame_equal(result, expected) + + def test_merge_on_extension_array_duplicates(self, data): + # GH 23020 + a, b = data[:2] + key = type(data)._from_sequence([a, b, a], dtype=data.dtype) + df1 = pd.DataFrame({"key": key, "val": [1, 2, 3]}) + df2 = pd.DataFrame({"key": key, "val": [1, 2, 3]}) + + result = pd.merge(df1, df2, on='key') + expected = pd.DataFrame({ + "key": key.take([0, 0, 0, 0, 1]), + "val_x": [1, 1, 3, 3, 2], + "val_y": [1, 3, 1, 3, 2], + }) + self.assert_frame_equal(result, expected) + @pytest.mark.parametrize("columns", [ ["A", "B"], pd.MultiIndex.from_tuples([('A', 'a'), ('A', 'b')], diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 94e180f9328d6..970802e94662a 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -1326,6 +1326,16 @@ def test_merging_with_bool_or_int_cateorical_column(self, category_column, CDT(categories, ordered=ordered)) assert_frame_equal(expected, result) + def test_merge_on_int_array(self): + # GH 23020 + df = pd.DataFrame({'A': pd.Series([1, 2, np.nan], dtype='Int64'), + 'B': 1}) + result = pd.merge(df, df, on='A') + expected = pd.DataFrame({'A': pd.Series([1, 2, np.nan], dtype='Int64'), + 'B_x': 1, + 'B_y': 1}) + assert_frame_equal(result, expected) + @pytest.fixture def left_df():
- [ ] closes #23020 - [ ] 1 test added - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/23262
2018-10-21T14:27:16Z
2018-12-19T14:28:58Z
2018-12-19T14:28:57Z
2018-12-19T14:29:13Z
Add tests in methods.py
diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index f7649415f2471..60de5d4db03d9 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -105,6 +105,30 @@ def test_factorize_equivalence(self, data_for_grouping, na_sentinel): tm.assert_numpy_array_equal(l1, l2) self.assert_extension_array_equal(u1, u2) + def test_fillna_copy_frame(self, data_missing): + arr = data_missing.take([1, 1]) + df = pd.DataFrame({"A": arr}) + + filled_val = df.iloc[0, 0] + result = df.fillna(filled_val) + + assert df.A.values is not result.A.values + + def test_fillna_copy_series(self, data_missing): + arr = data_missing.take([1, 1]) + ser = pd.Series(arr) + + filled_val = ser[0] + result = ser.fillna(filled_val) + + assert ser._values is not result._values + assert ser._values is arr + + def test_fillna_length_mismatch(self, data_missing): + with (tm.assert_raises_regex(ValueError, + "Length of 'value' does not match.")): + data_missing.fillna(data_missing.take([1])) + def test_combine_le(self, data_repeated): # GH 20825 # Test that combine works when doing a <= (le) comparison diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index 65e6a15dd8df0..b1d08a5620bf3 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -191,6 +191,10 @@ def test_combine_add(self, data_repeated): expected = pd.Series([a + val for a in list(orig_data1)]) self.assert_series_equal(result, expected) + @pytest.mark.skip(reason="Not Applicable") + def test_fillna_length_mismatch(self, data_missing): + pass + class TestCasting(base.BaseCastingTests): pass diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py index 3154f34434ce2..2c7bc79c324b4 100644 --- a/pandas/tests/extension/test_interval.py +++ b/pandas/tests/extension/test_interval.py @@ -109,6 +109,10 @@ class TestMethods(BaseInterval, base.BaseMethodsTests): def test_combine_add(self, data_repeated): pass + @pytest.mark.skip(reason="Not Applicable") + def test_fillna_length_mismatch(self, data_missing): + pass + class TestMissing(BaseInterval, base.BaseMissingTests): # Index.fillna only accepts scalar `value`, so we have to skip all diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 8c038b3950a26..4f67a13215cfd 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -231,6 +231,30 @@ def test_combine_le(self, data_repeated): ], fill_value=False)) self.assert_series_equal(result, expected) + def test_fillna_copy_frame(self, data_missing): + arr = data_missing.take([1, 1]) + df = pd.DataFrame({"A": arr}) + + filled_val = df.iloc[0, 0] + result = df.fillna(filled_val) + + assert df.values.base is not result.values.base + assert df.A._values.to_dense() is arr.to_dense() + + def test_fillna_copy_series(self, data_missing): + arr = data_missing.take([1, 1]) + ser = pd.Series(arr) + + filled_val = ser[0] + result = ser.fillna(filled_val) + + assert ser._values is not result._values + assert ser._values.to_dense() is arr.to_dense() + + @pytest.mark.skip(reason="Not Applicable") + def test_fillna_length_mismatch(self, data_missing): + pass + class TestCasting(BaseSparseTests, base.BaseCastingTests): pass
Closes #23241
https://api.github.com/repos/pandas-dev/pandas/pulls/23261
2018-10-21T00:04:49Z
2018-10-30T11:42:06Z
2018-10-30T11:42:05Z
2019-01-02T20:26:25Z
CLN: remove unused `mgr` kwarg
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 8a4754542b5b6..f89d4c51c9a6f 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -299,7 +299,7 @@ def _slice(self, slicer): """ return a slice of my values """ return self.values[slicer] - def reshape_nd(self, labels, shape, ref_items, mgr=None): + def reshape_nd(self, labels, shape, ref_items): """ Parameters ---------- @@ -381,7 +381,7 @@ def delete(self, loc): self.values = np.delete(self.values, loc, 0) self.mgr_locs = self.mgr_locs.delete(loc) - def apply(self, func, mgr=None, **kwargs): + def apply(self, func, **kwargs): """ apply the function to my values; return a block if we are not one """ @@ -393,8 +393,7 @@ def apply(self, func, mgr=None, **kwargs): return result - def fillna(self, value, limit=None, inplace=False, downcast=None, - mgr=None): + def fillna(self, value, limit=None, inplace=False, downcast=None): """ fillna on the block with the value. If we fail, then convert to ObjectBlock and try again """ @@ -520,7 +519,7 @@ def _maybe_downcast(self, blocks, downcast=None): blocks = [blocks] return _extend_blocks([b.downcast(downcast) for b in blocks]) - def downcast(self, dtypes=None, mgr=None): + def downcast(self, dtypes=None): """ try to downcast each item to the dict of dtypes if present """ # turn it off completely @@ -567,7 +566,7 @@ def astype(self, dtype, copy=False, errors='raise', values=None, **kwargs): **kwargs) def _astype(self, dtype, copy=False, errors='raise', values=None, - klass=None, mgr=None, **kwargs): + klass=None, **kwargs): """Coerce to the new type Parameters @@ -776,7 +775,7 @@ def to_native_types(self, slicer=None, na_rep='nan', quoting=None, return values # block actions #### - def copy(self, deep=True, mgr=None): + def copy(self, deep=True): """ copy constructor """ values = self.values if deep: @@ -784,7 +783,7 @@ def copy(self, deep=True, mgr=None): return self.make_block_same_class(values) def replace(self, to_replace, value, inplace=False, filter=None, - regex=False, convert=True, mgr=None): + regex=False, convert=True): """replace the to_replace value with value, possible to create new blocks here this is just a call to putmask. regex is not used here. It is used in ObjectBlocks. It is here for API compatibility. @@ -827,7 +826,7 @@ def _replace_single(self, *args, **kwargs): """ no-op on a non-ObjectBlock """ return self if kwargs['inplace'] else self.copy() - def setitem(self, indexer, value, mgr=None): + def setitem(self, indexer, value): """Set the value inplace, returning a a maybe different typed block. Parameters @@ -836,7 +835,6 @@ def setitem(self, indexer, value, mgr=None): The subset of self.values to set value : object The value being set - mgr : BlockPlacement, optional Returns ------- @@ -886,7 +884,7 @@ def setitem(self, indexer, value, mgr=None): dtype = find_common_type([values.dtype, dtype]) if not is_dtype_equal(self.dtype, dtype): b = self.astype(dtype) - return b.setitem(indexer, value, mgr=mgr) + return b.setitem(indexer, value) # value must be storeable at this moment arr_value = np.array(value) @@ -956,7 +954,7 @@ def _is_empty_indexer(indexer): return block def putmask(self, mask, new, align=True, inplace=False, axis=0, - transpose=False, mgr=None): + transpose=False): """ putmask the data to the block; it is possible that we may create a new dtype of block @@ -1131,7 +1129,7 @@ def coerce_to_target_dtype(self, other): def interpolate(self, method='pad', axis=0, index=None, values=None, inplace=False, limit=None, limit_direction='forward', limit_area=None, fill_value=None, coerce=False, - downcast=None, mgr=None, **kwargs): + downcast=None, **kwargs): inplace = validate_bool_kwarg(inplace, 'inplace') @@ -1158,7 +1156,7 @@ def check_int_bool(self, inplace): inplace=inplace, limit=limit, fill_value=fill_value, coerce=coerce, - downcast=downcast, mgr=mgr) + downcast=downcast) # try an interp method try: m = missing.clean_interp_method(method, **kwargs) @@ -1174,13 +1172,13 @@ def check_int_bool(self, inplace): limit_direction=limit_direction, limit_area=limit_area, fill_value=fill_value, inplace=inplace, - downcast=downcast, mgr=mgr, **kwargs) + downcast=downcast, **kwargs) raise ValueError("invalid method '{0}' to interpolate.".format(method)) def _interpolate_with_fill(self, method='pad', axis=0, inplace=False, limit=None, fill_value=None, coerce=False, - downcast=None, mgr=None): + downcast=None): """ fillna but using the interpolate machinery """ inplace = validate_bool_kwarg(inplace, 'inplace') @@ -1207,7 +1205,7 @@ def _interpolate_with_fill(self, method='pad', axis=0, inplace=False, def _interpolate(self, method=None, index=None, values=None, fill_value=None, axis=0, limit=None, limit_direction='forward', limit_area=None, - inplace=False, downcast=None, mgr=None, **kwargs): + inplace=False, downcast=None, **kwargs): """ interpolate using scipy wrappers """ inplace = validate_bool_kwarg(inplace, 'inplace') @@ -1283,12 +1281,12 @@ def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None): else: return self.make_block_same_class(new_values, new_mgr_locs) - def diff(self, n, axis=1, mgr=None): + def diff(self, n, axis=1): """ return block for the diff of the values """ new_values = algos.diff(self.values, n, axis=axis) return [self.make_block(values=new_values)] - def shift(self, periods, axis=0, mgr=None): + def shift(self, periods, axis=0): """ shift the block by periods, possibly upcast """ # convert integer to float if necessary. need to do a lot more than @@ -1319,7 +1317,7 @@ def shift(self, periods, axis=0, mgr=None): return [self.make_block(new_values)] def where(self, other, cond, align=True, errors='raise', - try_cast=False, axis=0, transpose=False, mgr=None): + try_cast=False, axis=0, transpose=False): """ evaluate the block; return result block(s) from the result @@ -1461,7 +1459,7 @@ def _unstack(self, unstacker_func, new_columns): blocks = [make_block(new_values, placement=new_placement)] return blocks, mask - def quantile(self, qs, interpolation='linear', axis=0, mgr=None): + def quantile(self, qs, interpolation='linear', axis=0, axes=None): """ compute the quantiles of the @@ -1470,6 +1468,7 @@ def quantile(self, qs, interpolation='linear', axis=0, mgr=None): qs: a scalar or list of the quantiles to be computed interpolation: type of interpolation, default 'linear' axis: axis to compute, default 0 + axes : BlockManager.axes Returns ------- @@ -1552,7 +1551,7 @@ def _nanpercentile(values, q, axis, **kw): if self.ndim == 1: ax = Float64Index([qs]) else: - ax = mgr.axes[0] + ax = axes[0] if is_empty: if self.ndim == 1: @@ -1571,7 +1570,7 @@ def _nanpercentile(values, q, axis, **kw): ndim=ndim) def _replace_coerce(self, to_replace, value, inplace=True, regex=False, - convert=False, mgr=None, mask=None): + convert=False, mask=None): """ Replace value corresponding to the given boolean array with another value. @@ -1588,7 +1587,6 @@ def _replace_coerce(self, to_replace, value, inplace=True, regex=False, If true, perform regular expression substitution. convert : bool, default True If true, try to coerce any object types to better types. - mgr : BlockManager, optional mask : array-like of bool, optional True indicate corresponding element is ignored. @@ -1605,8 +1603,7 @@ def _replace_coerce(self, to_replace, value, inplace=True, regex=False, return self._replace_single(to_replace, value, inplace=inplace, regex=regex, convert=convert, - mask=mask, - mgr=mgr) + mask=mask) return self @@ -1694,7 +1691,7 @@ def set(self, locs, values, check=False): self.values = values def putmask(self, mask, new, align=True, inplace=False, axis=0, - transpose=False, mgr=None): + transpose=False): """ putmask the data to the block; we must be a single block and not generate other blocks @@ -1826,7 +1823,7 @@ def is_view(self): def is_numeric(self): return self.values.dtype._is_numeric - def setitem(self, indexer, value, mgr=None): + def setitem(self, indexer, value): """Set the value inplace, returning a same-typed block. This differs from Block.setitem by not allowing setitem to change @@ -1838,7 +1835,6 @@ def setitem(self, indexer, value, mgr=None): The subset of self.values to set value : object The value being set - mgr : BlockPlacement, optional Returns ------- @@ -1923,8 +1919,7 @@ def concat_same_type(self, to_concat, placement=None): return self.make_block_same_class(values, ndim=self.ndim, placement=placement) - def fillna(self, value, limit=None, inplace=False, downcast=None, - mgr=None): + def fillna(self, value, limit=None, inplace=False, downcast=None): values = self.values if inplace else self.values.copy() values = values.fillna(value=value, limit=limit) return [self.make_block_same_class(values=values, @@ -1940,7 +1935,7 @@ def interpolate(self, method='pad', axis=0, inplace=False, limit=None, limit=limit), placement=self.mgr_locs) - def shift(self, periods, axis=0, mgr=None): + def shift(self, periods, axis=0): """ Shift the block by `periods`. @@ -2220,15 +2215,14 @@ def should_store(self, value): is_extension_array_dtype(value)) def replace(self, to_replace, value, inplace=False, filter=None, - regex=False, convert=True, mgr=None): + regex=False, convert=True): inplace = validate_bool_kwarg(inplace, 'inplace') to_replace_values = np.atleast_1d(to_replace) if not np.can_cast(to_replace_values, bool): return self return super(BoolBlock, self).replace(to_replace, value, inplace=inplace, filter=filter, - regex=regex, convert=convert, - mgr=mgr) + regex=regex, convert=convert) class ObjectBlock(Block): @@ -2361,7 +2355,7 @@ def should_store(self, value): is_extension_array_dtype(value)) def replace(self, to_replace, value, inplace=False, filter=None, - regex=False, convert=True, mgr=None): + regex=False, convert=True): to_rep_is_list = is_list_like(to_replace) value_is_list = is_list_like(value) both_lists = to_rep_is_list and value_is_list @@ -2373,19 +2367,19 @@ def replace(self, to_replace, value, inplace=False, filter=None, if not either_list and is_re(to_replace): return self._replace_single(to_replace, value, inplace=inplace, filter=filter, regex=True, - convert=convert, mgr=mgr) + convert=convert) elif not (either_list or regex): return super(ObjectBlock, self).replace(to_replace, value, inplace=inplace, filter=filter, regex=regex, - convert=convert, mgr=mgr) + convert=convert) elif both_lists: for to_rep, v in zip(to_replace, value): result_blocks = [] for b in blocks: result = b._replace_single(to_rep, v, inplace=inplace, filter=filter, regex=regex, - convert=convert, mgr=mgr) + convert=convert) result_blocks = _extend_blocks(result, result_blocks) blocks = result_blocks return result_blocks @@ -2396,17 +2390,17 @@ def replace(self, to_replace, value, inplace=False, filter=None, for b in blocks: result = b._replace_single(to_rep, value, inplace=inplace, filter=filter, regex=regex, - convert=convert, mgr=mgr) + convert=convert) result_blocks = _extend_blocks(result, result_blocks) blocks = result_blocks return result_blocks return self._replace_single(to_replace, value, inplace=inplace, filter=filter, convert=convert, - regex=regex, mgr=mgr) + regex=regex) def _replace_single(self, to_replace, value, inplace=False, filter=None, - regex=False, convert=True, mgr=None, mask=None): + regex=False, convert=True, mask=None): """ Replace elements by the given value. @@ -2423,7 +2417,6 @@ def _replace_single(self, to_replace, value, inplace=False, filter=None, If true, perform regular expression substitution. convert : bool, default True If true, try to coerce any object types to better types. - mgr : BlockManager, optional mask : array-like of bool, optional True indicate corresponding element is ignored. @@ -2466,8 +2459,7 @@ def _replace_single(self, to_replace, value, inplace=False, filter=None, # the superclass method -> to_replace is some kind of object return super(ObjectBlock, self).replace(to_replace, value, inplace=inplace, - filter=filter, regex=regex, - mgr=mgr) + filter=filter, regex=regex) new_values = self.values if inplace else self.values.copy() @@ -2508,7 +2500,7 @@ def re_replacer(s): return block def _replace_coerce(self, to_replace, value, inplace=True, regex=False, - convert=False, mgr=None, mask=None): + convert=False, mask=None): """ Replace value corresponding to the given boolean array with another value. @@ -2525,7 +2517,6 @@ def _replace_coerce(self, to_replace, value, inplace=True, regex=False, If true, perform regular expression substitution. convert : bool, default True If true, try to coerce any object types to better types. - mgr : BlockManager, optional mask : array-like of bool, optional True indicate corresponding element is ignored. @@ -2536,7 +2527,7 @@ def _replace_coerce(self, to_replace, value, inplace=True, regex=False, if mask.any(): block = super(ObjectBlock, self)._replace_coerce( to_replace=to_replace, value=value, inplace=inplace, - regex=regex, convert=convert, mgr=mgr, mask=mask) + regex=regex, convert=convert, mask=mask) if convert: block = [b.convert(by_item=True, numeric=False, copy=True) for b in block] @@ -2651,7 +2642,7 @@ def _maybe_coerce_values(self, values): values = conversion.ensure_datetime64ns(values) return values - def _astype(self, dtype, mgr=None, **kwargs): + def _astype(self, dtype, **kwargs): """ these automatically copy, so copy=True has no effect raise on an except if raise == True @@ -2824,7 +2815,7 @@ def is_view(self): # check the ndarray values of the DatetimeIndex values return self.values.values.base is not None - def copy(self, deep=True, mgr=None): + def copy(self, deep=True): """ copy constructor """ values = self.values if deep: @@ -2917,7 +2908,7 @@ def _try_coerce_result(self, result): def _box_func(self): return lambda x: tslibs.Timestamp(x, tz=self.dtype.tz) - def shift(self, periods, axis=0, mgr=None): + def shift(self, periods, axis=0): """ shift the block by periods """ # think about moving this to the DatetimeIndex. This is a non-freq @@ -2941,14 +2932,13 @@ def shift(self, periods, axis=0, mgr=None): return [self.make_block_same_class(new_values, placement=self.mgr_locs)] - def diff(self, n, axis=0, mgr=None): + def diff(self, n, axis=0): """1st discrete difference Parameters ---------- n : int, number of periods to diff axis : int, axis to diff upon. default 0 - mgr : default None Return ------ diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index f15f9ce3e8cb6..fc3a12a9da82a 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -402,7 +402,6 @@ def apply(self, f, axes=None, filter=None, do_integrity_check=False, kwargs[k] = obj.reindex(b_items, axis=axis, copy=align_copy) - kwargs['mgr'] = self applied = getattr(b, f)(**kwargs) result_blocks = _extend_blocks(applied, result_blocks) @@ -440,8 +439,7 @@ def reduction(self, f, axis=0, consolidate=True, transposed=False, axes, blocks = [], [] for b in self.blocks: - kwargs['mgr'] = self - axe, block = getattr(b, f)(axis=axis, **kwargs) + axe, block = getattr(b, f)(axis=axis, axes=self.axes, **kwargs) axes.append(axe) blocks.append(block) @@ -541,15 +539,11 @@ def convert(self, **kwargs): def replace(self, **kwargs): return self.apply('replace', **kwargs) - def replace_list(self, src_list, dest_list, inplace=False, regex=False, - mgr=None): + def replace_list(self, src_list, dest_list, inplace=False, regex=False): """ do a list replace """ inplace = validate_bool_kwarg(inplace, 'inplace') - if mgr is None: - mgr = self - # figure out our mask a-priori to avoid repeated replacements values = self.as_array() @@ -581,8 +575,7 @@ def comp(s, regex=False): convert = i == src_len result = b._replace_coerce(mask=m, to_replace=s, value=d, inplace=inplace, - convert=convert, regex=regex, - mgr=mgr) + convert=convert, regex=regex) if m.any(): new_rb = _extend_blocks(result, new_rb) else: @@ -717,7 +710,7 @@ def __contains__(self, item): def nblocks(self): return len(self.blocks) - def copy(self, deep=True, mgr=None): + def copy(self, deep=True): """ Make deep or shallow copy of BlockManager
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/23260
2018-10-20T21:48:37Z
2018-10-23T11:52:58Z
2018-10-23T11:52:58Z
2020-04-05T17:39:26Z
DOC: Fixed timedelta docstring and examples
diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index db93820c6942f..b6ceabb759954 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -16,31 +16,43 @@ def to_timedelta(arg, unit='ns', box=True, errors='raise'): """ - Convert argument to timedelta + Convert argument to timedelta. + + Timedeltas are absolute differences in times, expressed in difference + units (e.g. days, hours, minutes, seconds). This method converts + an argument from a recognized timedelta format / value into + a Timedelta type. Parameters ---------- - arg : string, timedelta, list, tuple, 1-d array, or Series - unit : str, optional - Denote the unit of the input, if input is an integer. Default 'ns'. - Possible values: - {'Y', 'M', 'W', 'D', 'days', 'day', 'hours', hour', 'hr', 'h', - 'm', 'minute', 'min', 'minutes', 'T', 'S', 'seconds', 'sec', 'second', - 'ms', 'milliseconds', 'millisecond', 'milli', 'millis', 'L', - 'us', 'microseconds', 'microsecond', 'micro', 'micros', 'U', - 'ns', 'nanoseconds', 'nano', 'nanos', 'nanosecond', 'N'} - box : boolean, default True - - If True returns a Timedelta/TimedeltaIndex of the results - - if False returns a np.timedelta64 or ndarray of values of dtype - timedelta64[ns] + arg : str, timedelta, list-like or Series + The data to be converted to timedelta. + unit : str, default 'ns' + Denotes the unit of the arg. Possible values: + ('Y', 'M', 'W', 'D', 'days', 'day', 'hours', hour', 'hr', + 'h', 'm', 'minute', 'min', 'minutes', 'T', 'S', 'seconds', + 'sec', 'second', 'ms', 'milliseconds', 'millisecond', + 'milli', 'millis', 'L', 'us', 'microseconds', 'microsecond', + 'micro', 'micros', 'U', 'ns', 'nanoseconds', 'nano', 'nanos', + 'nanosecond', 'N'). + box : bool, default True + - If True returns a Timedelta/TimedeltaIndex of the results. + - If False returns a numpy.timedelta64 or numpy.darray of + values of dtype timedelta64[ns]. errors : {'ignore', 'raise', 'coerce'}, default 'raise' - - If 'raise', then invalid parsing will raise an exception - - If 'coerce', then invalid parsing will be set as NaT - - If 'ignore', then invalid parsing will return the input + - If 'raise', then invalid parsing will raise an exception. + - If 'coerce', then invalid parsing will be set as NaT. + - If 'ignore', then invalid parsing will return the input. Returns ------- - ret : timedelta64/arrays of timedelta64 if parsing succeeded + timedelta64 or numpy.array of timedelta64 + Output type returned if parsing succeeded. + + See also + -------- + DataFrame.astype : Cast argument to a specified dtype. + to_datetime : Convert argument to datetime. Examples -------- @@ -68,10 +80,10 @@ def to_timedelta(arg, unit='ns', box=True, errors='raise'): TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'], dtype='timedelta64[ns]', freq=None) - See Also - -------- - pandas.DataFrame.astype : Cast argument to a specified dtype. - pandas.to_datetime : Convert argument to datetime. + Returning an ndarray by using the 'box' keyword argument: + + >>> pd.to_timedelta(np.arange(5), box=False) + array([0, 1, 2, 3, 4], dtype='timedelta64[ns]') """ unit = parse_timedelta_unit(unit)
- [x] closes #23248 - [x] tests added / passed - [x] passes `git diff upstream/master --name-only -- "*.py" | grep "pandas/" | xargs flake8` - [x] passes `python scripts/validate_docstrings.py pandas.to_timedelta`
https://api.github.com/repos/pandas-dev/pandas/pulls/23259
2018-10-20T21:43:56Z
2018-11-20T10:26:33Z
2018-11-20T10:26:33Z
2018-11-20T10:26:47Z
CLN: remove unused try_cast kwarg from ops
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 257e8a8c6d726..6dd9174028f18 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4971,14 +4971,14 @@ def _combine_match_index(self, other, func, level=None): index=left.index, columns=self.columns, copy=False) - def _combine_match_columns(self, other, func, level=None, try_cast=True): + def _combine_match_columns(self, other, func, level=None): assert isinstance(other, Series) left, right = self.align(other, join='outer', axis=1, level=level, copy=False) assert left.columns.equals(right.index) return ops.dispatch_to_series(left, right, func, axis="columns") - def _combine_const(self, other, func, errors='raise', try_cast=True): + def _combine_const(self, other, func, errors='raise'): assert lib.is_scalar(other) or np.ndim(other) == 0 return ops.dispatch_to_series(self, other, func) diff --git a/pandas/core/ops.py b/pandas/core/ops.py index 42d9fbd4b7585..f29b4410fbf54 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -1726,10 +1726,10 @@ def column_op(a, b): def _combine_series_frame(self, other, func, fill_value=None, axis=None, - level=None, try_cast=True): + level=None): """ Apply binary operator `func` to self, other using alignment and fill - conventions determined by the fill_value, axis, level, and try_cast kwargs. + conventions determined by the fill_value, axis, and level kwargs. Parameters ---------- @@ -1739,7 +1739,6 @@ def _combine_series_frame(self, other, func, fill_value=None, axis=None, fill_value : object, default None axis : {0, 1, 'columns', 'index', None}, default None level : int or None, default None - try_cast : bool, default True Returns ------- @@ -1754,8 +1753,7 @@ def _combine_series_frame(self, other, func, fill_value=None, axis=None, if axis == 0: return self._combine_match_index(other, func, level=level) else: - return self._combine_match_columns(other, func, level=level, - try_cast=try_cast) + return self._combine_match_columns(other, func, level=level) else: if not len(other): return self * np.nan @@ -1766,8 +1764,7 @@ def _combine_series_frame(self, other, func, fill_value=None, axis=None, columns=self.columns) # default axis is columns - return self._combine_match_columns(other, func, level=level, - try_cast=try_cast) + return self._combine_match_columns(other, func, level=level) def _align_method_FRAME(left, right, axis): @@ -1867,13 +1864,13 @@ def f(self, other, axis=default_axis, level=None, fill_value=None): pass_op = op if axis in [0, "columns", None] else na_op return _combine_series_frame(self, other, pass_op, fill_value=fill_value, axis=axis, - level=level, try_cast=True) + level=level) else: if fill_value is not None: self = self.fillna(fill_value) assert np.ndim(other) == 0 - return self._combine_const(other, op, try_cast=True) + return self._combine_const(other, op) f.__name__ = op_name @@ -1909,9 +1906,10 @@ def f(self, other, axis=default_axis, level=None): elif isinstance(other, ABCSeries): return _combine_series_frame(self, other, na_op, fill_value=None, axis=axis, - level=level, try_cast=False) + level=level) else: - return self._combine_const(other, na_op, try_cast=False) + assert np.ndim(other) == 0, other + return self._combine_const(other, na_op) f.__name__ = op_name @@ -1937,14 +1935,13 @@ def f(self, other): elif isinstance(other, ABCSeries): return _combine_series_frame(self, other, func, fill_value=None, axis=None, - level=None, try_cast=False) + level=None) else: # straight boolean comparisons we want to allow all columns # (regardless of dtype to pass thru) See #4537 for discussion. res = self._combine_const(other, func, - errors='ignore', - try_cast=False) + errors='ignore') return res.fillna(True).astype(bool) f.__name__ = op_name @@ -1991,13 +1988,13 @@ def f(self, other, axis=None): self._get_axis_number(axis) if isinstance(other, self._constructor): - return self._compare_constructor(other, na_op, try_cast=False) + return self._compare_constructor(other, na_op) elif isinstance(other, (self._constructor_sliced, ABCDataFrame, ABCSeries)): raise Exception("input needs alignment for this object [{object}]" .format(object=self._constructor)) else: - return self._combine_const(other, na_op, try_cast=False) + return self._combine_const(other, na_op) f.__name__ = op_name diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 1e2d4000413bb..72b014b018735 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -330,7 +330,7 @@ def _init_matrix(self, data, axes, dtype=None, copy=False): # ---------------------------------------------------------------------- # Comparison methods - def _compare_constructor(self, other, func, try_cast=True): + def _compare_constructor(self, other, func): if not self._indexed_same(other): raise Exception('Can only compare identically-labeled ' 'same type objects') @@ -745,13 +745,13 @@ def _combine(self, other, func, axis=0): "{otype!s} is not supported in combine operation with " "{selftype!s}".format(otype=type(other), selftype=type(self))) - def _combine_const(self, other, func, try_cast=True): + def _combine_const(self, other, func): with np.errstate(all='ignore'): new_values = func(self.values, other) d = self._construct_axes_dict() return self._constructor(new_values, **d) - def _combine_frame(self, other, func, axis=0, try_cast=True): + def _combine_frame(self, other, func, axis=0): index, columns = self._get_plane_axes(axis) axis = self._get_axis_number(axis) @@ -770,7 +770,7 @@ def _combine_frame(self, other, func, axis=0, try_cast=True): return self._constructor(new_values, self.items, self.major_axis, self.minor_axis) - def _combine_panel(self, other, func, try_cast=True): + def _combine_panel(self, other, func): items = self.items.union(other.items) major = self.major_axis.union(other.major_axis) minor = self.minor_axis.union(other.minor_axis) diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py index 2ed275e3bbd2d..e46df2b2bde70 100644 --- a/pandas/core/sparse/frame.py +++ b/pandas/core/sparse/frame.py @@ -618,7 +618,7 @@ def _combine_match_index(self, other, func, level=None): new_data, index=new_index, columns=self.columns, default_fill_value=fill_value).__finalize__(self) - def _combine_match_columns(self, other, func, level=None, try_cast=True): + def _combine_match_columns(self, other, func, level=None): # patched version of DataFrame._combine_match_columns to account for # NumPy circumventing __rsub__ with float64 types, e.g.: 3.0 - series, # where 3.0 is numpy.float64 and series is a SparseSeries. Still @@ -642,7 +642,7 @@ def _combine_match_columns(self, other, func, level=None, try_cast=True): new_data, index=self.index, columns=union, default_fill_value=self.default_fill_value).__finalize__(self) - def _combine_const(self, other, func, errors='raise', try_cast=True): + def _combine_const(self, other, func, errors='raise'): return self._apply_columns(lambda x: func(x, other)) def _reindex_index(self, index, method, copy, level, fill_value=np.nan,
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/23258
2018-10-20T20:33:24Z
2018-10-23T12:32:08Z
2018-10-23T12:32:08Z
2020-04-05T17:39:19Z
TST: stricter monotonicity/uniqueness tests
diff --git a/pandas/tests/indexes/multi/test_monotonic.py b/pandas/tests/indexes/multi/test_monotonic.py index f02447e27ab81..b9492794c479b 100644 --- a/pandas/tests/indexes/multi/test_monotonic.py +++ b/pandas/tests/indexes/multi/test_monotonic.py @@ -9,31 +9,31 @@ def test_is_monotonic_increasing(): i = MultiIndex.from_product([np.arange(10), np.arange(10)], names=['one', 'two']) - assert i.is_monotonic - assert i._is_strictly_monotonic_increasing - assert Index(i.values).is_monotonic - assert i._is_strictly_monotonic_increasing + assert i.is_monotonic is True + assert i._is_strictly_monotonic_increasing is True + assert Index(i.values).is_monotonic is True + assert i._is_strictly_monotonic_increasing is True i = MultiIndex.from_product([np.arange(10, 0, -1), np.arange(10)], names=['one', 'two']) - assert not i.is_monotonic - assert not i._is_strictly_monotonic_increasing - assert not Index(i.values).is_monotonic - assert not Index(i.values)._is_strictly_monotonic_increasing + assert i.is_monotonic is False + assert i._is_strictly_monotonic_increasing is False + assert Index(i.values).is_monotonic is False + assert Index(i.values)._is_strictly_monotonic_increasing is False i = MultiIndex.from_product([np.arange(10), np.arange(10, 0, -1)], names=['one', 'two']) - assert not i.is_monotonic - assert not i._is_strictly_monotonic_increasing - assert not Index(i.values).is_monotonic - assert not Index(i.values)._is_strictly_monotonic_increasing + assert i.is_monotonic is False + assert i._is_strictly_monotonic_increasing is False + assert Index(i.values).is_monotonic is False + assert Index(i.values)._is_strictly_monotonic_increasing is False i = MultiIndex.from_product([[1.0, np.nan, 2.0], ['a', 'b', 'c']]) - assert not i.is_monotonic - assert not i._is_strictly_monotonic_increasing - assert not Index(i.values).is_monotonic - assert not Index(i.values)._is_strictly_monotonic_increasing + assert i.is_monotonic is False + assert i._is_strictly_monotonic_increasing is False + assert Index(i.values).is_monotonic is False + assert Index(i.values)._is_strictly_monotonic_increasing is False # string ordering i = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], @@ -41,20 +41,20 @@ def test_is_monotonic_increasing(): labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) - assert not i.is_monotonic - assert not Index(i.values).is_monotonic - assert not i._is_strictly_monotonic_increasing - assert not Index(i.values)._is_strictly_monotonic_increasing + assert i.is_monotonic is False + assert Index(i.values).is_monotonic is False + assert i._is_strictly_monotonic_increasing is False + assert Index(i.values)._is_strictly_monotonic_increasing is False i = MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['mom', 'next', 'zenith']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) - assert i.is_monotonic - assert Index(i.values).is_monotonic - assert i._is_strictly_monotonic_increasing - assert Index(i.values)._is_strictly_monotonic_increasing + assert i.is_monotonic is True + assert Index(i.values).is_monotonic is True + assert i._is_strictly_monotonic_increasing is True + assert Index(i.values)._is_strictly_monotonic_increasing is True # mixed levels, hits the TypeError i = MultiIndex( @@ -64,46 +64,46 @@ def test_is_monotonic_increasing(): labels=[[0, 1, 1, 2, 2, 2, 3], [4, 2, 0, 0, 1, 3, -1]], names=['household_id', 'asset_id']) - assert not i.is_monotonic - assert not i._is_strictly_monotonic_increasing + assert i.is_monotonic is False + assert i._is_strictly_monotonic_increasing is False # empty i = MultiIndex.from_arrays([[], []]) - assert i.is_monotonic - assert Index(i.values).is_monotonic - assert i._is_strictly_monotonic_increasing - assert Index(i.values)._is_strictly_monotonic_increasing + assert i.is_monotonic is True + assert Index(i.values).is_monotonic is True + assert i._is_strictly_monotonic_increasing is True + assert Index(i.values)._is_strictly_monotonic_increasing is True def test_is_monotonic_decreasing(): i = MultiIndex.from_product([np.arange(9, -1, -1), np.arange(9, -1, -1)], names=['one', 'two']) - assert i.is_monotonic_decreasing - assert i._is_strictly_monotonic_decreasing - assert Index(i.values).is_monotonic_decreasing - assert i._is_strictly_monotonic_decreasing + assert i.is_monotonic_decreasing is True + assert i._is_strictly_monotonic_decreasing is True + assert Index(i.values).is_monotonic_decreasing is True + assert i._is_strictly_monotonic_decreasing is True i = MultiIndex.from_product([np.arange(10), np.arange(10, 0, -1)], names=['one', 'two']) - assert not i.is_monotonic_decreasing - assert not i._is_strictly_monotonic_decreasing - assert not Index(i.values).is_monotonic_decreasing - assert not Index(i.values)._is_strictly_monotonic_decreasing + assert i.is_monotonic_decreasing is False + assert i._is_strictly_monotonic_decreasing is False + assert Index(i.values).is_monotonic_decreasing is False + assert Index(i.values)._is_strictly_monotonic_decreasing is False i = MultiIndex.from_product([np.arange(10, 0, -1), np.arange(10)], names=['one', 'two']) - assert not i.is_monotonic_decreasing - assert not i._is_strictly_monotonic_decreasing - assert not Index(i.values).is_monotonic_decreasing - assert not Index(i.values)._is_strictly_monotonic_decreasing + assert i.is_monotonic_decreasing is False + assert i._is_strictly_monotonic_decreasing is False + assert Index(i.values).is_monotonic_decreasing is False + assert Index(i.values)._is_strictly_monotonic_decreasing is False i = MultiIndex.from_product([[2.0, np.nan, 1.0], ['c', 'b', 'a']]) - assert not i.is_monotonic_decreasing - assert not i._is_strictly_monotonic_decreasing - assert not Index(i.values).is_monotonic_decreasing - assert not Index(i.values)._is_strictly_monotonic_decreasing + assert i.is_monotonic_decreasing is False + assert i._is_strictly_monotonic_decreasing is False + assert Index(i.values).is_monotonic_decreasing is False + assert Index(i.values)._is_strictly_monotonic_decreasing is False # string ordering i = MultiIndex(levels=[['qux', 'foo', 'baz', 'bar'], @@ -111,20 +111,20 @@ def test_is_monotonic_decreasing(): labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) - assert not i.is_monotonic_decreasing - assert not Index(i.values).is_monotonic_decreasing - assert not i._is_strictly_monotonic_decreasing - assert not Index(i.values)._is_strictly_monotonic_decreasing + assert i.is_monotonic_decreasing is False + assert Index(i.values).is_monotonic_decreasing is False + assert i._is_strictly_monotonic_decreasing is False + assert Index(i.values)._is_strictly_monotonic_decreasing is False i = MultiIndex(levels=[['qux', 'foo', 'baz', 'bar'], ['zenith', 'next', 'mom']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) - assert i.is_monotonic_decreasing - assert Index(i.values).is_monotonic_decreasing - assert i._is_strictly_monotonic_decreasing - assert Index(i.values)._is_strictly_monotonic_decreasing + assert i.is_monotonic_decreasing is True + assert Index(i.values).is_monotonic_decreasing is True + assert i._is_strictly_monotonic_decreasing is True + assert Index(i.values)._is_strictly_monotonic_decreasing is True # mixed levels, hits the TypeError i = MultiIndex( @@ -134,29 +134,29 @@ def test_is_monotonic_decreasing(): labels=[[0, 1, 1, 2, 2, 2, 3], [4, 2, 0, 0, 1, 3, -1]], names=['household_id', 'asset_id']) - assert not i.is_monotonic_decreasing - assert not i._is_strictly_monotonic_decreasing + assert i.is_monotonic_decreasing is False + assert i._is_strictly_monotonic_decreasing is False # empty i = MultiIndex.from_arrays([[], []]) - assert i.is_monotonic_decreasing - assert Index(i.values).is_monotonic_decreasing - assert i._is_strictly_monotonic_decreasing - assert Index(i.values)._is_strictly_monotonic_decreasing + assert i.is_monotonic_decreasing is True + assert Index(i.values).is_monotonic_decreasing is True + assert i._is_strictly_monotonic_decreasing is True + assert Index(i.values)._is_strictly_monotonic_decreasing is True def test_is_strictly_monotonic_increasing(): idx = pd.MultiIndex(levels=[['bar', 'baz'], ['mom', 'next']], labels=[[0, 0, 1, 1], [0, 0, 0, 1]]) - assert idx.is_monotonic_increasing - assert not idx._is_strictly_monotonic_increasing + assert idx.is_monotonic_increasing is True + assert idx._is_strictly_monotonic_increasing is False def test_is_strictly_monotonic_decreasing(): idx = pd.MultiIndex(levels=[['baz', 'bar'], ['next', 'mom']], labels=[[0, 0, 1, 1], [0, 0, 0, 1]]) - assert idx.is_monotonic_decreasing - assert not idx._is_strictly_monotonic_decreasing + assert idx.is_monotonic_decreasing is True + assert idx._is_strictly_monotonic_decreasing is False def test_searchsorted_monotonic(indices): diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index 6b8e2203e83fd..60ba0491f1ffd 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -404,11 +404,11 @@ def test_is_monotonic_increasing(self): idx_dec1 = pd.PeriodIndex([p2, p1, p1]) idx = pd.PeriodIndex([p1, p2, p0]) - assert idx_inc0.is_monotonic_increasing - assert idx_inc1.is_monotonic_increasing - assert not idx_dec0.is_monotonic_increasing - assert not idx_dec1.is_monotonic_increasing - assert not idx.is_monotonic_increasing + assert idx_inc0.is_monotonic_increasing is True + assert idx_inc1.is_monotonic_increasing is True + assert idx_dec0.is_monotonic_increasing is False + assert idx_dec1.is_monotonic_increasing is False + assert idx.is_monotonic_increasing is False def test_is_monotonic_decreasing(self): # GH 17717 @@ -422,11 +422,11 @@ def test_is_monotonic_decreasing(self): idx_dec1 = pd.PeriodIndex([p2, p1, p1]) idx = pd.PeriodIndex([p1, p2, p0]) - assert not idx_inc0.is_monotonic_decreasing - assert not idx_inc1.is_monotonic_decreasing - assert idx_dec0.is_monotonic_decreasing - assert idx_dec1.is_monotonic_decreasing - assert not idx.is_monotonic_decreasing + assert idx_inc0.is_monotonic_decreasing is False + assert idx_inc1.is_monotonic_decreasing is False + assert idx_dec0.is_monotonic_decreasing is True + assert idx_dec1.is_monotonic_decreasing is True + assert idx.is_monotonic_decreasing is False def test_is_unique(self): # GH 17717 @@ -435,10 +435,10 @@ def test_is_unique(self): p2 = pd.Period('2017-09-03') idx0 = pd.PeriodIndex([p0, p1, p2]) - assert idx0.is_unique + assert idx0.is_unique is True idx1 = pd.PeriodIndex([p1, p1, p2]) - assert not idx1.is_unique + assert idx1.is_unique is False def test_contains(self): # GH 17717 diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 2eaa43e049f62..921bcda62794d 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2427,10 +2427,10 @@ def test_repeat(self): pd.to_datetime(['2000-01-01', 'NaT', '2000-01-02']), pd.to_timedelta(['1 day', 'NaT'])]) def test_is_monotonic_na(self, index): - assert not index.is_monotonic_increasing - assert not index.is_monotonic_decreasing - assert not index._is_strictly_monotonic_increasing - assert not index._is_strictly_monotonic_decreasing + assert index.is_monotonic_increasing is False + assert index.is_monotonic_decreasing is False + assert index._is_strictly_monotonic_increasing is False + assert index._is_strictly_monotonic_decreasing is False def test_repr_summary(self): with cf.option_context('display.max_seq_items', 10): diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py index d49a6a6abc7c9..99058f883a392 100644 --- a/pandas/tests/indexes/test_category.py +++ b/pandas/tests/indexes/test_category.py @@ -555,37 +555,37 @@ def test_reindex_empty_index(self): ]) def test_is_monotonic(self, data, non_lexsorted_data): c = CategoricalIndex(data) - assert c.is_monotonic_increasing - assert not c.is_monotonic_decreasing + assert c.is_monotonic_increasing is True + assert c.is_monotonic_decreasing is False c = CategoricalIndex(data, ordered=True) - assert c.is_monotonic_increasing - assert not c.is_monotonic_decreasing + assert c.is_monotonic_increasing is True + assert c.is_monotonic_decreasing is False c = CategoricalIndex(data, categories=reversed(data)) - assert not c.is_monotonic_increasing - assert c.is_monotonic_decreasing + assert c.is_monotonic_increasing is False + assert c.is_monotonic_decreasing is True c = CategoricalIndex(data, categories=reversed(data), ordered=True) - assert not c.is_monotonic_increasing - assert c.is_monotonic_decreasing + assert c.is_monotonic_increasing is False + assert c.is_monotonic_decreasing is True # test when data is neither monotonic increasing nor decreasing reordered_data = [data[0], data[2], data[1]] c = CategoricalIndex(reordered_data, categories=reversed(data)) - assert not c.is_monotonic_increasing - assert not c.is_monotonic_decreasing + assert c.is_monotonic_increasing is False + assert c.is_monotonic_decreasing is False # non lexsorted categories categories = non_lexsorted_data c = CategoricalIndex(categories[:2], categories=categories) - assert c.is_monotonic_increasing - assert not c.is_monotonic_decreasing + assert c.is_monotonic_increasing is True + assert c.is_monotonic_decreasing is False c = CategoricalIndex(categories[1:3], categories=categories) - assert c.is_monotonic_increasing - assert not c.is_monotonic_decreasing + assert c.is_monotonic_increasing is True + assert c.is_monotonic_decreasing is False @pytest.mark.parametrize('values, expected', [ ([1, 2, 3], True), @@ -599,8 +599,8 @@ def test_is_unique(self, values, expected): def test_has_duplicates(self): idx = CategoricalIndex([0, 0, 0], name='foo') - assert not idx.is_unique - assert idx.has_duplicates + assert idx.is_unique is False + assert idx.has_duplicates is True def test_drop_duplicates(self): diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 1cb2cd46a65db..186f00cfe7426 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -422,32 +422,32 @@ def test_view(self, indices): tm.assert_index_equal(i, self._holder(i_view, name='Foo')) def test_is_monotonic(self): - assert self.index.is_monotonic - assert self.index.is_monotonic_increasing - assert self.index._is_strictly_monotonic_increasing - assert not self.index.is_monotonic_decreasing - assert not self.index._is_strictly_monotonic_decreasing + assert self.index.is_monotonic is True + assert self.index.is_monotonic_increasing is True + assert self.index._is_strictly_monotonic_increasing is True + assert self.index.is_monotonic_decreasing is False + assert self.index._is_strictly_monotonic_decreasing is False index = self._holder([4, 3, 2, 1]) - assert not index.is_monotonic - assert not index._is_strictly_monotonic_increasing - assert index._is_strictly_monotonic_decreasing + assert index.is_monotonic is False + assert index._is_strictly_monotonic_increasing is False + assert index._is_strictly_monotonic_decreasing is True index = self._holder([1]) - assert index.is_monotonic - assert index.is_monotonic_increasing - assert index.is_monotonic_decreasing - assert index._is_strictly_monotonic_increasing - assert index._is_strictly_monotonic_decreasing + assert index.is_monotonic is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True def test_is_strictly_monotonic(self): index = self._holder([1, 1, 2, 3]) - assert index.is_monotonic_increasing - assert not index._is_strictly_monotonic_increasing + assert index.is_monotonic_increasing is True + assert index._is_strictly_monotonic_increasing is False index = self._holder([3, 2, 1, 1]) - assert index.is_monotonic_decreasing - assert not index._is_strictly_monotonic_decreasing + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_decreasing is False index = self._holder([1, 1]) assert index.is_monotonic_increasing diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py index 2a9efd92df8a3..0e47fcd52f625 100644 --- a/pandas/tests/indexes/test_range.py +++ b/pandas/tests/indexes/test_range.py @@ -340,38 +340,38 @@ def test_dtype(self): assert self.index.dtype == np.int64 def test_is_monotonic(self): - assert self.index.is_monotonic - assert self.index.is_monotonic_increasing - assert not self.index.is_monotonic_decreasing - assert self.index._is_strictly_monotonic_increasing - assert not self.index._is_strictly_monotonic_decreasing + assert self.index.is_monotonic is True + assert self.index.is_monotonic_increasing is True + assert self.index.is_monotonic_decreasing is False + assert self.index._is_strictly_monotonic_increasing is True + assert self.index._is_strictly_monotonic_decreasing is False index = RangeIndex(4, 0, -1) - assert not index.is_monotonic - assert not index._is_strictly_monotonic_increasing - assert index.is_monotonic_decreasing - assert index._is_strictly_monotonic_decreasing + assert index.is_monotonic is False + assert index._is_strictly_monotonic_increasing is False + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_decreasing is True index = RangeIndex(1, 2) - assert index.is_monotonic - assert index.is_monotonic_increasing - assert index.is_monotonic_decreasing - assert index._is_strictly_monotonic_increasing - assert index._is_strictly_monotonic_decreasing + assert index.is_monotonic is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True index = RangeIndex(2, 1) - assert index.is_monotonic - assert index.is_monotonic_increasing - assert index.is_monotonic_decreasing - assert index._is_strictly_monotonic_increasing - assert index._is_strictly_monotonic_decreasing + assert index.is_monotonic is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True index = RangeIndex(1, 1) - assert index.is_monotonic - assert index.is_monotonic_increasing - assert index.is_monotonic_decreasing - assert index._is_strictly_monotonic_increasing - assert index._is_strictly_monotonic_decreasing + assert index.is_monotonic is True + assert index.is_monotonic_increasing is True + assert index.is_monotonic_decreasing is True + assert index._is_strictly_monotonic_increasing is True + assert index._is_strictly_monotonic_decreasing is True def test_equals_range(self): equiv_pairs = [(RangeIndex(0, 9, 2), RangeIndex(0, 10, 2)), diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index d4a204ed265b5..a00a9816c70c0 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -1439,17 +1439,17 @@ def test_is_monotonic(self): s = Series(np.random.randint(0, 10, size=1000)) assert not s.is_monotonic s = Series(np.arange(1000)) - assert s.is_monotonic - assert s.is_monotonic_increasing + assert s.is_monotonic is True + assert s.is_monotonic_increasing is True s = Series(np.arange(1000, 0, -1)) - assert s.is_monotonic_decreasing + assert s.is_monotonic_decreasing is True s = Series(pd.date_range('20130101', periods=10)) - assert s.is_monotonic - assert s.is_monotonic_increasing + assert s.is_monotonic is True + assert s.is_monotonic_increasing is True s = Series(list(reversed(s.tolist()))) - assert not s.is_monotonic - assert s.is_monotonic_decreasing + assert s.is_monotonic is False + assert s.is_monotonic_decreasing is True def test_sort_index_level(self): mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC'))
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Asserting a method always passes. For example ``assert df.agg`` always passes. By making the monotonicity and uniqueness tests stricter (i.e. testing for actual True/False rather than truthy/Falsy values) I think we get better ensurance that some PR doesn't accidentally turn a property into a method or that the property doesn't accidentally returns a non-boolean return value.
https://api.github.com/repos/pandas-dev/pandas/pulls/23256
2018-10-20T19:24:39Z
2018-10-23T03:18:28Z
2018-10-23T03:18:28Z
2018-10-23T08:27:34Z
ENH:Add EA types to read CSV
diff --git a/doc/source/io.rst b/doc/source/io.rst index 7230ff55f9a6c..3bbd4e8410fa5 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -362,16 +362,17 @@ columns: .. ipython:: python - data = ('a,b,c\n' - '1,2,3\n' - '4,5,6\n' - '7,8,9') + data = ('a,b,c,d\n' + '1,2,3,4\n' + '5,6,7,8\n' + '9,10,11') print(data) df = pd.read_csv(StringIO(data), dtype=object) df df['a'][0] - df = pd.read_csv(StringIO(data), dtype={'b': object, 'c': np.float64}) + df = pd.read_csv(StringIO(data), + dtype={'b': object, 'c': np.float64, 'd': 'Int64'}) df.dtypes Fortunately, pandas offers more than one way to ensure that your column(s) diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index a84fd118061bc..028ed99b23a6c 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -31,6 +31,7 @@ New features - :func:`read_feather` now accepts ``columns`` as an argument, allowing the user to specify which columns should be read. (:issue:`24025`) - :func:`DataFrame.to_html` now accepts ``render_links`` as an argument, allowing the user to generate HTML with links to any URLs that appear in the DataFrame. See the :ref:`section on writing HTML <io.html>` in the IO docs for example usage. (:issue:`2679`) +- :func:`pandas.read_csv` now supports pandas extension types as an argument to ``dtype``, allowing the user to use pandas extension types when reading CSVs. (:issue:`23228`) - :meth:`DataFrame.shift` :meth:`Series.shift`, :meth:`ExtensionArray.shift`, :meth:`SparseArray.shift`, :meth:`Period.shift`, :meth:`GroupBy.shift`, :meth:`Categorical.shift`, :meth:`NDFrame.shift` and :meth:`Block.shift` now accept `fill_value` as an argument, allowing the user to specify a value which will be used instead of NA/NaT in the empty periods. (:issue:`15486`) .. _whatsnew_0240.values_api: diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 169aa4ffe72da..0b7edaf04a1ed 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -50,7 +50,7 @@ from pandas.core.dtypes.common import ( is_integer_dtype, is_float_dtype, is_bool_dtype, is_object_dtype, is_datetime64_dtype, - pandas_dtype) + pandas_dtype, is_extension_array_dtype) from pandas.core.arrays import Categorical from pandas.core.dtypes.concat import union_categoricals import pandas.io.common as icom @@ -983,7 +983,6 @@ cdef class TextReader: footer=footer, upcast_na=True) self._end_clock('Type conversion') - self._start_clock() if len(columns) > 0: rows_read = len(list(columns.values())[0]) @@ -1123,7 +1122,9 @@ cdef class TextReader: if na_filter: self._free_na_set(na_hashset) - if upcast_na and na_count > 0: + # don't try to upcast EAs + try_upcast = upcast_na and na_count > 0 + if try_upcast and not is_extension_array_dtype(col_dtype): col_res = _maybe_upcast(col_res) if col_res is None: @@ -1215,6 +1216,22 @@ cdef class TextReader: cats, codes, dtype, true_values=true_values) return cat, na_count + elif is_extension_array_dtype(dtype): + result, na_count = self._string_convert(i, start, end, na_filter, + na_hashset) + array_type = dtype.construct_array_type() + try: + # use _from_sequence_of_strings if the class defines it + result = array_type._from_sequence_of_strings(result, + dtype=dtype) + except NotImplementedError: + raise NotImplementedError( + "Extension Array: {ea} must implement " + "_from_sequence_of_strings in order " + "to be used in parser methods".format(ea=array_type)) + + return result, na_count + elif is_integer_dtype(dtype): try: result, na_count = _try_int64(self.parser, i, start, @@ -1240,7 +1257,6 @@ cdef class TextReader: if result is not None and dtype != 'float64': result = result.astype(dtype) return result, na_count - elif is_bool_dtype(dtype): result, na_count = _try_bool_flex(self.parser, i, start, end, na_filter, na_hashset, @@ -2173,7 +2189,11 @@ def _concatenate_chunks(list chunks): result[name] = union_categoricals(arrs, sort_categories=sort_categories) else: - result[name] = np.concatenate(arrs) + if is_extension_array_dtype(dtype): + array_type = dtype.construct_array_type() + result[name] = array_type._concat_same_type(arrs) + else: + result[name] = np.concatenate(arrs) if warning_columns: warning_names = ','.join(warning_columns) diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 2d4f8ca9c2cee..7aaefef3d03e5 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -78,6 +78,11 @@ class ExtensionArray(object): * _reduce + One can implement methods to handle parsing from strings that will be used + in methods such as ``pandas.io.parsers.read_csv``. + + * _from_sequence_of_strings + This class does not inherit from 'abc.ABCMeta' for performance reasons. Methods and properties required by the interface raise ``pandas.errors.AbstractMethodError`` and no ``register`` method is @@ -128,6 +133,30 @@ def _from_sequence(cls, scalars, dtype=None, copy=False): """ raise AbstractMethodError(cls) + @classmethod + def _from_sequence_of_strings(cls, strings, dtype=None, copy=False): + """Construct a new ExtensionArray from a sequence of strings. + + .. versionadded:: 0.24.0 + + Parameters + ---------- + strings : Sequence + Each element will be an instance of the scalar type for this + array, ``cls.dtype.type``. + dtype : dtype, optional + Construct for this particular dtype. This should be a Dtype + compatible with the ExtensionArray. + copy : boolean, default False + If True, copy the underlying data. + + Returns + ------- + ExtensionArray + + """ + raise AbstractMethodError(cls) + @classmethod def _from_factorized(cls, values, original): """ diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 38dc68e8f77a3..eaec76b96a24d 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -19,6 +19,7 @@ from pandas.core import nanops from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin +from pandas.core.tools.numeric import to_numeric class _IntegerDtype(ExtensionDtype): @@ -261,6 +262,11 @@ def __init__(self, values, mask, copy=False): def _from_sequence(cls, scalars, dtype=None, copy=False): return integer_array(scalars, dtype=dtype, copy=copy) + @classmethod + def _from_sequence_of_strings(cls, strings, dtype=None, copy=False): + scalars = to_numeric(strings, errors="raise") + return cls._from_sequence(scalars, dtype, copy) + @classmethod def _from_factorized(cls, values, original): return integer_array(values, dtype=original.dtype) diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index de0ed9407e161..0d10e8b8985cb 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -28,8 +28,8 @@ from pandas.core.dtypes.cast import astype_nansafe from pandas.core.dtypes.common import ( ensure_object, is_bool_dtype, is_categorical_dtype, is_dtype_equal, - is_float, is_integer, is_integer_dtype, is_list_like, is_object_dtype, - is_scalar, is_string_dtype) + is_extension_array_dtype, is_float, is_integer, is_integer_dtype, + is_list_like, is_object_dtype, is_scalar, is_string_dtype, pandas_dtype) from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.missing import isna @@ -134,7 +134,8 @@ 'X'...'X'. Passing in False will cause data to be overwritten if there are duplicate names in the columns. dtype : Type name or dict of column -> type, optional - Data type for data or columns. E.g. {{'a': np.float64, 'b': np.int32}} + Data type for data or columns. E.g. {{'a': np.float64, 'b': np.int32, + 'c': 'Int64'}} Use `str` or `object` together with suitable `na_values` settings to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD @@ -1659,16 +1660,20 @@ def _convert_to_ndarrays(self, dct, na_values, na_fvalues, verbose=False, values, set(col_na_values) | col_na_fvalues, try_num_bool=False) else: + is_str_or_ea_dtype = (is_string_dtype(cast_type) + or is_extension_array_dtype(cast_type)) # skip inference if specified dtype is object - try_num_bool = not (cast_type and is_string_dtype(cast_type)) + # or casting to an EA + try_num_bool = not (cast_type and is_str_or_ea_dtype) # general type inference and conversion cvals, na_count = self._infer_types( values, set(col_na_values) | col_na_fvalues, try_num_bool) - # type specified in dtype param - if cast_type and not is_dtype_equal(cvals, cast_type): + # type specified in dtype param or cast_type is an EA + if cast_type and (not is_dtype_equal(cvals, cast_type) + or is_extension_array_dtype(cast_type)): try: if (is_bool_dtype(cast_type) and not is_categorical_dtype(cast_type) @@ -1765,6 +1770,20 @@ def _cast_types(self, values, cast_type, column): cats, cats.get_indexer(values), cast_type, true_values=self.true_values) + # use the EA's implementation of casting + elif is_extension_array_dtype(cast_type): + # ensure cast_type is an actual dtype and not a string + cast_type = pandas_dtype(cast_type) + array_type = cast_type.construct_array_type() + try: + return array_type._from_sequence_of_strings(values, + dtype=cast_type) + except NotImplementedError: + raise NotImplementedError( + "Extension Array: {ea} must implement " + "_from_sequence_of_strings in order " + "to be used in parser methods".format(ea=array_type)) + else: try: values = astype_nansafe(values, cast_type, @@ -2174,8 +2193,8 @@ def __init__(self, f, **kwds): self.verbose = kwds['verbose'] self.converters = kwds['converters'] - self.dtype = kwds['dtype'] + self.dtype = kwds['dtype'] self.thousands = kwds['thousands'] self.decimal = kwds['decimal'] diff --git a/pandas/tests/extension/base/__init__.py b/pandas/tests/extension/base/__init__.py index 57704b77bb233..1f7ee2ae17e4a 100644 --- a/pandas/tests/extension/base/__init__.py +++ b/pandas/tests/extension/base/__init__.py @@ -53,3 +53,4 @@ class TestMyDtype(BaseDtypeTests): from .missing import BaseMissingTests # noqa from .reshaping import BaseReshapingTests # noqa from .setitem import BaseSetitemTests # noqa +from .io import BaseParsingTests # noqa diff --git a/pandas/tests/extension/base/io.py b/pandas/tests/extension/base/io.py new file mode 100644 index 0000000000000..7ea62e4e9d678 --- /dev/null +++ b/pandas/tests/extension/base/io.py @@ -0,0 +1,23 @@ +import numpy as np +import pytest + +from pandas.compat import StringIO + +import pandas as pd + +from .base import BaseExtensionTests + + +class BaseParsingTests(BaseExtensionTests): + + @pytest.mark.parametrize('engine', ['c', 'python']) + def test_EA_types(self, engine, data): + df = pd.DataFrame({ + 'with_dtype': pd.Series(data, dtype=str(data.dtype)) + }) + csv_output = df.to_csv(index=False, na_rep=np.nan) + result = pd.read_csv(StringIO(csv_output), dtype={ + 'with_dtype': str(data.dtype) + }, engine=engine) + expected = df + self.assert_frame_equal(result, expected) diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 7e618dfd2b92e..1823eeb4d7fc0 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -75,6 +75,11 @@ def dtype(self): def _from_sequence(cls, scalars, dtype=None, copy=False): return cls(scalars) + @classmethod + def _from_sequence_of_strings(cls, strings, dtype=None, copy=False): + return cls._from_sequence([decimal.Decimal(x) for x in strings], + dtype, copy) + @classmethod def _from_factorized(cls, values, original): return cls(values) diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index c876db416470c..ac52d8f15b8ce 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -237,3 +237,7 @@ def _compare_other(self, s, data, op_name, other): else: with pytest.raises(TypeError): op(data, other) + + +class TestParsing(base.BaseParsingTests): + pass diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py index e21ca81bcf5c3..aadf9f2f12b68 100644 --- a/pandas/tests/extension/test_integer.py +++ b/pandas/tests/extension/test_integer.py @@ -218,3 +218,7 @@ class TestBooleanReduce(base.BaseBooleanReduceTests): class TestPrinting(base.BasePrintingTests): pass + + +class TestParsing(base.BaseParsingTests): + pass diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py index 644f3ef94f40b..6eedbfb4aba39 100644 --- a/pandas/tests/extension/test_interval.py +++ b/pandas/tests/extension/test_interval.py @@ -152,3 +152,11 @@ class TestPrinting(BaseInterval, base.BasePrintingTests): @pytest.mark.skip(reason="custom repr") def test_array_repr(self, data, size): pass + + +class TestParsing(BaseInterval, base.BaseParsingTests): + @pytest.mark.parametrize('engine', ['c', 'python']) + def test_EA_types(self, engine, data): + expected_msg = r'.*must implement _from_sequence_of_strings.*' + with pytest.raises(NotImplementedError, match=expected_msg): + super(TestParsing, self).test_EA_types(engine, data) diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 70a3a8ab58aac..7ca6882c7441b 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -210,3 +210,7 @@ def test_concat_mixed_dtypes(self, data): class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): pass + + +class TestParsing(BaseNumPyTests, base.BaseParsingTests): + pass diff --git a/pandas/tests/extension/test_period.py b/pandas/tests/extension/test_period.py index 08e21fc30ad10..813efcb5678d3 100644 --- a/pandas/tests/extension/test_period.py +++ b/pandas/tests/extension/test_period.py @@ -156,3 +156,11 @@ class TestGroupby(BasePeriodTests, base.BaseGroupbyTests): class TestPrinting(BasePeriodTests, base.BasePrintingTests): pass + + +class TestParsing(BasePeriodTests, base.BaseParsingTests): + @pytest.mark.parametrize('engine', ['c', 'python']) + def test_EA_types(self, engine, data): + expected_msg = r'.*must implement _from_sequence_of_strings.*' + with pytest.raises(NotImplementedError, match=expected_msg): + super(TestParsing, self).test_EA_types(engine, data) diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 257eb44cd94fe..39a138ed534bd 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -359,3 +359,11 @@ class TestPrinting(BaseSparseTests, base.BasePrintingTests): @pytest.mark.xfail(reason='Different repr', strict=True) def test_array_repr(self, data, size): super(TestPrinting, self).test_array_repr(data, size) + + +class TestParsing(BaseSparseTests, base.BaseParsingTests): + @pytest.mark.parametrize('engine', ['c', 'python']) + def test_EA_types(self, engine, data): + expected_msg = r'.*must implement _from_sequence_of_strings.*' + with pytest.raises(NotImplementedError, match=expected_msg): + super(TestParsing, self).test_EA_types(engine, data) diff --git a/pandas/tests/io/parser/common.py b/pandas/tests/io/parser/common.py new file mode 100644 index 0000000000000..e69de29bb2d1d
Closes GH23228 - [x ] closes #23228 - [ x] tests added / passed - [x ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x ] whatsnew - May need some guidance on this part.
https://api.github.com/repos/pandas-dev/pandas/pulls/23255
2018-10-20T19:12:14Z
2019-01-02T02:57:20Z
2019-01-02T02:57:20Z
2019-01-05T16:11:17Z
CLN:Remove unused **kwargs from user facing methods
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 41e14e482d061..4c28e0f88b1ae 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1674,7 +1674,7 @@ def cvalues(self): def __iter__(self): return iter(self.values) - def maybe_set_size(self, min_itemsize=None, **kwargs): + def maybe_set_size(self, min_itemsize=None): """ maybe set a string col itemsize: min_itemsize can be an integer or a dict with this columns name with an integer size """ @@ -1687,13 +1687,13 @@ def maybe_set_size(self, min_itemsize=None, **kwargs): self.typ = _tables( ).StringCol(itemsize=min_itemsize, pos=self.pos) - def validate(self, handler, append, **kwargs): + def validate(self, handler, append): self.validate_names() def validate_names(self): pass - def validate_and_set(self, handler, append, **kwargs): + def validate_and_set(self, handler, append): self.set_table(handler.table) self.validate_col() self.validate_attr(append) @@ -3772,7 +3772,7 @@ def read_coordinates(self, where=None, start=None, stop=None, **kwargs): return Index(coords) - def read_column(self, column, where=None, start=None, stop=None, **kwargs): + def read_column(self, column, where=None, start=None, stop=None): """return a single column from the table, generally only indexables are interesting """ @@ -4727,7 +4727,7 @@ class Selection(object): """ - def __init__(self, table, where=None, start=None, stop=None, **kwargs): + def __init__(self, table, where=None, start=None, stop=None): self.table = table self.where = where self.start = start
closes GH18748 for user facing methods. An updated [extra_kwargs.txt](https://github.com/pandas-dev/pandas/files/2498300/extra_kwargs.txt) mostly shows internal functions and false positives. There are a few cases like all of the `visit_*` functions that removing the `**kwargs` breaks the API. - [ ] xref #18748 - [x ] tests added / passed - [x ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry - N/A only code cleanup.
https://api.github.com/repos/pandas-dev/pandas/pulls/23249
2018-10-20T15:49:42Z
2018-11-12T04:45:27Z
2018-11-12T04:45:27Z
2018-11-12T14:24:34Z
TST: parametrize and de-duplicate arithmetic tests
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 36bb0aca066fb..71eba1e6901a1 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -323,32 +323,35 @@ def test_dti_cmp_null_scalar_inequality(self, tz_naive_fixture, other): with pytest.raises(TypeError): dti >= other - def test_dti_cmp_nat(self): + @pytest.mark.parametrize('dtype', [None, object]) + def test_dti_cmp_nat(self, dtype): left = pd.DatetimeIndex([pd.Timestamp('2011-01-01'), pd.NaT, pd.Timestamp('2011-01-03')]) right = pd.DatetimeIndex([pd.NaT, pd.NaT, pd.Timestamp('2011-01-03')]) - for lhs, rhs in [(left, right), - (left.astype(object), right.astype(object))]: - result = rhs == lhs - expected = np.array([False, False, True]) - tm.assert_numpy_array_equal(result, expected) + lhs, rhs = left, right + if dtype is object: + lhs, rhs = left.astype(object), right.astype(object) + + result = rhs == lhs + expected = np.array([False, False, True]) + tm.assert_numpy_array_equal(result, expected) - result = lhs != rhs - expected = np.array([True, True, False]) - tm.assert_numpy_array_equal(result, expected) + result = lhs != rhs + expected = np.array([True, True, False]) + tm.assert_numpy_array_equal(result, expected) - expected = np.array([False, False, False]) - tm.assert_numpy_array_equal(lhs == pd.NaT, expected) - tm.assert_numpy_array_equal(pd.NaT == rhs, expected) + expected = np.array([False, False, False]) + tm.assert_numpy_array_equal(lhs == pd.NaT, expected) + tm.assert_numpy_array_equal(pd.NaT == rhs, expected) - expected = np.array([True, True, True]) - tm.assert_numpy_array_equal(lhs != pd.NaT, expected) - tm.assert_numpy_array_equal(pd.NaT != lhs, expected) + expected = np.array([True, True, True]) + tm.assert_numpy_array_equal(lhs != pd.NaT, expected) + tm.assert_numpy_array_equal(pd.NaT != lhs, expected) - expected = np.array([False, False, False]) - tm.assert_numpy_array_equal(lhs < pd.NaT, expected) - tm.assert_numpy_array_equal(pd.NaT > lhs, expected) + expected = np.array([False, False, False]) + tm.assert_numpy_array_equal(lhs < pd.NaT, expected) + tm.assert_numpy_array_equal(pd.NaT > lhs, expected) def test_dti_cmp_nat_behaves_like_float_cmp_nan(self): fidx1 = pd.Index([1.0, np.nan, 3.0, np.nan, 5.0, 7.0]) @@ -901,13 +904,15 @@ def test_dt64_series_add_intlike(self, tz, op): other = Series([20, 30, 40], dtype='uint8') - pytest.raises(TypeError, getattr(ser, op), 1) - - pytest.raises(TypeError, getattr(ser, op), other) - - pytest.raises(TypeError, getattr(ser, op), other.values) - - pytest.raises(TypeError, getattr(ser, op), pd.Index(other)) + method = getattr(ser, op) + with pytest.raises(TypeError): + method(1) + with pytest.raises(TypeError): + method(other) + with pytest.raises(TypeError): + method(other.values) + with pytest.raises(TypeError): + method(pd.Index(other)) # ------------------------------------------------------------- # Timezone-Centric Tests @@ -994,10 +999,6 @@ def test_dti_add_timestamp_raises(self, box): msg = "cannot add" with tm.assert_raises_regex(TypeError, msg): idx + Timestamp('2011-01-01') - - def test_dti_radd_timestamp_raises(self): - idx = DatetimeIndex(['2011-01-01', '2011-01-02']) - msg = "cannot add DatetimeIndex and Timestamp" with tm.assert_raises_regex(TypeError, msg): Timestamp('2011-01-01') + idx diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index fe98b74499983..4ccebd4305b90 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -11,7 +11,6 @@ import pandas.util.testing as tm from pandas.errors import PerformanceWarning -from pandas._libs.tslibs.period import IncompatibleFrequency import pandas.core.indexes.period as period from pandas.core import ops @@ -30,75 +29,107 @@ def test_pi_cmp_period(self): tm.assert_numpy_array_equal(result, exp) @pytest.mark.parametrize('freq', ['M', '2M', '3M']) - def test_pi_cmp_pi(self, freq): + def test_parr_cmp_period_scalar(self, freq, box): + # GH#13200 + xbox = np.ndarray if box is pd.Index else box + base = PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04'], freq=freq) + base = tm.box_expected(base, box) per = Period('2011-02', freq=freq) exp = np.array([False, True, False, False]) - tm.assert_numpy_array_equal(base == per, exp) - tm.assert_numpy_array_equal(per == base, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base == per, exp) + tm.assert_equal(per == base, exp) exp = np.array([True, False, True, True]) - tm.assert_numpy_array_equal(base != per, exp) - tm.assert_numpy_array_equal(per != base, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base != per, exp) + tm.assert_equal(per != base, exp) exp = np.array([False, False, True, True]) - tm.assert_numpy_array_equal(base > per, exp) - tm.assert_numpy_array_equal(per < base, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base > per, exp) + tm.assert_equal(per < base, exp) exp = np.array([True, False, False, False]) - tm.assert_numpy_array_equal(base < per, exp) - tm.assert_numpy_array_equal(per > base, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base < per, exp) + tm.assert_equal(per > base, exp) exp = np.array([False, True, True, True]) - tm.assert_numpy_array_equal(base >= per, exp) - tm.assert_numpy_array_equal(per <= base, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base >= per, exp) + tm.assert_equal(per <= base, exp) exp = np.array([True, True, False, False]) - tm.assert_numpy_array_equal(base <= per, exp) - tm.assert_numpy_array_equal(per >= base, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base <= per, exp) + tm.assert_equal(per >= base, exp) + + @pytest.mark.parametrize('freq', ['M', '2M', '3M']) + def test_parr_cmp_pi(self, freq, box_df_fail): + # GH#13200 + box = box_df_fail + xbox = np.ndarray if box is pd.Index else box + base = PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04'], + freq=freq) + base = tm.box_expected(base, box) + + # TODO: could also box idx? idx = PeriodIndex(['2011-02', '2011-01', '2011-03', '2011-05'], freq=freq) exp = np.array([False, False, True, False]) - tm.assert_numpy_array_equal(base == idx, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base == idx, exp) exp = np.array([True, True, False, True]) - tm.assert_numpy_array_equal(base != idx, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base != idx, exp) exp = np.array([False, True, False, False]) - tm.assert_numpy_array_equal(base > idx, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base > idx, exp) exp = np.array([True, False, False, True]) - tm.assert_numpy_array_equal(base < idx, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base < idx, exp) exp = np.array([False, True, True, False]) - tm.assert_numpy_array_equal(base >= idx, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base >= idx, exp) exp = np.array([True, False, True, True]) - tm.assert_numpy_array_equal(base <= idx, exp) + exp = tm.box_expected(exp, xbox) + tm.assert_equal(base <= idx, exp) @pytest.mark.parametrize('freq', ['M', '2M', '3M']) - def test_pi_cmp_pi_mismatched_freq_raises(self, freq): + def test_parr_cmp_pi_mismatched_freq_raises(self, freq, box_df_fail): + # GH#13200 # different base freq + box = box_df_fail + base = PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04'], freq=freq) + base = tm.box_expected(base, box) - msg = "Input has different freq=A-DEC from PeriodIndex" + msg = "Input has different freq=A-DEC from " with tm.assert_raises_regex(period.IncompatibleFrequency, msg): base <= Period('2011', freq='A') with tm.assert_raises_regex(period.IncompatibleFrequency, msg): Period('2011', freq='A') >= base + # TODO: Could parametrize over boxes for idx? idx = PeriodIndex(['2011', '2012', '2013', '2014'], freq='A') with tm.assert_raises_regex(period.IncompatibleFrequency, msg): base <= idx # Different frequency - msg = "Input has different freq=4M from PeriodIndex" + msg = "Input has different freq=4M from " with tm.assert_raises_regex(period.IncompatibleFrequency, msg): base <= Period('2011', freq='4M') @@ -197,80 +228,6 @@ def test_comp_nat(self, dtype): class TestPeriodSeriesComparisons(object): - @pytest.mark.parametrize('freq', ['M', '2M', '3M']) - def test_cmp_series_period_scalar(self, freq): - # GH 13200 - base = Series([Period(x, freq=freq) for x in - ['2011-01', '2011-02', '2011-03', '2011-04']]) - p = Period('2011-02', freq=freq) - - exp = Series([False, True, False, False]) - tm.assert_series_equal(base == p, exp) - tm.assert_series_equal(p == base, exp) - - exp = Series([True, False, True, True]) - tm.assert_series_equal(base != p, exp) - tm.assert_series_equal(p != base, exp) - - exp = Series([False, False, True, True]) - tm.assert_series_equal(base > p, exp) - tm.assert_series_equal(p < base, exp) - - exp = Series([True, False, False, False]) - tm.assert_series_equal(base < p, exp) - tm.assert_series_equal(p > base, exp) - - exp = Series([False, True, True, True]) - tm.assert_series_equal(base >= p, exp) - tm.assert_series_equal(p <= base, exp) - - exp = Series([True, True, False, False]) - tm.assert_series_equal(base <= p, exp) - tm.assert_series_equal(p >= base, exp) - - # different base freq - msg = "Input has different freq=A-DEC from Period" - with tm.assert_raises_regex(IncompatibleFrequency, msg): - base <= Period('2011', freq='A') - - with tm.assert_raises_regex(IncompatibleFrequency, msg): - Period('2011', freq='A') >= base - - @pytest.mark.parametrize('freq', ['M', '2M', '3M']) - def test_cmp_series_period_series(self, freq): - # GH#13200 - base = Series([Period(x, freq=freq) for x in - ['2011-01', '2011-02', '2011-03', '2011-04']]) - - ser = Series([Period(x, freq=freq) for x in - ['2011-02', '2011-01', '2011-03', '2011-05']]) - - exp = Series([False, False, True, False]) - tm.assert_series_equal(base == ser, exp) - - exp = Series([True, True, False, True]) - tm.assert_series_equal(base != ser, exp) - - exp = Series([False, True, False, False]) - tm.assert_series_equal(base > ser, exp) - - exp = Series([True, False, False, True]) - tm.assert_series_equal(base < ser, exp) - - exp = Series([False, True, True, False]) - tm.assert_series_equal(base >= ser, exp) - - exp = Series([True, False, True, True]) - tm.assert_series_equal(base <= ser, exp) - - ser2 = Series([Period(x, freq='A') for x in - ['2011', '2011', '2011', '2011']]) - - # different base freq - msg = "Input has different freq=A-DEC from Period" - with tm.assert_raises_regex(IncompatibleFrequency, msg): - base <= ser2 - def test_cmp_series_period_series_mixed_freq(self): # GH#13200 base = Series([Period('2011', freq='A'), @@ -405,9 +362,13 @@ def test_parr_sub_pi_mismatched_freq(self, box_df_broadcast_failure): @pytest.mark.parametrize('other', [3.14, np.array([2.0, 3.0])]) @pytest.mark.parametrize('op', [operator.add, ops.radd, operator.sub, ops.rsub]) - def test_pi_add_sub_float(self, op, other): + def test_pi_add_sub_float(self, op, other, box): + if box is pd.DataFrame and isinstance(other, np.ndarray): + pytest.xfail(reason="Tries to broadcast incorrectly") + dti = pd.DatetimeIndex(['2011-01-01', '2011-01-02'], freq='D') pi = dti.to_period('D') + pi = tm.box_expected(pi, box) with pytest.raises(TypeError): op(pi, other) @@ -678,7 +639,7 @@ def test_pi_sub_isub_timedeltalike_daily(self, three_days): rng -= other tm.assert_index_equal(rng, expected) - def test_pi_add_iadd_timedeltalike_freq_mismatch_daily(self, not_daily): + def test_pi_add_sub_timedeltalike_freq_mismatch_daily(self, not_daily): other = not_daily rng = pd.period_range('2014-05-01', '2014-05-15', freq='D') msg = 'Input has different freq(=.+)? from PeriodIndex\\(freq=D\\)' @@ -686,13 +647,10 @@ def test_pi_add_iadd_timedeltalike_freq_mismatch_daily(self, not_daily): rng + other with tm.assert_raises_regex(period.IncompatibleFrequency, msg): rng += other - - def test_pi_sub_timedeltalike_freq_mismatch_daily(self, not_daily): - other = not_daily - rng = pd.period_range('2014-05-01', '2014-05-15', freq='D') - msg = 'Input has different freq(=.+)? from PeriodIndex\\(freq=D\\)' with tm.assert_raises_regex(period.IncompatibleFrequency, msg): rng - other + with tm.assert_raises_regex(period.IncompatibleFrequency, msg): + rng -= other def test_pi_add_iadd_timedeltalike_hourly(self, two_hours): other = two_hours @@ -739,8 +697,8 @@ def test_add_iadd_timedeltalike_annual(self): rng += pd.offsets.YearEnd(5) tm.assert_index_equal(rng, expected) - def test_pi_add_iadd_timedeltalike_freq_mismatch_annual(self, - mismatched_freq): + def test_pi_add_sub_timedeltalike_freq_mismatch_annual(self, + mismatched_freq): other = mismatched_freq rng = pd.period_range('2014', '2024', freq='A') msg = ('Input has different freq(=.+)? ' @@ -749,13 +707,6 @@ def test_pi_add_iadd_timedeltalike_freq_mismatch_annual(self, rng + other with tm.assert_raises_regex(period.IncompatibleFrequency, msg): rng += other - - def test_pi_sub_isub_timedeltalike_freq_mismatch_annual(self, - mismatched_freq): - other = mismatched_freq - rng = pd.period_range('2014', '2024', freq='A') - msg = ('Input has different freq(=.+)? ' - 'from PeriodIndex\\(freq=A-DEC\\)') with tm.assert_raises_regex(period.IncompatibleFrequency, msg): rng - other with tm.assert_raises_regex(period.IncompatibleFrequency, msg): @@ -771,8 +722,8 @@ def test_pi_add_iadd_timedeltalike_M(self): rng += pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected) - def test_pi_add_iadd_timedeltalike_freq_mismatch_monthly(self, - mismatched_freq): + def test_pi_add_sub_timedeltalike_freq_mismatch_monthly(self, + mismatched_freq): other = mismatched_freq rng = pd.period_range('2014-01', '2016-12', freq='M') msg = 'Input has different freq(=.+)? from PeriodIndex\\(freq=M\\)' @@ -780,12 +731,6 @@ def test_pi_add_iadd_timedeltalike_freq_mismatch_monthly(self, rng + other with tm.assert_raises_regex(period.IncompatibleFrequency, msg): rng += other - - def test_pi_sub_isub_timedeltalike_freq_mismatch_monthly(self, - mismatched_freq): - other = mismatched_freq - rng = pd.period_range('2014-01', '2016-12', freq='M') - msg = 'Input has different freq(=.+)? from PeriodIndex\\(freq=M\\)' with tm.assert_raises_regex(period.IncompatibleFrequency, msg): rng - other with tm.assert_raises_regex(period.IncompatibleFrequency, msg): @@ -842,11 +787,7 @@ class TestPeriodIndexSeriesMethods(object): def _check(self, values, func, expected): idx = pd.PeriodIndex(values) result = func(idx) - if isinstance(expected, pd.Index): - tm.assert_index_equal(result, expected) - else: - # comp op results in bool - tm.assert_numpy_array_equal(result, expected) + tm.assert_equal(result, expected) ser = pd.Series(values) result = func(ser) @@ -874,35 +815,34 @@ def test_pi_ops(self): tm.assert_index_equal(result, exp) @pytest.mark.parametrize('ng', ["str", 1.5]) - def test_pi_ops_errors(self, ng): + def test_pi_ops_errors(self, ng, box): idx = PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04'], freq='M', name='idx') - ser = pd.Series(idx) + obj = tm.box_expected(idx, box) msg = r"unsupported operand type\(s\)" - for obj in [idx, ser]: - with tm.assert_raises_regex(TypeError, msg): - obj + ng + with tm.assert_raises_regex(TypeError, msg): + obj + ng - with pytest.raises(TypeError): - # error message differs between PY2 and 3 - ng + obj + with pytest.raises(TypeError): + # error message differs between PY2 and 3 + ng + obj - with tm.assert_raises_regex(TypeError, msg): - obj - ng + with tm.assert_raises_regex(TypeError, msg): + obj - ng - with pytest.raises(TypeError): - np.add(obj, ng) + with pytest.raises(TypeError): + np.add(obj, ng) - with pytest.raises(TypeError): - np.add(ng, obj) + with pytest.raises(TypeError): + np.add(ng, obj) - with pytest.raises(TypeError): - np.subtract(obj, ng) + with pytest.raises(TypeError): + np.subtract(obj, ng) - with pytest.raises(TypeError): - np.subtract(ng, obj) + with pytest.raises(TypeError): + np.subtract(ng, obj) def test_pi_ops_nat(self): idx = PeriodIndex(['2011-01', '2011-02', 'NaT', '2011-04'], diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 14a55785c243b..56bef2fee2b41 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -45,32 +45,35 @@ def test_tdi_cmp_str_invalid(self): with pytest.raises(TypeError): left != right - def test_comp_nat(self): + @pytest.mark.parametrize('dtype', [None, object]) + def test_comp_nat(self, dtype): left = pd.TimedeltaIndex([pd.Timedelta('1 days'), pd.NaT, pd.Timedelta('3 days')]) right = pd.TimedeltaIndex([pd.NaT, pd.NaT, pd.Timedelta('3 days')]) - for lhs, rhs in [(left, right), - (left.astype(object), right.astype(object))]: - result = rhs == lhs - expected = np.array([False, False, True]) - tm.assert_numpy_array_equal(result, expected) + lhs, rhs = left, right + if dtype is object: + lhs, rhs = left.astype(object), right.astype(object) - result = rhs != lhs - expected = np.array([True, True, False]) - tm.assert_numpy_array_equal(result, expected) + result = rhs == lhs + expected = np.array([False, False, True]) + tm.assert_numpy_array_equal(result, expected) - expected = np.array([False, False, False]) - tm.assert_numpy_array_equal(lhs == pd.NaT, expected) - tm.assert_numpy_array_equal(pd.NaT == rhs, expected) + result = rhs != lhs + expected = np.array([True, True, False]) + tm.assert_numpy_array_equal(result, expected) + + expected = np.array([False, False, False]) + tm.assert_numpy_array_equal(lhs == pd.NaT, expected) + tm.assert_numpy_array_equal(pd.NaT == rhs, expected) - expected = np.array([True, True, True]) - tm.assert_numpy_array_equal(lhs != pd.NaT, expected) - tm.assert_numpy_array_equal(pd.NaT != lhs, expected) + expected = np.array([True, True, True]) + tm.assert_numpy_array_equal(lhs != pd.NaT, expected) + tm.assert_numpy_array_equal(pd.NaT != lhs, expected) - expected = np.array([False, False, False]) - tm.assert_numpy_array_equal(lhs < pd.NaT, expected) - tm.assert_numpy_array_equal(pd.NaT > lhs, expected) + expected = np.array([False, False, False]) + tm.assert_numpy_array_equal(lhs < pd.NaT, expected) + tm.assert_numpy_array_equal(pd.NaT > lhs, expected) def test_comparisons_nat(self): tdidx1 = pd.TimedeltaIndex(['1 day', pd.NaT, '1 day 00:00:01', pd.NaT, @@ -425,14 +428,6 @@ def test_td64arr_add_timestamp(self, box): result = idx + Timestamp('2011-01-01') tm.assert_equal(result, expected) - def test_td64_radd_timestamp(self, box): - idx = TimedeltaIndex(['1 day', '2 day']) - expected = DatetimeIndex(['2011-01-02', '2011-01-03']) - - idx = tm.box_expected(idx, box) - expected = tm.box_expected(expected, box) - - # TODO: parametrize over scalar datetime types? result = Timestamp('2011-01-01') + idx tm.assert_equal(result, expected) @@ -500,26 +495,16 @@ def test_tdi_add_dt64_array(self, box_df_broadcast_failure): def test_td64arr_add_int_series_invalid(self, box, tdser): tdser = tm.box_expected(tdser, box) err = TypeError if box is not pd.Index else NullFrequencyError - with pytest.raises(err): - tdser + Series([2, 3, 4]) + int_ser = Series([2, 3, 4]) - def test_td64arr_radd_int_series_invalid(self, box, tdser): - tdser = tm.box_expected(tdser, box) - err = TypeError if box is not pd.Index else NullFrequencyError with pytest.raises(err): - Series([2, 3, 4]) + tdser - - def test_td64arr_sub_int_series_invalid(self, box, tdser): - tdser = tm.box_expected(tdser, box) - err = TypeError if box is not pd.Index else NullFrequencyError + tdser + int_ser with pytest.raises(err): - tdser - Series([2, 3, 4]) - - def test_td64arr_rsub_int_series_invalid(self, box, tdser): - tdser = tm.box_expected(tdser, box) - err = TypeError if box is not pd.Index else NullFrequencyError + int_ser + tdser + with pytest.raises(err): + tdser - int_ser with pytest.raises(err): - Series([2, 3, 4]) - tdser + int_ser - tdser def test_td64arr_add_intlike(self, box_df_broadcast_failure): # GH#19123 diff --git a/pandas/util/testing.py b/pandas/util/testing.py index b5ec0912c5c26..4327ff42b6044 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1563,6 +1563,8 @@ def box_expected(expected, box_cls): expected = pd.Series(expected) elif box_cls is pd.DataFrame: expected = pd.Series(expected).to_frame() + elif box_cls is np.ndarray: + expected = np.array(expected) else: raise NotImplementedError(box_cls) return expected
This is likely to be a sisyphean task...
https://api.github.com/repos/pandas-dev/pandas/pulls/23240
2018-10-19T16:42:22Z
2018-10-24T12:28:40Z
2018-10-24T12:28:40Z
2018-10-24T16:09:16Z
ENH/TST/DOC: set infer_nrows for read_fwf (GH15138)
diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index 48a3bfdab62c9..0e38396d156e1 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -286,6 +286,7 @@ Other Enhancements - New attribute :attr:`__git_version__` will return git commit sha of current build (:issue:`21295`). - Compatibility with Matplotlib 3.0 (:issue:`22790`). - Added :meth:`Interval.overlaps`, :meth:`IntervalArray.overlaps`, and :meth:`IntervalIndex.overlaps` for determining overlaps between interval-like objects (:issue:`21998`) +- :func:`read_fwf` now accepts keyword `infer_nrows` (:issue:`15138`). - :func:`~DataFrame.to_parquet` now supports writing a ``DataFrame`` as a directory of parquet files partitioned by a subset of the columns when ``engine = 'pyarrow'`` (:issue:`23283`) - :meth:`Timestamp.tz_localize`, :meth:`DatetimeIndex.tz_localize`, and :meth:`Series.tz_localize` have gained the ``nonexistent`` argument for alternative handling of nonexistent times. See :ref:`timeseries.timezone_nonexistent` (:issue:`8917`) - :meth:`Index.difference` now has an optional ``sort`` parameter to specify whether the results should be sorted if possible (:issue:`17839`) diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index acb9bca2545c0..4bbd69cb5c8ad 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -501,6 +501,7 @@ def _read(filepath_or_buffer, kwds): _fwf_defaults = { 'colspecs': 'infer', + 'infer_nrows': 100, 'widths': None, } @@ -718,8 +719,8 @@ def parser_f(filepath_or_buffer, )(read_table) -def read_fwf(filepath_or_buffer, colspecs='infer', - widths=None, **kwds): +def read_fwf(filepath_or_buffer, colspecs='infer', widths=None, + infer_nrows=100, **kwds): r""" Read a table of fixed-width formatted lines into DataFrame. @@ -752,6 +753,11 @@ def read_fwf(filepath_or_buffer, colspecs='infer', widths : list of int, optional A list of field widths which can be used instead of 'colspecs' if the intervals are contiguous. + infer_nrows : int, default 100 + The number of rows to consider when letting the parser determine the + `colspecs`. + + .. versionadded:: 0.24.0 **kwds : optional Optional keyword arguments can be passed to ``TextFileReader``. @@ -786,6 +792,7 @@ def read_fwf(filepath_or_buffer, colspecs='infer', col += w kwds['colspecs'] = colspecs + kwds['infer_nrows'] = infer_nrows kwds['engine'] = 'python-fwf' return _read(filepath_or_buffer, kwds) @@ -3442,13 +3449,15 @@ class FixedWidthReader(BaseIterator): A reader of fixed-width lines. """ - def __init__(self, f, colspecs, delimiter, comment, skiprows=None): + def __init__(self, f, colspecs, delimiter, comment, skiprows=None, + infer_nrows=100): self.f = f self.buffer = None self.delimiter = '\r\n' + delimiter if delimiter else '\n\r\t ' self.comment = comment if colspecs == 'infer': - self.colspecs = self.detect_colspecs(skiprows=skiprows) + self.colspecs = self.detect_colspecs(infer_nrows=infer_nrows, + skiprows=skiprows) else: self.colspecs = colspecs @@ -3464,19 +3473,20 @@ def __init__(self, f, colspecs, delimiter, comment, skiprows=None): raise TypeError('Each column specification must be ' '2 element tuple or list of integers') - def get_rows(self, n, skiprows=None): + def get_rows(self, infer_nrows, skiprows=None): """ Read rows from self.f, skipping as specified. - We distinguish buffer_rows (the first <= n lines) - from the rows returned to detect_colspecs because - it's simpler to leave the other locations with - skiprows logic alone than to modify them to deal - with the fact we skipped some rows here as well. + We distinguish buffer_rows (the first <= infer_nrows + lines) from the rows returned to detect_colspecs + because it's simpler to leave the other locations + with skiprows logic alone than to modify them to + deal with the fact we skipped some rows here as + well. Parameters ---------- - n : int + infer_nrows : int Number of rows to read from self.f, not counting rows that are skipped. skiprows: set, optional @@ -3496,16 +3506,16 @@ def get_rows(self, n, skiprows=None): if i not in skiprows: detect_rows.append(row) buffer_rows.append(row) - if len(detect_rows) >= n: + if len(detect_rows) >= infer_nrows: break self.buffer = iter(buffer_rows) return detect_rows - def detect_colspecs(self, n=100, skiprows=None): + def detect_colspecs(self, infer_nrows=100, skiprows=None): # Regex escape the delimiters delimiters = ''.join(r'\%s' % x for x in self.delimiter) pattern = re.compile('([^%s]+)' % delimiters) - rows = self.get_rows(n, skiprows) + rows = self.get_rows(infer_nrows, skiprows) if not rows: raise EmptyDataError("No rows from which to infer column width") max_len = max(map(len, rows)) @@ -3544,8 +3554,10 @@ class FixedWidthFieldParser(PythonParser): def __init__(self, f, **kwds): # Support iterators, convert to a list. self.colspecs = kwds.pop('colspecs') + self.infer_nrows = kwds.pop('infer_nrows') PythonParser.__init__(self, f, **kwds) def _make_reader(self, f): self.data = FixedWidthReader(f, self.colspecs, self.delimiter, - self.comment, self.skiprows) + self.comment, self.skiprows, + self.infer_nrows) diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py index bb64a85590c8b..1c89e41df8df9 100644 --- a/pandas/tests/io/parser/test_read_fwf.py +++ b/pandas/tests/io/parser/test_read_fwf.py @@ -140,6 +140,22 @@ def test_fwf_colspecs_None(self): expected = DataFrame([[123456, 456], [456789, 789]]) tm.assert_frame_equal(result, expected) + def test_fwf_colspecs_infer_nrows(self): + # GH 15138 + data = """\ + 1 2 +123 98 +""" + # infer_nrows == 1 should have colspec == [(2, 3), (5, 6)] + df = read_fwf(StringIO(data), header=None, infer_nrows=1) + expected = pd.DataFrame([[1, 2], [3, 8]]) + tm.assert_frame_equal(df, expected) + + # test for infer_nrows > number of rows + df = read_fwf(StringIO(data), header=None, infer_nrows=10) + expected = pd.DataFrame([[1, 2], [123, 98]]) + tm.assert_frame_equal(df, expected) + def test_fwf_regression(self): # GH 3594 # turns out 'T060' is parsable as a datetime slice!
- [ ] closes #15138 - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry `read_fwf` can infer the widths of columns of a dataset from a file or buffer, but if the widths change after the first 100 rows, then the default behavior fails to capture the data correctly. This PR addresses that issue by allowing the user to set a parameter `infer_nrows` that is passed down to the appropriate function. The associated test ensures that `colspecs` can be determined from the first row, thereby missing data from the subsequent rows and verifying the expected behavior.
https://api.github.com/repos/pandas-dev/pandas/pulls/23238
2018-10-19T14:07:58Z
2018-11-26T00:35:45Z
2018-11-26T00:35:45Z
2018-11-26T00:36:06Z
BUG GH23224 Allow integer_array to be initialized with all None
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 52762514d00c2..17e92c3976e2c 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -173,8 +173,11 @@ def coerce_to_array(values, dtype, mask=None, copy=False): values = np.array(values, copy=copy) if is_object_dtype(values): inferred_type = lib.infer_dtype(values) - if inferred_type not in ['floating', 'integer', - 'mixed-integer', 'mixed-integer-float']: + if inferred_type is 'mixed' and isna(values).any(): + values = np.empty(len(values)) + values.fill(np.nan) + elif inferred_type not in ['floating', 'integer', + 'mixed-integer', 'mixed-integer-float']: raise TypeError("{} cannot be converted to an IntegerDtype".format( values.dtype)) diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py index 66d2baac8c91c..e6dae0ffaec28 100644 --- a/pandas/tests/arrays/test_integer.py +++ b/pandas/tests/arrays/test_integer.py @@ -527,9 +527,9 @@ def test_integer_array_constructor(): @pytest.mark.parametrize('a, b', [ ([1, None], [1, np.nan]), - pytest.param([None], [np.nan], - marks=pytest.mark.xfail(reason='GH-23224', - strict=True)), + ([None], [np.nan]), + ([None, np.nan], [np.nan, np.nan]), + ([np.nan, np.nan], [np.nan, np.nan]), ]) def test_integer_array_constructor_none_is_nan(a, b): result = integer_array(a) @@ -559,7 +559,8 @@ def test_integer_array_constructor_copy(): 1, 1.0, pd.date_range('20130101', periods=2), - np.array(['foo'])]) + np.array(['foo']), + [[1, 2], [3, 4]]]) def test_to_integer_array_error(values): # error in converting existing arrays to IntegerArrays with pytest.raises(TypeError):
- [X] closes #23224 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Allows for initialization of `integer_array` with `[None]`, lists of `None`, and lists made of only `None` and other na types
https://api.github.com/repos/pandas-dev/pandas/pulls/23237
2018-10-19T07:44:37Z
2018-10-23T03:06:35Z
2018-10-23T03:06:35Z
2018-10-23T09:20:34Z
PERF: speed up CategoricalIndex.get_loc
diff --git a/asv_bench/benchmarks/indexing_engines.py b/asv_bench/benchmarks/indexing_engines.py index 1e9283c7fb92b..f3d063ee31bc8 100644 --- a/asv_bench/benchmarks/indexing_engines.py +++ b/asv_bench/benchmarks/indexing_engines.py @@ -1,18 +1,30 @@ import numpy as np -from pandas._libs.index import (Int64Engine, UInt64Engine, Float64Engine, - ObjectEngine) +from pandas._libs import index as libindex + + +def _get_numeric_engines(): + engine_names = [ + ('Int64Engine', np.int64), ('Int32Engine', np.int32), + ('Int16Engine', np.int16), ('Int8Engine', np.int8), + ('UInt64Engine', np.uint64), ('UInt32Engine', np.uint32), + ('UInt16engine', np.uint16), ('UInt8Engine', np.uint8), + ('Float64Engine', np.float64), ('Float32Engine', np.float32), + ] + return [(getattr(libindex, engine_name), dtype) + for engine_name, dtype in engine_names + if hasattr(libindex, engine_name)] class NumericEngineIndexing(object): - params = [[Int64Engine, UInt64Engine, Float64Engine], - [np.int64, np.uint64, np.float64], + params = [_get_numeric_engines(), ['monotonic_incr', 'monotonic_decr', 'non_monotonic'], ] - param_names = ['engine', 'dtype', 'index_type'] + param_names = ['engine_and_dtype', 'index_type'] - def setup(self, engine, dtype, index_type): + def setup(self, engine_and_dtype, index_type): + engine, dtype = engine_and_dtype N = 10**5 values = list([1] * N + [2] * N + [3] * N) arr = { @@ -26,7 +38,7 @@ def setup(self, engine, dtype, index_type): # code belows avoids populating the mapping etc. while timing. self.data.get_loc(2) - def time_get_loc(self, engine, dtype, index_type): + def time_get_loc(self, engine_and_dtype, index_type): self.data.get_loc(2) @@ -44,7 +56,7 @@ def setup(self, index_type): 'non_monotonic': np.array(list('abc') * N, dtype=object), }[index_type] - self.data = ObjectEngine(lambda: arr, len(arr)) + self.data = libindex.ObjectEngine(lambda: arr, len(arr)) # code belows avoids populating the mapping etc. while timing. self.data.get_loc('b') diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 7a10e8d1073d0..245dd639b5305 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -935,9 +935,11 @@ Removal of prior version deprecations/changes Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ -- Very large improvement in performance of slicing when the index is a :class:`CategoricalIndex`, - both when indexing by label (using .loc) and position(.iloc). - Likewise, slicing a ``CategoricalIndex`` itself (i.e. ``ci[100:200]``) shows similar speed improvements (:issue:`21659`) +- Slicing Series and Dataframes with an monotonically increasing :class:`CategoricalIndex` + is now very fast and has speed comparable to slicing with an ``Int64Index``. + The speed increase is both when indexing by label (using .loc) and position(.iloc) (:issue:`20395`) + Slicing a monotonically increasing :class:`CategoricalIndex` itself (i.e. ``ci[1000:2000]``) + shows similar speed improvements as above (:issue:`21659`) - Improved performance of :func:`Series.describe` in case of numeric dtpyes (:issue:`21274`) - Improved performance of :func:`pandas.core.groupby.GroupBy.rank` when dealing with tied rankings (:issue:`21237`) - Improved performance of :func:`DataFrame.set_index` with columns consisting of :class:`Period` objects (:issue:`21582`, :issue:`21606`) diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index d2914dc8ac751..3ba4c2375b4e8 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -10,7 +10,8 @@ from libc.math cimport fabs, sqrt import numpy as np cimport numpy as cnp from numpy cimport (ndarray, - NPY_INT64, NPY_UINT64, NPY_INT32, NPY_INT16, NPY_INT8, + NPY_INT64, NPY_INT32, NPY_INT16, NPY_INT8, + NPY_UINT64, NPY_UINT32, NPY_UINT16, NPY_UINT8, NPY_FLOAT32, NPY_FLOAT64, NPY_OBJECT, int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, @@ -359,9 +360,13 @@ ctypedef fused algos_t: float64_t float32_t object - int32_t int64_t + int32_t + int16_t + int8_t uint64_t + uint32_t + uint16_t uint8_t @@ -459,7 +464,12 @@ pad_float32 = pad["float32_t"] pad_object = pad["object"] pad_int64 = pad["int64_t"] pad_int32 = pad["int32_t"] +pad_int16 = pad["int16_t"] +pad_int8 = pad["int8_t"] pad_uint64 = pad["uint64_t"] +pad_uint32 = pad["uint32_t"] +pad_uint16 = pad["uint16_t"] +pad_uint8 = pad["uint8_t"] pad_bool = pad["uint8_t"] @@ -653,7 +663,12 @@ backfill_float32 = backfill["float32_t"] backfill_object = backfill["object"] backfill_int64 = backfill["int64_t"] backfill_int32 = backfill["int32_t"] +backfill_int16 = backfill["int16_t"] +backfill_int8 = backfill["int8_t"] backfill_uint64 = backfill["uint64_t"] +backfill_uint32 = backfill["uint32_t"] +backfill_uint16 = backfill["uint16_t"] +backfill_uint8 = backfill["uint8_t"] backfill_bool = backfill["uint8_t"] @@ -866,7 +881,12 @@ is_monotonic_float32 = is_monotonic["float32_t"] is_monotonic_object = is_monotonic["object"] is_monotonic_int64 = is_monotonic["int64_t"] is_monotonic_int32 = is_monotonic["int32_t"] +is_monotonic_int16 = is_monotonic["int16_t"] +is_monotonic_int8 = is_monotonic["int8_t"] is_monotonic_uint64 = is_monotonic["uint64_t"] +is_monotonic_uint32 = is_monotonic["uint32_t"] +is_monotonic_uint16 = is_monotonic["uint16_t"] +is_monotonic_uint8 = is_monotonic["uint8_t"] is_monotonic_bool = is_monotonic["uint8_t"] diff --git a/pandas/_libs/algos_common_helper.pxi.in b/pandas/_libs/algos_common_helper.pxi.in index b39b5eaced8fd..518664d70cf06 100644 --- a/pandas/_libs/algos_common_helper.pxi.in +++ b/pandas/_libs/algos_common_helper.pxi.in @@ -133,6 +133,9 @@ dtypes = [('float64', 'FLOAT64', 'float64'), ('int16', 'INT16', 'int16'), ('int32', 'INT32', 'int32'), ('int64', 'INT64', 'int64'), + ('uint8', 'UINT8', 'uint8'), + ('uint16', 'UINT16', 'uint16'), + ('uint32', 'UINT32', 'uint32'), ('uint64', 'UINT64', 'uint64'), # ('platform_int', 'INT', 'int_'), # ('object', 'OBJECT', 'object_'), diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 3f76915655f58..d418ac63a4ac8 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -5,8 +5,10 @@ import cython import numpy as np cimport numpy as cnp -from numpy cimport (ndarray, float64_t, int32_t, - int64_t, uint8_t, uint64_t, intp_t, +from numpy cimport (ndarray, intp_t, + float64_t, float32_t, + int64_t, int32_t, int16_t, int8_t, + uint64_t, uint32_t, uint16_t, uint8_t, # Note: NPY_DATETIME, NPY_TIMEDELTA are only available # for cimport in cython>=0.27.3 NPY_DATETIME, NPY_TIMEDELTA) diff --git a/pandas/_libs/index_class_helper.pxi.in b/pandas/_libs/index_class_helper.pxi.in index 4ea35da0626f3..c19812efaaa35 100644 --- a/pandas/_libs/index_class_helper.pxi.in +++ b/pandas/_libs/index_class_helper.pxi.in @@ -10,14 +10,22 @@ WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in {{py: -# name, dtype, ctype -dtypes = [('Float64', 'float64', 'float64_t'), - ('UInt64', 'uint64', 'uint64_t'), - ('Int64', 'int64', 'int64_t'), - ('Object', 'object', 'object')] +# name, dtype, ctype, hashtable_name, hashtable_dtype +dtypes = [('Float64', 'float64', 'float64_t', 'Float64', 'float64'), + ('Float32', 'float32', 'float32_t', 'Float64', 'float64'), + ('Int64', 'int64', 'int64_t', 'Int64', 'int64'), + ('Int32', 'int32', 'int32_t', 'Int64', 'int64'), + ('Int16', 'int16', 'int16_t', 'Int64', 'int64'), + ('Int8', 'int8', 'int8_t', 'Int64', 'int64'), + ('UInt64', 'uint64', 'uint64_t', 'UInt64', 'uint64'), + ('UInt32', 'uint32', 'uint32_t', 'UInt64', 'uint64'), + ('UInt16', 'uint16', 'uint16_t', 'UInt64', 'uint64'), + ('UInt8', 'uint8', 'uint8_t', 'UInt64', 'uint64'), + ('Object', 'object', 'object', 'PyObject', 'object'), + ] }} -{{for name, dtype, ctype in dtypes}} +{{for name, dtype, ctype, hashtable_name, hashtable_dtype in dtypes}} cdef class {{name}}Engine(IndexEngine): @@ -34,13 +42,9 @@ cdef class {{name}}Engine(IndexEngine): other, limit=limit) cdef _make_hash_table(self, n): - {{if name == 'Object'}} - return _hash.PyObjectHashTable(n) - {{else}} - return _hash.{{name}}HashTable(n) - {{endif}} + return _hash.{{hashtable_name}}HashTable(n) - {{if name != 'Float64' and name != 'Object'}} + {{if name not in {'Float64', 'Float32', 'Object'} }} cdef _check_type(self, object val): hash(val) if util.is_bool_object(val): @@ -50,6 +54,11 @@ cdef class {{name}}Engine(IndexEngine): {{endif}} {{if name != 'Object'}} + cpdef _call_map_locations(self, values): + # self.mapping is of type {{hashtable_name}}HashTable, + # so convert dtype of values + self.mapping.map_locations(algos.ensure_{{hashtable_dtype}}(values)) + cdef _get_index_values(self): return algos.ensure_{{dtype}}(self.vgetter()) @@ -60,7 +69,7 @@ cdef class {{name}}Engine(IndexEngine): ndarray[{{ctype}}] values int count = 0 - {{if name != 'Float64'}} + {{if name not in {'Float64', 'Float32'} }} if not util.is_integer_object(val): raise KeyError(val) {{endif}} diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index e4250ae790553..278e395d65014 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -84,7 +84,17 @@ class CategoricalIndex(Index, accessor.PandasDelegate): """ _typ = 'categoricalindex' - _engine_type = libindex.Int64Engine + + @property + def _engine_type(self): + # self.codes can have dtype int8, int16, int32 or int64, so we need + # to return the corresponding engine type (libindex.Int8Engine, etc.). + return {np.int8: libindex.Int8Engine, + np.int16: libindex.Int16Engine, + np.int32: libindex.Int32Engine, + np.int64: libindex.Int64Engine, + }[self.codes.dtype.type] + _attributes = ['name'] def __new__(cls, data=None, categories=None, ordered=None, dtype=None, @@ -382,7 +392,7 @@ def argsort(self, *args, **kwargs): def _engine(self): # we are going to look things up with the codes themselves - return self._engine_type(lambda: self.codes.astype('i8'), len(self)) + return self._engine_type(lambda: self.codes, len(self)) # introspection @cache_readonly @@ -450,6 +460,7 @@ def get_loc(self, key, method=None): array([False, True, False, True], dtype=bool) """ code = self.categories.get_loc(key) + code = self.codes.dtype.type(code) try: return self._engine.get_loc(code) except KeyError: diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py index 99058f883a392..d89baa41d33fe 100644 --- a/pandas/tests/indexes/test_category.py +++ b/pandas/tests/indexes/test_category.py @@ -1,16 +1,16 @@ # -*- coding: utf-8 -*- import pytest +import numpy as np import pandas.util.testing as tm from pandas.core.indexes.api import Index, CategoricalIndex from pandas.core.dtypes.dtypes import CategoricalDtype +from pandas._libs import index as libindex from .common import Base from pandas.compat import range, PY3 -import numpy as np - from pandas import Categorical, IntervalIndex, compat from pandas.util.testing import assert_almost_equal import pandas.core.config as cf @@ -1117,3 +1117,23 @@ def test_take_invalid_kwargs(self): msg = "the 'mode' parameter is not supported" tm.assert_raises_regex(ValueError, msg, idx.take, indices, mode='clip') + + @pytest.mark.parametrize('dtype, engine_type', [ + (np.int8, libindex.Int8Engine), + (np.int16, libindex.Int16Engine), + (np.int32, libindex.Int32Engine), + (np.int64, libindex.Int64Engine), + ]) + def test_engine_type(self, dtype, engine_type): + if dtype != np.int64: + # num. of uniques required to push CategoricalIndex.codes to a + # dtype (128 categories required for .codes dtype to be int16 etc.) + num_uniques = {np.int8: 1, np.int16: 128, np.int32: 32768}[dtype] + ci = pd.CategoricalIndex(range(num_uniques)) + else: + # having 2**32 - 2**31 categories would be very memory-intensive, + # so we cheat a bit with the dtype + ci = pd.CategoricalIndex(range(32768)) # == 2**16 - 2**(16 - 1) + ci.values._codes = ci.values._codes.astype('int64') + assert np.issubdtype(ci.codes.dtype, dtype) + assert isinstance(ci._engine, engine_type) diff --git a/pandas/tests/indexing/conftest.py b/pandas/tests/indexing/conftest.py new file mode 100644 index 0000000000000..be1cf4800a2ef --- /dev/null +++ b/pandas/tests/indexing/conftest.py @@ -0,0 +1,20 @@ +import numpy as np +import pytest + +from pandas._libs import index as libindex + + +@pytest.fixture(params=[ + (libindex.Int64Engine, np.int64), + (libindex.Int32Engine, np.int32), + (libindex.Int16Engine, np.int16), + (libindex.Int8Engine, np.int8), + (libindex.UInt64Engine, np.uint64), + (libindex.UInt32Engine, np.uint32), + (libindex.UInt16Engine, np.uint16), + (libindex.UInt8Engine, np.uint8), + (libindex.Float64Engine, np.float64), + (libindex.Float32Engine, np.float32), +], ids=lambda x: x[0].__name__) +def numeric_indexing_engine_type_and_dtype(request): + return request.param diff --git a/pandas/tests/indexing/test_indexing_engines.py b/pandas/tests/indexing/test_indexing_engines.py new file mode 100644 index 0000000000000..410eba99948ce --- /dev/null +++ b/pandas/tests/indexing/test_indexing_engines.py @@ -0,0 +1,168 @@ +import numpy as np + +import pandas.util.testing as tm +from pandas import compat +from pandas._libs import algos as libalgos, index as libindex + + +class TestNumericEngine(object): + def test_is_monotonic(self, numeric_indexing_engine_type_and_dtype): + engine_type, dtype = numeric_indexing_engine_type_and_dtype + num = 1000 + arr = np.array([1] * num + [2] * num + [3] * num, dtype=dtype) + + # monotonic increasing + engine = engine_type(lambda: arr, len(arr)) + assert engine.is_monotonic_increasing is True + assert engine.is_monotonic_decreasing is False + + # monotonic decreasing + engine = engine_type(lambda: arr[::-1], len(arr)) + assert engine.is_monotonic_increasing is False + assert engine.is_monotonic_decreasing is True + + # neither monotonic increasing or decreasing + arr = np.array([1] * num + [2] * num + [1] * num, dtype=dtype) + engine = engine_type(lambda: arr[::-1], len(arr)) + assert engine.is_monotonic_increasing is False + assert engine.is_monotonic_decreasing is False + + def test_is_unique(self, numeric_indexing_engine_type_and_dtype): + engine_type, dtype = numeric_indexing_engine_type_and_dtype + + # unique + arr = np.array([1, 3, 2], dtype=dtype) + engine = engine_type(lambda: arr, len(arr)) + assert engine.is_unique is True + + # not unique + arr = np.array([1, 2, 1], dtype=dtype) + engine = engine_type(lambda: arr, len(arr)) + assert engine.is_unique is False + + def test_get_loc(self, numeric_indexing_engine_type_and_dtype): + engine_type, dtype = numeric_indexing_engine_type_and_dtype + + # unique + arr = np.array([1, 2, 3], dtype=dtype) + engine = engine_type(lambda: arr, len(arr)) + assert engine.get_loc(2) == 1 + + # monotonic + num = 1000 + arr = np.array([1] * num + [2] * num + [3] * num, dtype=dtype) + engine = engine_type(lambda: arr, len(arr)) + assert engine.get_loc(2) == slice(1000, 2000) + + # not monotonic + arr = np.array([1, 2, 3] * num, dtype=dtype) + engine = engine_type(lambda: arr, len(arr)) + expected = np.array([False, True, False] * num, dtype=bool) + result = engine.get_loc(2) + assert (result == expected).all() + + def test_get_backfill_indexer( + self, numeric_indexing_engine_type_and_dtype): + engine_type, dtype = numeric_indexing_engine_type_and_dtype + + arr = np.array([1, 5, 10], dtype=dtype) + engine = engine_type(lambda: arr, len(arr)) + + new = np.array(compat.range(12), dtype=dtype) + result = engine.get_backfill_indexer(new) + + expected = libalgos.backfill(arr, new) + tm.assert_numpy_array_equal(result, expected) + + def test_get_pad_indexer( + self, numeric_indexing_engine_type_and_dtype): + engine_type, dtype = numeric_indexing_engine_type_and_dtype + + arr = np.array([1, 5, 10], dtype=dtype) + engine = engine_type(lambda: arr, len(arr)) + + new = np.array(compat.range(12), dtype=dtype) + result = engine.get_pad_indexer(new) + + expected = libalgos.pad(arr, new) + tm.assert_numpy_array_equal(result, expected) + + +class TestObjectEngine(object): + engine_type = libindex.ObjectEngine + dtype = np.object_ + values = list('abc') + + def test_is_monotonic(self): + + num = 1000 + arr = np.array(['a'] * num + ['a'] * num + ['c'] * num, + dtype=self.dtype) + + # monotonic increasing + engine = self.engine_type(lambda: arr, len(arr)) + assert engine.is_monotonic_increasing is True + assert engine.is_monotonic_decreasing is False + + # monotonic decreasing + engine = self.engine_type(lambda: arr[::-1], len(arr)) + assert engine.is_monotonic_increasing is False + assert engine.is_monotonic_decreasing is True + + # neither monotonic increasing or decreasing + arr = np.array(['a'] * num + ['b'] * num + ['a'] * num, + dtype=self.dtype) + engine = self.engine_type(lambda: arr[::-1], len(arr)) + assert engine.is_monotonic_increasing is False + assert engine.is_monotonic_decreasing is False + + def test_is_unique(self): + # unique + arr = np.array(self.values, dtype=self.dtype) + engine = self.engine_type(lambda: arr, len(arr)) + assert engine.is_unique is True + + # not unique + arr = np.array(['a', 'b', 'a'], dtype=self.dtype) + engine = self.engine_type(lambda: arr, len(arr)) + assert engine.is_unique is False + + def test_get_loc(self): + # unique + arr = np.array(self.values, dtype=self.dtype) + engine = self.engine_type(lambda: arr, len(arr)) + assert engine.get_loc('b') == 1 + + # monotonic + num = 1000 + arr = np.array(['a'] * num + ['b'] * num + ['c'] * num, + dtype=self.dtype) + engine = self.engine_type(lambda: arr, len(arr)) + assert engine.get_loc('b') == slice(1000, 2000) + + # not monotonic + arr = np.array(self.values * num, dtype=self.dtype) + engine = self.engine_type(lambda: arr, len(arr)) + expected = np.array([False, True, False] * num, dtype=bool) + result = engine.get_loc('b') + assert (result == expected).all() + + def test_get_backfill_indexer(self): + arr = np.array(['a', 'e', 'j'], dtype=self.dtype) + engine = self.engine_type(lambda: arr, len(arr)) + + new = np.array(list('abcdefghij'), dtype=self.dtype) + result = engine.get_backfill_indexer(new) + + expected = libalgos.backfill_object(arr, new) + tm.assert_numpy_array_equal(result, expected) + + def test_get_pad_indexer(self): + arr = np.array(['a', 'e', 'j'], dtype=self.dtype) + engine = self.engine_type(lambda: arr, len(arr)) + + new = np.array(list('abcdefghij'), dtype=self.dtype) + result = engine.get_pad_indexer(new) + + expected = libalgos.pad_object(arr, new) + tm.assert_numpy_array_equal(result, expected)
- [x] closes #20395 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This is the the final puzzle for #20395 and speeds up ``CategoricalIndex.get_loc`` for monotonic increasing indexes. This PR supersedes #21699, so #21699 should be closed. The problem with the current get_loc implementation is that ``CategoricalIndex._engine`` constantly recodes int8 arrays to int64 arrays: https://github.com/pandas-dev/pandas/blob/dc45fbafef172e357cb5decdeab22de67160f5b7/pandas/core/indexes/category.py#L365-L369 Notice the ``lambda: self.codes.astype('i8')`` part, which means that every time ``_engine.vgetter`` is called, an int64-array is created. This is expensive and we would ideally want to just use the original array dtype (int8, int16 or whatever) always and avoid this conversion. A complicating issue is that it is *not* enough to just avoid the int64 transformation, as ``array.searchsorted`` apparantly needs a dtype-compatible input or else it is *also* very slow: ```python >>> n = 1_000_000 >>> ci = pd.CategoricalIndex(list('a' * n + 'b' * n + 'c' * n)) >>> %timeit ci.codes.searchsorted(1) # search for left location of 'b' 7.38 ms # slow >>> code = np.int8(1) >>> %timeit ci.codes.searchsorted(code) 2.57 µs # fast ``` ### Solution As CategoricalIndex.codes may be int8, int16, etc, the solution must (1) have an indexing engine for each integer dtype and (2) have the code for the key be translated into the same dtype as the codes array before calling searchsorted. This PR does that, essentially. ### Performance improvement examples ```python >>> n = 100_000 >>> ci = pd.CategoricalIndex(list('a' * n + 'b' * n + 'c' * n)) >>> %timeit ci.get_loc('b') 2.05 ms # master 8.96 µs # this PR >>> n = 1_000_000 >>> ci = pd.CategoricalIndex(list('a' * n + 'b' * n + 'c' * n)) >>> %timeit ci.get_loc('b') 18.7 ms # master 9.09 µs # this PR ``` So we go from O(n) performance to O(1) performance. The indexing_engines.py ASV results: ``` [ 0.00%] ·· Building for conda-py3.6-Cython-matplotlib-numexpr-numpy-openpyxl-pytables-pytest-scipy-sqlalchemy-xlrd-xlsxwriter-xlwt [ 0.00%] ·· Benchmarking conda-py3.6-Cython-matplotlib-numexpr-numpy-openpyxl-pytables-pytest-scipy-sqlalchemy-xlrd-xlsxwriter-xlwt [ 50.00%] ··· Running indexing_engines.NumericEngineIndexing.time_get_loc 7.18±1μs;... [100.00%] ··· Running indexing_engines.ObjectEngineIndexing.time_get_loc 7.04±0.4μs;... ```
https://api.github.com/repos/pandas-dev/pandas/pulls/23235
2018-10-19T02:21:26Z
2018-10-26T01:11:55Z
2018-10-26T01:11:55Z
2018-10-26T01:50:41Z
CI: Quieter doctests
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 6494311d73290..aec74eb970322 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -122,22 +122,22 @@ fi if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then MSG='Doctests frame.py' ; echo $MSG - pytest --doctest-modules -v pandas/core/frame.py \ + pytest -q --doctest-modules pandas/core/frame.py \ -k"-axes -combine -itertuples -join -nlargest -nsmallest -nunique -pivot_table -quantile -query -reindex -reindex_axis -replace -round -set_index -stack -to_stata" RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Doctests series.py' ; echo $MSG - pytest --doctest-modules -v pandas/core/series.py \ + pytest -q --doctest-modules pandas/core/series.py \ -k"-nonzero -reindex -searchsorted -to_dict" RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Doctests generic.py' ; echo $MSG - pytest --doctest-modules -v pandas/core/generic.py \ + pytest -q --doctest-modules pandas/core/generic.py \ -k"-_set_axis_name -_xs -describe -droplevel -groupby -interpolate -pct_change -pipe -reindex -reindex_axis -resample -to_json -transpose -values -xs" RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Doctests top-level reshaping functions' ; echo $MSG - pytest --doctest-modules -v \ + pytest -q --doctest-modules \ pandas/core/reshape/concat.py \ pandas/core/reshape/pivot.py \ pandas/core/reshape/reshape.py \
ref https://github.com/pandas-dev/pandas/pull/23215#issuecomment-431127737 cc @datapythonista @jbrockmendel
https://api.github.com/repos/pandas-dev/pandas/pulls/23232
2018-10-18T19:50:52Z
2018-10-19T02:01:58Z
2018-10-19T02:01:58Z
2018-10-19T02:03:04Z
STYLE: Fix isort failure in range.py
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 00f17d5c91537..6494311d73290 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -16,7 +16,7 @@ echo "inside $0" [[ $LINT ]] || { echo "NOT Linting. To lint use: LINT=true $0 $1"; exit 0; } -[[ -z "$1" || "$1" == "lint" || "$1" == "patterns" || "$1" == "doctests" ]] || { echo "Unkown command $1. Usage: $0 [lint|patterns|doctests]"; exit 9999; } +[[ -z "$1" || "$1" == "lint" || "$1" == "patterns" || "$1" == "doctests" ]] || { echo "Unknown command $1. Usage: $0 [lint|patterns|doctests]"; exit 9999; } source activate pandas RET=0 diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 30a803c5636c4..2b2f9ca51ce12 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -1,7 +1,7 @@ import operator +import warnings from datetime import timedelta from sys import getsizeof -import warnings import numpy as np
https://travis-ci.org/pandas-dev/pandas/jobs/443300714#L2922
https://api.github.com/repos/pandas-dev/pandas/pulls/23231
2018-10-18T18:52:10Z
2018-10-18T20:41:48Z
2018-10-18T20:41:48Z
2018-10-19T00:55:04Z
CLN GH23204 remove "not" typo in assertion
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 1c602a0af1ec1..aa380d95e5f36 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -446,7 +446,7 @@ def _get_new_axes(self): new_axes[i] = self._get_comb_axis(i) else: if len(self.join_axes) != ndim - 1: - raise AssertionError("length of join_axes must not be equal " + raise AssertionError("length of join_axes must be equal " "to {length}".format(length=ndim - 1)) # ufff...
- [x] closes #23204 - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Remove an unwanted "not" in the assertion message. This is my first pandas PR! Let me know if there's anything else I need to do. Thanks!
https://api.github.com/repos/pandas-dev/pandas/pulls/23221
2018-10-18T13:23:04Z
2018-10-23T03:04:07Z
2018-10-23T03:04:07Z
2018-10-23T12:21:26Z
CLN: de-duplicate generate_range
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index a98b0b3bf35f9..72bc5c2209d04 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -595,9 +595,12 @@ def _time_shift(self, periods, freq=None): start = self[0] + periods * self.freq end = self[-1] + periods * self.freq - attribs = self._get_attributes_dict() + + # Note: in the DatetimeTZ case, _generate_range will infer the + # appropriate timezone from `start` and `end`, so tz does not need + # to be passed explicitly. return self._generate_range(start=start, end=end, periods=None, - **attribs) + freq=self.freq) @classmethod def _add_datetimelike_methods(cls): diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 16fa9ccb43b4d..1426b9690f4df 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -176,11 +176,13 @@ def _from_ordinals(cls, values, freq=None, **kwargs): @classmethod def _generate_range(cls, start, end, periods, freq, fields): + periods = dtl.validate_periods(periods) + if freq is not None: freq = Period._maybe_convert_freq(freq) field_count = len(fields) - if com.count_not_none(start, end) > 0: + if start is not None or end is not None: if field_count > 0: raise ValueError('Can either instantiate from fields ' 'or endpoints, but not both') diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 4904a90ab7b2b..eb7dabdc03b0b 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -126,8 +126,7 @@ def _simple_new(cls, values, freq=None, **kwargs): result._freq = freq return result - def __new__(cls, values, freq=None, start=None, end=None, periods=None, - closed=None): + def __new__(cls, values, freq=None): freq, freq_infer = dtl.maybe_infer_freq(freq) @@ -140,8 +139,7 @@ def __new__(cls, values, freq=None, start=None, end=None, periods=None, return result @classmethod - def _generate_range(cls, start, end, periods, freq, closed=None, **kwargs): - # **kwargs are for compat with TimedeltaIndex, which includes `name` + def _generate_range(cls, start, end, periods, freq, closed=None): periods = dtl.validate_periods(periods) if freq is None and any(x is None for x in [periods, start, end]): @@ -167,10 +165,9 @@ def _generate_range(cls, start, end, periods, freq, closed=None, **kwargs): if freq is not None: index = _generate_regular_range(start, end, periods, freq) - index = cls._simple_new(index, freq=freq, **kwargs) + index = cls._simple_new(index, freq=freq) else: index = np.linspace(start.value, end.value, periods).astype('i8') - # TODO: shouldn't we pass `name` here? (via **kwargs) index = cls._simple_new(index, freq=freq) if not left_closed: diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index d9152c50309eb..53f8d42f46d55 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -703,6 +703,12 @@ def astype(self, dtype, copy=True): raise TypeError(msg.format(name=type(self).__name__, dtype=dtype)) return super(DatetimeIndexOpsMixin, self).astype(dtype, copy=copy) + @Appender(DatetimeLikeArrayMixin._time_shift.__doc__) + def _time_shift(self, periods, freq=None): + result = DatetimeLikeArrayMixin._time_shift(self, periods, freq=freq) + result.name = self.name + return result + def _ensure_datetimelike_to_i8(other, to_utc=False): """ diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index e0219acc115b5..c9107d6509848 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -241,9 +241,11 @@ def __new__(cls, data=None, if data is None: # TODO: Remove this block and associated kwargs; GH#20535 - return cls._generate_range(start, end, periods, name, freq, - tz=tz, normalize=normalize, - closed=closed, ambiguous=ambiguous) + result = cls._generate_range(start, end, periods, + freq=freq, tz=tz, normalize=normalize, + closed=closed, ambiguous=ambiguous) + result.name = name + return result if not isinstance(data, (np.ndarray, Index, ABCSeries, DatetimeArrayMixin)): @@ -315,17 +317,6 @@ def __new__(cls, data=None, return subarr._deepcopy_if_needed(ref_to_data, copy) - @classmethod - @Appender(DatetimeArrayMixin._generate_range.__doc__) - def _generate_range(cls, start, end, periods, name=None, freq=None, - tz=None, normalize=False, ambiguous='raise', - closed=None): - out = super(DatetimeIndex, cls)._generate_range( - start, end, periods, freq, - tz=tz, normalize=normalize, ambiguous=ambiguous, closed=closed) - out.name = name - return out - def _convert_for_op(self, value): """ Convert value to be insertable to ndarray """ if self._has_same_tz(value): diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index cbcd39317e17e..74768d7813501 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -165,8 +165,6 @@ def __new__(cls, data=None, ordinal=None, freq=None, start=None, end=None, raise TypeError('__new__() got an unexpected keyword argument {}'. format(list(set(fields) - valid_field_set)[0])) - periods = dtl.validate_periods(periods) - if name is None and hasattr(data, 'name'): name = data.name diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 8c94ac2ea8256..1efa0a15d34d7 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -147,12 +147,10 @@ def __new__(cls, data=None, unit=None, freq=None, start=None, end=None, if data is None: # TODO: Remove this block and associated kwargs; GH#20535 - if freq is None and com._any_none(periods, start, end): - raise ValueError('Must provide freq argument if no data is ' - 'supplied') - periods = dtl.validate_periods(periods) - return cls._generate_range(start, end, periods, name, freq, - closed=closed) + result = cls._generate_range(start, end, periods, freq, + closed=closed) + result.name = name + return result if unit is not None: data = to_timedelta(data, unit=unit, box=False) @@ -181,16 +179,6 @@ def __new__(cls, data=None, unit=None, freq=None, start=None, end=None, return subarr - @classmethod - def _generate_range(cls, start, end, periods, - name=None, freq=None, closed=None): - # TimedeltaArray gets `name` via **kwargs, so we need to explicitly - # override it if name is passed as a positional argument - return super(TimedeltaIndex, cls)._generate_range(start, end, - periods, freq, - name=name, - closed=closed) - @classmethod def _simple_new(cls, values, name=None, freq=None, **kwargs): result = super(TimedeltaIndex, cls)._simple_new(values, freq, **kwargs)
Split off from #23140.
https://api.github.com/repos/pandas-dev/pandas/pulls/23218
2018-10-18T02:29:18Z
2018-10-23T03:07:07Z
2018-10-23T03:07:07Z
2018-10-23T03:09:51Z
TST: Fix improperly defined tests in test_interval_new.py
diff --git a/pandas/tests/indexes/interval/test_interval_new.py b/pandas/tests/indexes/interval/test_interval_new.py index a0d11db46d316..c5daa7271926f 100644 --- a/pandas/tests/indexes/interval/test_interval_new.py +++ b/pandas/tests/indexes/interval/test_interval_new.py @@ -19,17 +19,16 @@ def _compare_tuple_of_numpy_array(self, result, 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): + def test_get_loc_interval(self, closed, side): - idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=idx_side) + idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed) 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 closed == side: if bound == [0, 1]: assert idx.get_loc(Interval(0, 1, closed=side)) == 0 elif bound == [2, 3]: @@ -41,9 +40,8 @@ def test_get_loc_interval(self, idx_side, side): 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): + def test_get_loc_scalar(self, closed, scalar): # correct = {side: {query: answer}}. # If query is not in the dict, that query should raise a KeyError @@ -52,12 +50,12 @@ def test_get_loc_scalar(self, idx_side, scalar): '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) + idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed) # 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] + if scalar in correct[closed].keys(): + assert idx.get_loc(scalar) == correct[closed][scalar] else: pytest.raises(KeyError, idx.get_loc, scalar) @@ -139,140 +137,119 @@ def test_slice_locs_with_ints_and_floats_succeeds(self): 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): + [0, 1], [0, 2], [0, 3], [3, 1], [3, 4], [0, 4]]) + @pytest.mark.parametrize("tuples", [ + [(0, 2), (1, 3), (2, 4)], [(2, 4), (1, 3), (0, 2)], + [(0, 2), (0, 2), (2, 4)], [(0, 2), (2, 4), (0, 2)], + [(0, 2), (0, 2), (2, 4), (1, 3)]]) + def test_slice_locs_with_ints_and_floats_errors(self, tuples, query): + index = IntervalIndex.from_tuples(tuples) + with pytest.raises(KeyError): + index.slice_locs(query) + + @pytest.mark.parametrize('query, expected', [ + (Interval(1, 3, closed='right'), 1), + (Interval(1, 3, closed='left'), -1), + (Interval(1, 3, closed='both'), -1), + (Interval(1, 3, closed='neither'), -1), + (Interval(1, 4, closed='right'), -1), + (Interval(0, 4, closed='right'), -1), + (Interval(1, 2, closed='right'), -1)]) + def test_get_indexer_with_interval_single_queries(self, query, expected): 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): + expected = np.array([expected], dtype='intp') + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize('query, expected', [ + ([Interval(2, 4, closed='right'), Interval(1, 3, closed='right')], + [2, 1]), + ([Interval(1, 3, closed='right'), Interval(0, 2, closed='right')], + [1, -1]), + ([Interval(1, 3, closed='right'), Interval(1, 3, closed='left')], + [1, -1])]) + def test_get_indexer_with_interval_multiple_queries(self, query, expected): 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]) + expected = np.array(expected, dtype='intp') + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize('query, expected', [ + (-0.5, -1), (0, -1), (0.5, 0), (1, 0), (1.5, 1), (2, 1), + (2.5, -1), (3, -1), (3.5, 2), (4, 2), (4.5, -1)]) def test_get_indexer_with_ints_and_floats_single_queries( - self, query, expected_result): + self, query, expected): 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]]) + expected = np.array([expected], dtype='intp') + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize('query, expected', [ + ([1, 2], [0, 1]), + ([1, 2, 3], [0, 1, -1]), + ([1, 2, 3, 4], [0, 1, -1, 2]), + ([1, 2, 3, 4, 2], [0, 1, -1, 2, 1])]) def test_get_indexer_with_ints_and_floats_multiple_queries( - self, query, expected_result): + self, query, expected): 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) + expected = np.array(expected, dtype='intp') + tm.assert_numpy_array_equal(result, expected) 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]))]) + @pytest.mark.parametrize('query, expected', [ + (-0.5, (Int64Index([], dtype='int64'), np.array([0]))), + (0, (Int64Index([0], dtype='int64'), np.array([]))), + (0.5, (Int64Index([0], dtype='int64'), np.array([]))), + (1, (Int64Index([0, 1], dtype='int64'), np.array([]))), + (1.5, (Int64Index([0, 1], dtype='int64'), np.array([]))), + (2, (Int64Index([0, 1, 2], dtype='int64'), np.array([]))), + (2.5, (Int64Index([1, 2], dtype='int64'), np.array([]))), + (3, (Int64Index([2], dtype='int64'), np.array([]))), + (3.5, (Int64Index([2], dtype='int64'), np.array([]))), + (4, (Int64Index([], dtype='int64'), np.array([0]))), + (4.5, (Int64Index([], dtype='int64'), np.array([0])))]) def test_get_indexer_non_unique_with_ints_and_floats_single_queries( - self, query, expected_result): + self, query, expected): 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]))]) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize('query, expected', [ + ([1, 2], (Int64Index([0, 1, 0, 1, 2], dtype='int64'), np.array([]))), + ([1, 2, 3], + (Int64Index([0, 1, 0, 1, 2, 2], dtype='int64'), np.array([]))), + ([1, 2, 3, 4], + (Int64Index([0, 1, 0, 1, 2, 2, -1], dtype='int64'), np.array([3]))), + ([1, 2, 3, 4, 2], + (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): + self, query, expected): 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) + tm.assert_numpy_array_equal(result, expected) # TODO we may also want to test get_indexer for the case when # the intervals are duplicated, decreasing, non-monotonic, etc.. @@ -303,13 +280,13 @@ def test_contains_method(self): 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 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(Interval(0, 3, closed='right')) + assert not index.contains(Interval(1, 3, closed='right')) assert not index.contains(20) assert not index.contains(-20)
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` I've been working over the new `IntervalIndex` behavior specs and found some issues with the tests for the new behavior. Wanted to make the requisite changes separately so the new behavior PR is as straightforward as possible (will open a WIP PR for it at some point soonish). Specifically fixed a few instances of the following: - Combined instances of two parametrize's that should instead be one pairwise parametrize (i.e. test was doing the product of all parameters instead of pairwise parameters) - Used the `closed` fixture instead of an equivalent explicit parametrize - Fixed a few instances of misplaced parentheses - `expected_result` --> `expected` - parametrized one test where obvious
https://api.github.com/repos/pandas-dev/pandas/pulls/23217
2018-10-18T01:44:46Z
2018-10-18T14:10:46Z
2018-10-18T14:10:46Z
2018-10-19T21:22:51Z
BUG/TST/REF: Datetimelike Arithmetic Methods
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 51c398518c153..4b49bb3da1382 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -1028,6 +1028,7 @@ Datetimelike - Bug in :func:`date_range` when decrementing a start date to a past end date by a negative frequency (:issue:`23270`) - Bug in :func:`DataFrame.combine` with datetimelike values raising a TypeError (:issue:`23079`) - Bug in :func:`date_range` with frequency of ``Day`` or higher where dates sufficiently far in the future could wrap around to the past instead of raising ``OutOfBoundsDatetime`` (:issue:`14187`) +- Bug in :class:`PeriodIndex` with attribute ``freq.n`` greater than 1 where adding a :class:`DateOffset` object would return incorrect results (:issue:`23215`) Timedelta ^^^^^^^^^ @@ -1039,7 +1040,8 @@ Timedelta - Bug in :class:`TimedeltaIndex` incorrectly allowing indexing with ``Timestamp`` object (:issue:`20464`) - Fixed bug where subtracting :class:`Timedelta` from an object-dtyped array would raise ``TypeError`` (:issue:`21980`) - Fixed bug in adding a :class:`DataFrame` with all-`timedelta64[ns]` dtypes to a :class:`DataFrame` with all-integer dtypes returning incorrect results instead of raising ``TypeError`` (:issue:`22696`) - +- Bug in :class:`TimedeltaIndex` where adding a timezone-aware datetime scalar incorrectly returned a timezone-naive :class:`DatetimeIndex` (:issue:`23215`) +- Bug in :class:`TimedeltaIndex` where adding ``np.timedelta64('NaT')`` incorrectly returned an all-`NaT` :class:`DatetimeIndex` instead of an all-`NaT` :class:`TimedeltaIndex` (:issue:`23215`) Timezones ^^^^^^^^^ @@ -1069,7 +1071,7 @@ Offsets - Bug in :class:`FY5253` where date offsets could incorrectly raise an ``AssertionError`` in arithmetic operatons (:issue:`14774`) - Bug in :class:`DateOffset` where keyword arguments ``week`` and ``milliseconds`` were accepted and ignored. Passing these will now raise ``ValueError`` (:issue:`19398`) -- +- Bug in adding :class:`DateOffset` with :class:`DataFrame` or :class:`PeriodIndex` incorrectly raising ``TypeError`` (:issue:`23215`) Numeric ^^^^^^^ diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 393c2cdba8568..5baacfe5f725f 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -344,8 +344,8 @@ class _BaseOffset(object): return {name: kwds[name] for name in kwds if kwds[name] is not None} def __add__(self, other): - if getattr(other, "_typ", None) in ["datetimeindex", - "series", "period"]: + if getattr(other, "_typ", None) in ["datetimeindex", "periodindex", + "series", "period", "dataframe"]: # defer to the other class's implementation return other + self try: diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 28fe6471efb73..0247ce8dc6ac4 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -221,11 +221,12 @@ def hasnans(self): """ return if I have any nans; enables various perf speedups """ return bool(self._isnan.any()) - def _maybe_mask_results(self, result, fill_value=None, convert=None): + def _maybe_mask_results(self, result, fill_value=iNaT, convert=None): """ Parameters ---------- result : a ndarray + fill_value : object, default iNaT convert : string/dtype or None Returns @@ -246,27 +247,6 @@ def _maybe_mask_results(self, result, fill_value=None, convert=None): result[self._isnan] = fill_value return result - def _nat_new(self, box=True): - """ - Return Array/Index or ndarray filled with NaT which has the same - length as the caller. - - Parameters - ---------- - box : boolean, default True - - If True returns a Array/Index as the same as caller. - - If False returns ndarray of np.int64. - """ - result = np.zeros(len(self), dtype=np.int64) - result.fill(iNaT) - if not box: - return result - - attribs = self._get_attributes_dict() - if not is_period_dtype(self): - attribs['freq'] = None - return self._simple_new(result, **attribs) - # ------------------------------------------------------------------ # Frequency Properties/Methods @@ -346,24 +326,58 @@ def _validate_frequency(cls, index, freq, **kwargs): # ------------------------------------------------------------------ # Arithmetic Methods - def _add_datelike(self, other): + def _add_datetimelike_scalar(self, other): + # Overriden by TimedeltaArray raise TypeError("cannot add {cls} and {typ}" .format(cls=type(self).__name__, typ=type(other).__name__)) - def _sub_datelike(self, other): - raise com.AbstractMethodError(self) + _add_datetime_arraylike = _add_datetimelike_scalar + + def _sub_datetimelike_scalar(self, other): + # Overridden by DatetimeArray + assert other is not NaT + raise TypeError("cannot subtract a datelike from a {cls}" + .format(cls=type(self).__name__)) + + _sub_datetime_arraylike = _sub_datetimelike_scalar def _sub_period(self, other): - return NotImplemented + # Overriden by PeriodArray + raise TypeError("cannot subtract Period from a {cls}" + .format(cls=type(self).__name__)) def _add_offset(self, offset): raise com.AbstractMethodError(self) def _add_delta(self, other): - return NotImplemented + """ + Add a timedelta-like, Tick or TimedeltaIndex-like object + to self, yielding an int64 numpy array + + Parameters + ---------- + delta : {timedelta, np.timedelta64, Tick, + TimedeltaIndex, ndarray[timedelta64]} + + Returns + ------- + result : ndarray[int64] - def _add_delta_td(self, other): + Notes + ----- + The result's name is set outside of _add_delta by the calling + method (__add__ or __sub__), if necessary (i.e. for Indexes). + """ + if isinstance(other, (Tick, timedelta, np.timedelta64)): + new_values = self._add_timedeltalike_scalar(other) + elif is_timedelta64_dtype(other): + # ndarray[timedelta64] or TimedeltaArray/index + new_values = self._add_delta_tdi(other) + + return new_values + + def _add_timedeltalike_scalar(self, other): """ Add a delta of a timedeltalike return the i8 result view @@ -371,8 +385,7 @@ def _add_delta_td(self, other): inc = delta_to_nanoseconds(other) new_values = checked_add_with_arr(self.asi8, inc, arr_mask=self._isnan).view('i8') - if self.hasnans: - new_values[self._isnan] = iNaT + new_values = self._maybe_mask_results(new_values) return new_values.view('i8') def _add_delta_tdi(self, other): @@ -380,7 +393,7 @@ def _add_delta_tdi(self, other): Add a delta of a TimedeltaIndex return the i8 result view """ - if not len(self) == len(other): + if len(self) != len(other): raise ValueError("cannot add indices of unequal length") if isinstance(other, np.ndarray): @@ -407,7 +420,9 @@ def _add_nat(self): # GH#19124 pd.NaT is treated like a timedelta for both timedelta # and datetime dtypes - return self._nat_new(box=True) + result = np.zeros(len(self), dtype=np.int64) + result.fill(iNaT) + return self._shallow_copy(result, freq=None) def _sub_nat(self): """Subtract pd.NaT from self""" @@ -441,7 +456,7 @@ def _sub_period_array(self, other): .format(dtype=other.dtype, cls=type(self).__name__)) - if not len(self) == len(other): + if len(self) != len(other): raise ValueError("cannot subtract arrays/indices of " "unequal length") if self.freq != other.freq: @@ -473,6 +488,8 @@ def _addsub_int_array(self, other, op): ------- result : same class as self """ + # _addsub_int_array is overriden by PeriodArray + assert not is_period_dtype(self) assert op in [operator.add, operator.sub] if self.freq is None: @@ -613,7 +630,7 @@ def __add__(self, other): # specifically _not_ a Tick result = self._add_offset(other) elif isinstance(other, (datetime, np.datetime64)): - result = self._add_datelike(other) + result = self._add_datetimelike_scalar(other) elif lib.is_integer(other): # This check must come after the check for np.timedelta64 # as is_integer returns True for these @@ -628,7 +645,7 @@ def __add__(self, other): result = self._addsub_offset_array(other, operator.add) elif is_datetime64_dtype(other) or is_datetime64tz_dtype(other): # DatetimeIndex, ndarray[datetime64] - return self._add_datelike(other) + return self._add_datetime_arraylike(other) elif is_integer_dtype(other): result = self._addsub_int_array(other, operator.add) elif is_float_dtype(other): @@ -671,7 +688,7 @@ def __sub__(self, other): # specifically _not_ a Tick result = self._add_offset(-other) elif isinstance(other, (datetime, np.datetime64)): - result = self._sub_datelike(other) + result = self._sub_datetimelike_scalar(other) elif lib.is_integer(other): # This check must come after the check for np.timedelta64 # as is_integer returns True for these @@ -688,7 +705,7 @@ def __sub__(self, other): result = self._addsub_offset_array(other, operator.sub) elif is_datetime64_dtype(other) or is_datetime64tz_dtype(other): # DatetimeIndex, ndarray[datetime64] - result = self._sub_datelike(other) + result = self._sub_datetime_arraylike(other) elif is_period_dtype(other): # PeriodIndex result = self._sub_period_array(other) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 2392bbdd87f7a..b656690b30e34 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -from datetime import datetime, timedelta, time +from datetime import datetime, time import warnings import numpy as np @@ -21,7 +21,6 @@ is_object_dtype, is_datetime64tz_dtype, is_datetime64_dtype, - is_timedelta64_dtype, ensure_int64) from pandas.core.dtypes.dtypes import DatetimeTZDtype from pandas.core.dtypes.missing import isna @@ -76,11 +75,12 @@ def f(self): if field in self._object_ops: result = fields.get_date_name_field(values, field) - result = self._maybe_mask_results(result) + result = self._maybe_mask_results(result, fill_value=None) else: result = fields.get_date_field(values, field) - result = self._maybe_mask_results(result, convert='float64') + result = self._maybe_mask_results(result, fill_value=None, + convert='float64') return result @@ -424,11 +424,21 @@ def _assert_tzawareness_compat(self, other): # ----------------------------------------------------------------- # Arithmetic Methods - def _sub_datelike_dti(self, other): - """subtraction of two DatetimeIndexes""" - if not len(self) == len(other): + def _sub_datetime_arraylike(self, other): + """subtract DatetimeArray/Index or ndarray[datetime64]""" + if len(self) != len(other): raise ValueError("cannot add indices of unequal length") + if isinstance(other, np.ndarray): + assert is_datetime64_dtype(other) + other = type(self)(other) + + if not self._has_same_tz(other): + # require tz compat + raise TypeError("{cls} subtraction must have the same " + "timezones or no timezones" + .format(cls=type(self).__name__)) + self_i8 = self.asi8 other_i8 = other.asi8 new_values = checked_add_with_arr(self_i8, -other_i8, @@ -456,74 +466,41 @@ def _add_offset(self, offset): return type(self)(result, freq='infer') - def _sub_datelike(self, other): + def _sub_datetimelike_scalar(self, other): # subtract a datetime from myself, yielding a ndarray[timedelta64[ns]] - if isinstance(other, (DatetimeArrayMixin, np.ndarray)): - if isinstance(other, np.ndarray): - # if other is an ndarray, we assume it is datetime64-dtype - other = type(self)(other) - if not self._has_same_tz(other): - # require tz compat - raise TypeError("{cls} subtraction must have the same " - "timezones or no timezones" - .format(cls=type(self).__name__)) - result = self._sub_datelike_dti(other) - elif isinstance(other, (datetime, np.datetime64)): - assert other is not NaT - other = Timestamp(other) - if other is NaT: - return self - NaT + assert isinstance(other, (datetime, np.datetime64)) + assert other is not NaT + other = Timestamp(other) + if other is NaT: + return self - NaT + + if not self._has_same_tz(other): # require tz compat - elif not self._has_same_tz(other): - raise TypeError("Timestamp subtraction must have the same " - "timezones or no timezones") - else: - i8 = self.asi8 - result = checked_add_with_arr(i8, -other.value, - arr_mask=self._isnan) - result = self._maybe_mask_results(result, - fill_value=iNaT) - else: - raise TypeError("cannot subtract {cls} and {typ}" - .format(cls=type(self).__name__, - typ=type(other).__name__)) + raise TypeError("Timestamp subtraction must have the same " + "timezones or no timezones") + + i8 = self.asi8 + result = checked_add_with_arr(i8, -other.value, + arr_mask=self._isnan) + result = self._maybe_mask_results(result) return result.view('timedelta64[ns]') def _add_delta(self, delta): """ - Add a timedelta-like, DateOffset, or TimedeltaIndex-like object - to self. + Add a timedelta-like, Tick, or TimedeltaIndex-like object + to self, yielding a new DatetimeArray Parameters ---------- - delta : {timedelta, np.timedelta64, DateOffset, + other : {timedelta, np.timedelta64, Tick, TimedeltaIndex, ndarray[timedelta64]} Returns ------- - result : same type as self - - Notes - ----- - The result's name is set outside of _add_delta by the calling - method (__add__ or __sub__) + result : DatetimeArray """ - from pandas.core.arrays import TimedeltaArrayMixin - - if isinstance(delta, (Tick, timedelta, np.timedelta64)): - new_values = self._add_delta_td(delta) - elif is_timedelta64_dtype(delta): - if not isinstance(delta, TimedeltaArrayMixin): - delta = TimedeltaArrayMixin(delta) - new_values = self._add_delta_tdi(delta) - else: - new_values = self.astype('O') + delta - - tz = 'UTC' if self.tz is not None else None - result = type(self)(new_values, tz=tz, freq='infer') - if self.tz is not None and self.tz is not utc: - result = result.tz_convert(self.tz) - return result + new_values = dtl.DatetimeLikeArrayMixin._add_delta(self, delta) + return type(self)(new_values, tz=self.tz, freq='infer') # ----------------------------------------------------------------- # Timezone Conversion and Localization Methods @@ -904,7 +881,7 @@ def month_name(self, locale=None): result = fields.get_date_name_field(values, 'month_name', locale=locale) - result = self._maybe_mask_results(result) + result = self._maybe_mask_results(result, fill_value=None) return result def day_name(self, locale=None): @@ -940,7 +917,7 @@ def day_name(self, locale=None): result = fields.get_date_name_field(values, 'day_name', locale=locale) - result = self._maybe_mask_results(result) + result = self._maybe_mask_results(result, fill_value=None) return result @property diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 085298d8324c5..31bcac2f4f529 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -6,7 +6,6 @@ from pandas import compat from pandas.compat.numpy import function as nv -from pandas._libs import lib from pandas._libs.tslib import NaT, iNaT from pandas._libs.tslibs.period import ( Period, IncompatibleFrequency, DIFFERENT_FREQ_INDEX, @@ -15,7 +14,7 @@ from pandas._libs.tslibs import period as libperiod from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds, Timedelta from pandas._libs.tslibs.fields import isleapyear_arr -from pandas.util._decorators import cache_readonly +from pandas.util._decorators import cache_readonly, Appender from pandas.util._validators import validate_fillna_kwargs import pandas.core.algorithms as algos from pandas.core.dtypes.common import ( @@ -23,7 +22,6 @@ pandas_dtype, is_datetime64_dtype, is_categorical_dtype, - is_timedelta64_dtype, is_list_like, is_array_like, is_object_dtype, @@ -33,8 +31,6 @@ ensure_object, _TD_DTYPE, ) - - from pandas.core.dtypes.dtypes import PeriodDtype from pandas.core.dtypes.generic import ( ABCSeries, ABCIndexClass, ABCPeriodIndex @@ -45,7 +41,7 @@ import pandas.core.common as com from pandas.tseries import frequencies -from pandas.tseries.offsets import Tick, DateOffset +from pandas.tseries.offsets import Tick from pandas.core.arrays import ExtensionArray from pandas.core.arrays import datetimelike as dtl @@ -497,7 +493,11 @@ def _time_shift(self, n, freq=None): freq : pandas.DateOffset, pandas.Timedelta, or string Frequency increment to shift by. """ - values = self._data + n * self.freq.n + if freq is not None: + raise TypeError("`freq` argument is not supported for " + "{cls}._time_shift" + .format(cls=type(self).__name__)) + values = self.asi8 + n * self.freq.n if self.hasnans: values[self._isnan] = iNaT return type(self)(values, freq=self.freq) @@ -606,52 +606,9 @@ def to_timestamp(self, freq=None, how='start'): new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base) return DatetimeArrayMixin(new_data, freq='infer') - def _maybe_convert_timedelta(self, other): - """ - Convert timedelta-like input to an integer multiple of self.freq - - Parameters - ---------- - other : timedelta, np.timedelta64, DateOffset, int, np.ndarray - - Returns - ------- - converted : int, np.ndarray[int64] - - Raises - ------ - IncompatibleFrequency : if the input cannot be written as a multiple - of self.freq. Note IncompatibleFrequency subclasses ValueError. - """ - if isinstance( - other, (timedelta, np.timedelta64, Tick, np.ndarray)): - offset = frequencies.to_offset(self.freq.rule_code) - if isinstance(offset, Tick): - # _check_timedeltalike_freq_compat will raise if incompatible - delta = self._check_timedeltalike_freq_compat(other) - return delta - elif isinstance(other, DateOffset): - freqstr = other.rule_code - base = frequencies.get_base_alias(freqstr) - if base == self.freq.rule_code: - return other.n - msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) - raise IncompatibleFrequency(msg) - elif lib.is_integer(other): - # integer is passed to .shift via - # _add_datetimelike_methods basically - # but ufunc may pass integer to _add_delta - return other - - # raise when input doesn't have freq - msg = "Input has different freq from {cls}(freq={freqstr})" - raise IncompatibleFrequency(msg.format(cls=type(self).__name__, - freqstr=self.freqstr)) - # ------------------------------------------------------------------ # Formatting - def _format_native_types(self, na_rep=u'NaT', date_format=None, - **kwargs): + def _format_native_types(self, na_rep=u'NaT', date_format=None, **kwargs): """ actually format my specific types """ # TODO(DatetimeArray): remove values = self.astype(object) @@ -671,58 +628,6 @@ def _format_native_types(self, na_rep=u'NaT', date_format=None, values = np.array([formatter(dt) for dt in values]) return values - def _check_timedeltalike_freq_compat(self, other): - """ - Arithmetic operations with timedelta-like scalars or array `other` - are only valid if `other` is an integer multiple of `self.freq`. - If the operation is valid, find that integer multiple. Otherwise, - raise because the operation is invalid. - - Parameters - ---------- - other : timedelta, np.timedelta64, Tick, - ndarray[timedelta64], TimedeltaArray, TimedeltaIndex - - Returns - ------- - multiple : int or ndarray[int64] - - Raises - ------ - IncompatibleFrequency - """ - assert isinstance(self.freq, Tick) # checked by calling function - own_offset = frequencies.to_offset(self.freq.rule_code) - base_nanos = delta_to_nanoseconds(own_offset) - - if isinstance(other, (timedelta, np.timedelta64, Tick)): - nanos = delta_to_nanoseconds(other) - - elif isinstance(other, np.ndarray): - # numpy timedelta64 array; all entries must be compatible - assert other.dtype.kind == 'm' - if other.dtype != _TD_DTYPE: - # i.e. non-nano unit - # TODO: disallow unit-less timedelta64 - other = other.astype(_TD_DTYPE) - nanos = other.view('i8') - else: - # TimedeltaArray/Index - nanos = other.asi8 - - if np.all(nanos % base_nanos == 0): - # nanos being added is an integer multiple of the - # base-frequency to self.freq - delta = nanos // base_nanos - # delta is the integer (or integer-array) number of periods - # by which will be added to self. - return delta - - raise IncompatibleFrequency("Input has different freq from " - "{cls}(freq={freqstr})" - .format(cls=type(self).__name__, - freqstr=self.freqstr)) - def repeat(self, repeats, *args, **kwargs): """ Repeat elements of a Categorical. @@ -810,6 +715,7 @@ def _sub_period(self, other): return new_data + @Appender(dtl.DatetimeLikeArrayMixin._addsub_int_array.__doc__) def _addsub_int_array( self, other, # type: Union[Index, ExtensionArray, np.ndarray[int]] @@ -817,7 +723,6 @@ def _addsub_int_array( ): # type: (...) -> PeriodArray assert op in [operator.add, operator.sub] - # easy case for PeriodIndex if op is operator.sub: other = -other res_values = algos.checked_add_with_arr(self.asi8, other, @@ -832,30 +737,53 @@ def _add_offset(self, other): if base != self.freq.rule_code: msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) - return self._time_shift(other.n) - def _add_delta_td(self, other): + # Note: when calling parent class's _add_timedeltalike_scalar, + # it will call delta_to_nanoseconds(delta). Because delta here + # is an integer, delta_to_nanoseconds will return it unchanged. + result = super(PeriodArray, self)._add_timedeltalike_scalar(other.n) + return type(self)(result, freq=self.freq) + + def _add_timedeltalike_scalar(self, other): + """ + Parameters + ---------- + other : timedelta, Tick, np.timedelta64 + + Returns + ------- + result : ndarray[int64] + """ assert isinstance(self.freq, Tick) # checked by calling function assert isinstance(other, (timedelta, np.timedelta64, Tick)) delta = self._check_timedeltalike_freq_compat(other) - # Note: when calling parent class's _add_delta_td, it will call - # delta_to_nanoseconds(delta). Because delta here is an integer, - # delta_to_nanoseconds will return it unchanged. - ordinals = super(PeriodArray, self)._add_delta_td(delta) - return type(self)(ordinals, self.freq) + # Note: when calling parent class's _add_timedeltalike_scalar, + # it will call delta_to_nanoseconds(delta). Because delta here + # is an integer, delta_to_nanoseconds will return it unchanged. + ordinals = super(PeriodArray, self)._add_timedeltalike_scalar(delta) + return ordinals def _add_delta_tdi(self, other): + """ + Parameters + ---------- + other : TimedeltaArray or ndarray[timedelta64] + + Returns + ------- + result : ndarray[int64] + """ assert isinstance(self.freq, Tick) # checked by calling function delta = self._check_timedeltalike_freq_compat(other) - return self._addsub_int_array(delta, operator.add) + return self._addsub_int_array(delta, operator.add).asi8 def _add_delta(self, other): """ Add a timedelta-like, Tick, or TimedeltaIndex-like object - to self. + to self, yielding a new PeriodArray Parameters ---------- @@ -864,7 +792,7 @@ def _add_delta(self, other): Returns ------- - result : same type as self + result : PeriodArray """ if not isinstance(self.freq, Tick): # We cannot add timedelta-like to non-tick PeriodArray @@ -873,15 +801,60 @@ def _add_delta(self, other): .format(cls=type(self).__name__, freqstr=self.freqstr)) - # TODO: standardize across datetimelike subclasses whether to return - # i8 view or _shallow_copy - if isinstance(other, (Tick, timedelta, np.timedelta64)): - return self._add_delta_td(other) - elif is_timedelta64_dtype(other): - # ndarray[timedelta64] or TimedeltaArray/index - return self._add_delta_tdi(other) - else: # pragma: no cover - raise TypeError(type(other).__name__) + new_ordinals = super(PeriodArray, self)._add_delta(other) + return type(self)(new_ordinals, freq=self.freq) + + def _check_timedeltalike_freq_compat(self, other): + """ + Arithmetic operations with timedelta-like scalars or array `other` + are only valid if `other` is an integer multiple of `self.freq`. + If the operation is valid, find that integer multiple. Otherwise, + raise because the operation is invalid. + + Parameters + ---------- + other : timedelta, np.timedelta64, Tick, + ndarray[timedelta64], TimedeltaArray, TimedeltaIndex + + Returns + ------- + multiple : int or ndarray[int64] + + Raises + ------ + IncompatibleFrequency + """ + assert isinstance(self.freq, Tick) # checked by calling function + own_offset = frequencies.to_offset(self.freq.rule_code) + base_nanos = delta_to_nanoseconds(own_offset) + + if isinstance(other, (timedelta, np.timedelta64, Tick)): + nanos = delta_to_nanoseconds(other) + + elif isinstance(other, np.ndarray): + # numpy timedelta64 array; all entries must be compatible + assert other.dtype.kind == 'm' + if other.dtype != _TD_DTYPE: + # i.e. non-nano unit + # TODO: disallow unit-less timedelta64 + other = other.astype(_TD_DTYPE) + nanos = other.view('i8') + else: + # TimedeltaArray/Index + nanos = other.asi8 + + if np.all(nanos % base_nanos == 0): + # nanos being added is an integer multiple of the + # base-frequency to self.freq + delta = nanos // base_nanos + # delta is the integer (or integer-array) number of periods + # by which will be added to self. + return delta + + raise IncompatibleFrequency("Input has different freq from " + "{cls}(freq={freqstr})" + .format(cls=type(self).__name__, + freqstr=self.freqstr)) PeriodArray._add_comparison_ops() diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index eb7dabdc03b0b..397297c1b88d0 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -4,7 +4,7 @@ import numpy as np from pandas._libs import tslibs -from pandas._libs.tslibs import Timedelta, Timestamp, NaT, iNaT +from pandas._libs.tslibs import Timedelta, Timestamp, NaT from pandas._libs.tslibs.fields import get_timedelta_field from pandas._libs.tslibs.timedeltas import array_to_timedelta64 @@ -46,7 +46,8 @@ def f(self): values = self.asi8 result = get_timedelta_field(values, alias) if self.hasnans: - result = self._maybe_mask_results(result, convert='float64') + result = self._maybe_mask_results(result, fill_value=None, + convert='float64') return result @@ -188,61 +189,51 @@ def _add_offset(self, other): .format(typ=type(other).__name__, cls=type(self).__name__)) - def _sub_datelike(self, other): - assert other is not NaT - raise TypeError("cannot subtract a datelike from a {cls}" - .format(cls=type(self).__name__)) - def _add_delta(self, delta): """ Add a timedelta-like, Tick, or TimedeltaIndex-like object - to self. + to self, yielding a new TimedeltaArray Parameters ---------- - delta : timedelta, np.timedelta64, Tick, TimedeltaArray, TimedeltaIndex + other : {timedelta, np.timedelta64, Tick, + TimedeltaIndex, ndarray[timedelta64]} Returns ------- - result : same type as self - - Notes - ----- - The result's name is set outside of _add_delta by the calling - method (__add__ or __sub__) + result : TimedeltaArray """ - if isinstance(delta, (Tick, timedelta, np.timedelta64)): - new_values = self._add_delta_td(delta) - elif isinstance(delta, TimedeltaArrayMixin): - new_values = self._add_delta_tdi(delta) - elif is_timedelta64_dtype(delta): - # ndarray[timedelta64] --> wrap in TimedeltaArray/Index - delta = type(self)(delta) - new_values = self._add_delta_tdi(delta) - else: - raise TypeError("cannot add the type {0} to a TimedeltaIndex" - .format(type(delta))) - + new_values = dtl.DatetimeLikeArrayMixin._add_delta(self, delta) return type(self)(new_values, freq='infer') - def _add_datelike(self, other): + def _add_datetime_arraylike(self, other): + """Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray""" + if isinstance(other, np.ndarray): + # At this point we have already checked that dtype is datetime64 + from pandas.core.arrays import DatetimeArrayMixin + other = DatetimeArrayMixin(other) + + # defer to implementation in DatetimeArray + return other + self + + def _add_datetimelike_scalar(self, other): # adding a timedeltaindex to a datetimelike from pandas.core.arrays import DatetimeArrayMixin - if isinstance(other, (DatetimeArrayMixin, np.ndarray)): - # if other is an ndarray, we assume it is datetime64-dtype - # defer to implementation in DatetimeIndex - if not isinstance(other, DatetimeArrayMixin): - other = DatetimeArrayMixin(other) - return other + self - else: - assert other is not NaT - other = Timestamp(other) - i8 = self.asi8 - result = checked_add_with_arr(i8, other.value, - arr_mask=self._isnan) - result = self._maybe_mask_results(result, fill_value=iNaT) + + assert other is not NaT + other = Timestamp(other) + if other is NaT: + # In this case we specifically interpret NaT as a datetime, not + # the timedelta interpretation we would get by returning self + NaT + result = self.asi8.view('m8[ms]') + NaT.to_datetime64() return DatetimeArrayMixin(result) + i8 = self.asi8 + result = checked_add_with_arr(i8, other.value, + arr_mask=self._isnan) + result = self._maybe_mask_results(result) + return DatetimeArrayMixin(result, tz=other.tz) + def _addsub_offset_array(self, other, op): # Add or subtract Array-like of DateOffset objects try: @@ -276,7 +267,8 @@ def _evaluate_with_timedelta_like(self, other, op): result = op(left, right) else: result = op(left, np.float64(right)) - result = self._maybe_mask_results(result, convert='float64') + result = self._maybe_mask_results(result, fill_value=None, + convert='float64') return result return NotImplemented @@ -339,7 +331,7 @@ def total_seconds(self): Float64Index([0.0, 86400.0, 172800.0, 259200.00000000003, 345600.0], dtype='float64') """ - return self._maybe_mask_results(1e-9 * self.asi8) + return self._maybe_mask_results(1e-9 * self.asi8, fill_value=None) def to_pytimedelta(self): """ diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index e59e696e98e51..c3728d8d956de 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -1,5 +1,5 @@ # pylint: disable=E1101,E1103,W0232 -from datetime import datetime +from datetime import datetime, timedelta import numpy as np import operator import warnings @@ -39,6 +39,9 @@ Appender, Substitution, cache_readonly, deprecate_kwarg ) +from pandas.tseries.offsets import Tick, DateOffset +from pandas.tseries import frequencies + import pandas.core.indexes.base as ibase _index_doc_kwargs = dict(ibase._index_doc_kwargs) _index_doc_kwargs.update( @@ -406,8 +409,46 @@ def _format_native_types(self, na_rep=u'NaT', quoting=None, **kwargs): **kwargs) def _maybe_convert_timedelta(self, other): - # just dispatch, return ndarray - return self._data._maybe_convert_timedelta(other) + """ + Convert timedelta-like input to an integer multiple of self.freq + + Parameters + ---------- + other : timedelta, np.timedelta64, DateOffset, int, np.ndarray + + Returns + ------- + converted : int, np.ndarray[int64] + + Raises + ------ + IncompatibleFrequency : if the input cannot be written as a multiple + of self.freq. Note IncompatibleFrequency subclasses ValueError. + """ + if isinstance( + other, (timedelta, np.timedelta64, Tick, np.ndarray)): + offset = frequencies.to_offset(self.freq.rule_code) + if isinstance(offset, Tick): + # _check_timedeltalike_freq_compat will raise if incompatible + delta = self._data._check_timedeltalike_freq_compat(other) + return delta + elif isinstance(other, DateOffset): + freqstr = other.rule_code + base = frequencies.get_base_alias(freqstr) + if base == self.freq.rule_code: + return other.n + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + raise IncompatibleFrequency(msg) + elif is_integer(other): + # integer is passed to .shift via + # _add_datetimelike_methods basically + # but ufunc may pass integer to _add_delta + return other + + # raise when input doesn't have freq + msg = "Input has different freq from {cls}(freq={freqstr})" + raise IncompatibleFrequency(msg.format(cls=type(self).__name__, + freqstr=self.freqstr)) # ------------------------------------------------------------------------ # Indexing diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 1efa0a15d34d7..e5da21478d0a4 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -232,7 +232,8 @@ def astype(self, dtype, copy=True): # return an index (essentially this is division) result = self.values.astype(dtype, copy=copy) if self.hasnans: - values = self._maybe_mask_results(result, convert='float64') + values = self._maybe_mask_results(result, fill_value=None, + convert='float64') return Index(values, name=self.name) return Index(result.astype('i8'), name=self.name) return super(TimedeltaIndex, self).astype(dtype, copy=copy) diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index cff2c25231220..184e76cfa490f 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -15,6 +15,7 @@ import pandas.core.indexes.period as period from pandas.core import ops from pandas import Period, PeriodIndex, period_range, Series +from pandas.tseries.frequencies import to_offset # ------------------------------------------------------------------ @@ -372,6 +373,22 @@ def test_pi_add_sub_float(self, op, other, box): with pytest.raises(TypeError): op(pi, other) + @pytest.mark.parametrize('other', [pd.Timestamp.now(), + pd.Timestamp.now().to_pydatetime(), + pd.Timestamp.now().to_datetime64()]) + def test_pi_add_sub_datetime(self, other): + # GH#23215 + rng = pd.period_range('1/1/2000', freq='D', periods=3) + + with pytest.raises(TypeError): + rng + other + with pytest.raises(TypeError): + other + rng + with pytest.raises(TypeError): + rng - other + with pytest.raises(TypeError): + other - rng + # ----------------------------------------------------------------- # __add__/__sub__ with ndarray[datetime64] and ndarray[timedelta64] @@ -536,6 +553,38 @@ def test_pi_sub_isub_offset(self): rng -= pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected) + def test_pi_add_offset_n_gt1(self, box): + # GH#23215 + # add offset to PeriodIndex with freq.n > 1 + per = pd.Period('2016-01', freq='2M') + pi = pd.PeriodIndex([per]) + + expected = pd.PeriodIndex(['2016-03'], freq='2M') + pi = tm.box_expected(pi, box) + expected = tm.box_expected(expected, box) + + result = pi + per.freq + tm.assert_equal(result, expected) + + result = per.freq + pi + tm.assert_equal(result, expected) + + def test_pi_add_offset_n_gt1_not_divisible(self, box): + # GH#23215 + # PeriodIndex with freq.n > 1 add offset with offset.n % freq.n != 0 + + pi = pd.PeriodIndex(['2016-01'], freq='2M') + pi = tm.box_expected(pi, box) + + expected = pd.PeriodIndex(['2016-04'], freq='2M') + expected = tm.box_expected(expected, box) + + result = pi + to_offset('3M') + tm.assert_equal(result, expected) + + result = to_offset('3M') + pi + tm.assert_equal(result, expected) + # --------------------------------------------------------------- # __add__/__sub__ with integer arrays diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 56bef2fee2b41..9930297fd1a3c 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -418,17 +418,22 @@ def test_td64arr_sub_timestamp_raises(self, box): with tm.assert_raises_regex(TypeError, msg): idx - Timestamp('2011-01-01') - def test_td64arr_add_timestamp(self, box): + def test_td64arr_add_timestamp(self, box, tz_naive_fixture): + # GH#23215 + # TODO: parametrize over scalar datetime types? + tz = tz_naive_fixture + other = Timestamp('2011-01-01', tz=tz) + idx = TimedeltaIndex(['1 day', '2 day']) - expected = DatetimeIndex(['2011-01-02', '2011-01-03']) + expected = DatetimeIndex(['2011-01-02', '2011-01-03'], tz=tz) idx = tm.box_expected(idx, box) expected = tm.box_expected(expected, box) - result = idx + Timestamp('2011-01-01') + result = idx + other tm.assert_equal(result, expected) - result = Timestamp('2011-01-01') + idx + result = other + idx tm.assert_equal(result, expected) def test_td64arr_add_sub_timestamp(self, box): @@ -489,6 +494,19 @@ def test_tdi_add_dt64_array(self, box_df_broadcast_failure): result = dtarr + tdi tm.assert_equal(result, expected) + def test_td64arr_add_datetime64_nat(self, box): + # GH#23215 + other = np.datetime64('NaT') + + tdi = timedelta_range('1 day', periods=3) + expected = pd.DatetimeIndex(["NaT", "NaT", "NaT"]) + + tdser = tm.box_expected(tdi, box) + expected = tm.box_expected(expected, box) + + tm.assert_equal(tdser + other, expected) + tm.assert_equal(other + tdser, expected) + # ------------------------------------------------------------------ # Operations with int-like others diff --git a/pandas/tests/arrays/test_period.py b/pandas/tests/arrays/test_period.py index 780df579d2778..dcbb0d4048b0f 100644 --- a/pandas/tests/arrays/test_period.py +++ b/pandas/tests/arrays/test_period.py @@ -190,17 +190,3 @@ def tet_sub_period(): other = pd.Period("2000", freq="M") with tm.assert_raises_regex(IncompatibleFrequency, "freq"): arr - other - - -# ---------------------------------------------------------------------------- -# other - -def test_maybe_convert_timedelta(): - arr = period_array(['2000', '2001'], freq='D') - offset = pd.tseries.offsets.Day(2) - assert arr._maybe_convert_timedelta(offset) == 2 - assert arr._maybe_convert_timedelta(2) == 2 - - offset = pd.tseries.offsets.BusinessDay() - with tm.assert_raises_regex(ValueError, 'freq'): - arr._maybe_convert_timedelta(offset) diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index f06291a7e4e9e..086c687148292 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -5,7 +5,6 @@ import pytest import pandas as pd -import pandas._libs.tslib as tslib import pandas.util.testing as tm from pandas import ( DatetimeIndex, Index, PeriodIndex, Series, Timestamp, bdate_range, @@ -36,7 +35,7 @@ def test_ops_properties(self): def test_ops_properties_basic(self): # sanity check that the behavior didn't change - # GH7206 + # GH#7206 for op in ['year', 'day', 'second', 'weekday']: pytest.raises(TypeError, lambda x: getattr(self.dt_series, op)) @@ -339,16 +338,6 @@ def test_infer_freq(self, freq): tm.assert_index_equal(idx, result) assert result.freq == freq - def test_nat_new(self): - idx = pd.date_range('2011-01-01', freq='D', periods=5, name='x') - result = idx._nat_new() - exp = pd.DatetimeIndex([pd.NaT] * 5, name='x') - tm.assert_index_equal(result, exp) - - result = idx._nat_new(box=False) - exp = np.array([tslib.iNaT] * 5, dtype=np.int64) - tm.assert_numpy_array_equal(result, exp) - def test_nat(self, tz_naive_fixture): tz = tz_naive_fixture assert pd.DatetimeIndex._na_value is pd.NaT diff --git a/pandas/tests/indexes/period/test_ops.py b/pandas/tests/indexes/period/test_ops.py index f4ee5e88b77b2..80550292ed4f8 100644 --- a/pandas/tests/indexes/period/test_ops.py +++ b/pandas/tests/indexes/period/test_ops.py @@ -312,17 +312,6 @@ def test_order(self): tm.assert_numpy_array_equal(indexer, exp, check_dtype=False) assert ordered.freq == 'D' - def test_nat_new(self): - - idx = pd.period_range('2011-01', freq='M', periods=5, name='x') - result = idx._nat_new() - exp = pd.PeriodIndex([pd.NaT] * 5, freq='M', name='x') - tm.assert_index_equal(result, exp) - - result = idx._nat_new(box=False) - exp = np.array([tslib.iNaT] * 5, dtype=np.int64) - tm.assert_numpy_array_equal(result, exp) - def test_shift(self): # This is tested in test_arithmetic pass diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index e699a560cb2f6..300d5ef609b3e 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -557,3 +557,14 @@ def test_insert(self): for na in (np.nan, pd.NaT, None): result = period_range('2017Q1', periods=4, freq='Q').insert(1, na) tm.assert_index_equal(result, expected) + + +def test_maybe_convert_timedelta(): + pi = PeriodIndex(['2000', '2001'], freq='D') + offset = offsets.Day(2) + assert pi._maybe_convert_timedelta(offset) == 2 + assert pi._maybe_convert_timedelta(2) == 2 + + offset = offsets.BusinessDay() + with tm.assert_raises_regex(ValueError, 'freq'): + pi._maybe_convert_timedelta(offset) diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index 9b3bcbef36805..a8cfdd0add178 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -9,7 +9,6 @@ Series, Timedelta, TimedeltaIndex, Timestamp, timedelta_range, to_timedelta ) -from pandas._libs.tslib import iNaT from pandas.core.dtypes.generic import ABCDateOffset from pandas.tests.test_base import Ops from pandas.tseries.offsets import Day, Hour @@ -238,17 +237,6 @@ def test_infer_freq(self, freq): tm.assert_index_equal(idx, result) assert result.freq == freq - def test_nat_new(self): - - idx = pd.timedelta_range('1', freq='D', periods=5, name='x') - result = idx._nat_new() - exp = pd.TimedeltaIndex([pd.NaT] * 5, name='x') - tm.assert_index_equal(result, exp) - - result = idx._nat_new(box=False) - exp = np.array([iNaT] * 5, dtype=np.int64) - tm.assert_numpy_array_equal(result, exp) - def test_shift(self): pass # handled in test_arithmetic.py
@TomAugspurger @jorisvandenbossche @jreback as discussed - [ ] closes #xxxx - [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/23215
2018-10-17T23:09:56Z
2018-10-28T13:34:00Z
2018-10-28T13:34:00Z
2018-10-28T16:16:10Z
REF: use fused types for the rest of libjoin
diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx index 7c791ab8a1b00..c6afeda6a37dc 100644 --- a/pandas/_libs/join.pyx +++ b/pandas/_libs/join.pyx @@ -17,8 +17,6 @@ cdef double nan = NaN from pandas._libs.algos import groupsort_indexer, ensure_platform_int from pandas.core.algorithms import take_nd -include "join_func_helper.pxi" - def inner_join(ndarray[int64_t] left, ndarray[int64_t] right, Py_ssize_t max_groups): @@ -309,8 +307,8 @@ left_join_indexer_unique_int64 = left_join_indexer_unique["int64_t"] left_join_indexer_unique_uint64 = left_join_indexer_unique["uint64_t"] -# @cython.wraparound(False) -# @cython.boundscheck(False) +@cython.wraparound(False) +@cython.boundscheck(False) def left_join_indexer(ndarray[join_t] left, ndarray[join_t] right): """ Two-pass algorithm for monotonic indexes. Handles many-to-one merges @@ -656,3 +654,357 @@ outer_join_indexer_object = outer_join_indexer["object"] outer_join_indexer_int32 = outer_join_indexer["int32_t"] outer_join_indexer_int64 = outer_join_indexer["int64_t"] outer_join_indexer_uint64 = outer_join_indexer["uint64_t"] + + +# ---------------------------------------------------------------------- +# asof_join_by +# ---------------------------------------------------------------------- + +from hashtable cimport ( + HashTable, PyObjectHashTable, UInt64HashTable, Int64HashTable) + +ctypedef fused asof_t: + uint8_t + uint16_t + uint32_t + uint64_t + int8_t + int16_t + int32_t + int64_t + float + double + +ctypedef fused by_t: + object + int64_t + uint64_t + + +def asof_join_backward_on_X_by_Y(ndarray[asof_t] left_values, + ndarray[asof_t] right_values, + ndarray[by_t] left_by_values, + ndarray[by_t] right_by_values, + bint allow_exact_matches=1, + tolerance=None): + + cdef: + Py_ssize_t left_pos, right_pos, left_size, right_size, found_right_pos + ndarray[int64_t] left_indexer, right_indexer + bint has_tolerance = 0 + asof_t tolerance_ = 0 + asof_t diff = 0 + HashTable hash_table + by_t by_value + + # if we are using tolerance, set our objects + if tolerance is not None: + has_tolerance = 1 + tolerance_ = tolerance + + left_size = len(left_values) + right_size = len(right_values) + + left_indexer = np.empty(left_size, dtype=np.int64) + right_indexer = np.empty(left_size, dtype=np.int64) + + if by_t is object: + hash_table = PyObjectHashTable(right_size) + elif by_t is int64_t: + hash_table = Int64HashTable(right_size) + elif by_t is uint64_t: + hash_table = UInt64HashTable(right_size) + + right_pos = 0 + for left_pos in range(left_size): + # restart right_pos if it went negative in a previous iteration + if right_pos < 0: + right_pos = 0 + + # find last position in right whose value is less than left's + if allow_exact_matches: + while (right_pos < right_size and + right_values[right_pos] <= left_values[left_pos]): + hash_table.set_item(right_by_values[right_pos], right_pos) + right_pos += 1 + else: + while (right_pos < right_size and + right_values[right_pos] < left_values[left_pos]): + hash_table.set_item(right_by_values[right_pos], right_pos) + right_pos += 1 + right_pos -= 1 + + # save positions as the desired index + by_value = left_by_values[left_pos] + found_right_pos = (hash_table.get_item(by_value) + if by_value in hash_table else -1) + left_indexer[left_pos] = left_pos + right_indexer[left_pos] = found_right_pos + + # if needed, verify that tolerance is met + if has_tolerance and found_right_pos != -1: + diff = left_values[left_pos] - right_values[found_right_pos] + if diff > tolerance_: + right_indexer[left_pos] = -1 + + return left_indexer, right_indexer + + +def asof_join_forward_on_X_by_Y(ndarray[asof_t] left_values, + ndarray[asof_t] right_values, + ndarray[by_t] left_by_values, + ndarray[by_t] right_by_values, + bint allow_exact_matches=1, + tolerance=None): + + cdef: + Py_ssize_t left_pos, right_pos, left_size, right_size, found_right_pos + ndarray[int64_t] left_indexer, right_indexer + bint has_tolerance = 0 + asof_t tolerance_ = 0 + asof_t diff = 0 + HashTable hash_table + by_t by_value + + # if we are using tolerance, set our objects + if tolerance is not None: + has_tolerance = 1 + tolerance_ = tolerance + + left_size = len(left_values) + right_size = len(right_values) + + left_indexer = np.empty(left_size, dtype=np.int64) + right_indexer = np.empty(left_size, dtype=np.int64) + + if by_t is object: + hash_table = PyObjectHashTable(right_size) + elif by_t is int64_t: + hash_table = Int64HashTable(right_size) + elif by_t is uint64_t: + hash_table = UInt64HashTable(right_size) + + right_pos = right_size - 1 + for left_pos in range(left_size - 1, -1, -1): + # restart right_pos if it went over in a previous iteration + if right_pos == right_size: + right_pos = right_size - 1 + + # find first position in right whose value is greater than left's + if allow_exact_matches: + while (right_pos >= 0 and + right_values[right_pos] >= left_values[left_pos]): + hash_table.set_item(right_by_values[right_pos], right_pos) + right_pos -= 1 + else: + while (right_pos >= 0 and + right_values[right_pos] > left_values[left_pos]): + hash_table.set_item(right_by_values[right_pos], right_pos) + right_pos -= 1 + right_pos += 1 + + # save positions as the desired index + by_value = left_by_values[left_pos] + found_right_pos = (hash_table.get_item(by_value) + if by_value in hash_table else -1) + left_indexer[left_pos] = left_pos + right_indexer[left_pos] = found_right_pos + + # if needed, verify that tolerance is met + if has_tolerance and found_right_pos != -1: + diff = right_values[found_right_pos] - left_values[left_pos] + if diff > tolerance_: + right_indexer[left_pos] = -1 + + return left_indexer, right_indexer + + +def asof_join_nearest_on_X_by_Y(ndarray[asof_t] left_values, + ndarray[asof_t] right_values, + ndarray[by_t] left_by_values, + ndarray[by_t] right_by_values, + bint allow_exact_matches=1, + tolerance=None): + + cdef: + Py_ssize_t left_size, right_size, i + ndarray[int64_t] left_indexer, right_indexer, bli, bri, fli, fri + asof_t bdiff, fdiff + + left_size = len(left_values) + right_size = len(right_values) + + left_indexer = np.empty(left_size, dtype=np.int64) + right_indexer = np.empty(left_size, dtype=np.int64) + + # search both forward and backward + bli, bri = asof_join_backward_on_X_by_Y(left_values, + right_values, + left_by_values, + right_by_values, + allow_exact_matches, + tolerance) + fli, fri = asof_join_forward_on_X_by_Y(left_values, + right_values, + left_by_values, + right_by_values, + allow_exact_matches, + tolerance) + + for i in range(len(bri)): + # choose timestamp from right with smaller difference + if bri[i] != -1 and fri[i] != -1: + bdiff = left_values[bli[i]] - right_values[bri[i]] + fdiff = right_values[fri[i]] - left_values[fli[i]] + right_indexer[i] = bri[i] if bdiff <= fdiff else fri[i] + else: + right_indexer[i] = bri[i] if bri[i] != -1 else fri[i] + left_indexer[i] = bli[i] + + return left_indexer, right_indexer + + +# ---------------------------------------------------------------------- +# asof_join +# ---------------------------------------------------------------------- + +def asof_join_backward(ndarray[asof_t] left_values, + ndarray[asof_t] right_values, + bint allow_exact_matches=1, + tolerance=None): + + cdef: + Py_ssize_t left_pos, right_pos, left_size, right_size + ndarray[int64_t] left_indexer, right_indexer + bint has_tolerance = 0 + asof_t tolerance_ = 0 + asof_t diff = 0 + + # if we are using tolerance, set our objects + if tolerance is not None: + has_tolerance = 1 + tolerance_ = tolerance + + left_size = len(left_values) + right_size = len(right_values) + + left_indexer = np.empty(left_size, dtype=np.int64) + right_indexer = np.empty(left_size, dtype=np.int64) + + right_pos = 0 + for left_pos in range(left_size): + # restart right_pos if it went negative in a previous iteration + if right_pos < 0: + right_pos = 0 + + # find last position in right whose value is less than left's + if allow_exact_matches: + while (right_pos < right_size and + right_values[right_pos] <= left_values[left_pos]): + right_pos += 1 + else: + while (right_pos < right_size and + right_values[right_pos] < left_values[left_pos]): + right_pos += 1 + right_pos -= 1 + + # save positions as the desired index + left_indexer[left_pos] = left_pos + right_indexer[left_pos] = right_pos + + # if needed, verify that tolerance is met + if has_tolerance and right_pos != -1: + diff = left_values[left_pos] - right_values[right_pos] + if diff > tolerance_: + right_indexer[left_pos] = -1 + + return left_indexer, right_indexer + + +def asof_join_forward(ndarray[asof_t] left_values, + ndarray[asof_t] right_values, + bint allow_exact_matches=1, + tolerance=None): + + cdef: + Py_ssize_t left_pos, right_pos, left_size, right_size + ndarray[int64_t] left_indexer, right_indexer + bint has_tolerance = 0 + asof_t tolerance_ = 0 + asof_t diff = 0 + + # if we are using tolerance, set our objects + if tolerance is not None: + has_tolerance = 1 + tolerance_ = tolerance + + left_size = len(left_values) + right_size = len(right_values) + + left_indexer = np.empty(left_size, dtype=np.int64) + right_indexer = np.empty(left_size, dtype=np.int64) + + right_pos = right_size - 1 + for left_pos in range(left_size - 1, -1, -1): + # restart right_pos if it went over in a previous iteration + if right_pos == right_size: + right_pos = right_size - 1 + + # find first position in right whose value is greater than left's + if allow_exact_matches: + while (right_pos >= 0 and + right_values[right_pos] >= left_values[left_pos]): + right_pos -= 1 + else: + while (right_pos >= 0 and + right_values[right_pos] > left_values[left_pos]): + right_pos -= 1 + right_pos += 1 + + # save positions as the desired index + left_indexer[left_pos] = left_pos + right_indexer[left_pos] = (right_pos + if right_pos != right_size else -1) + + # if needed, verify that tolerance is met + if has_tolerance and right_pos != right_size: + diff = right_values[right_pos] - left_values[left_pos] + if diff > tolerance_: + right_indexer[left_pos] = -1 + + return left_indexer, right_indexer + + +def asof_join_nearest(ndarray[asof_t] left_values, + ndarray[asof_t] right_values, + bint allow_exact_matches=1, + tolerance=None): + + cdef: + Py_ssize_t left_size, right_size, i + ndarray[int64_t] left_indexer, right_indexer, bli, bri, fli, fri + asof_t bdiff, fdiff + + left_size = len(left_values) + right_size = len(right_values) + + left_indexer = np.empty(left_size, dtype=np.int64) + right_indexer = np.empty(left_size, dtype=np.int64) + + # search both forward and backward + bli, bri = asof_join_backward(left_values, right_values, + allow_exact_matches, tolerance) + fli, fri = asof_join_forward(left_values, right_values, + allow_exact_matches, tolerance) + + for i in range(len(bri)): + # choose timestamp from right with smaller difference + if bri[i] != -1 and fri[i] != -1: + bdiff = left_values[bli[i]] - right_values[bri[i]] + fdiff = right_values[fri[i]] - left_values[fli[i]] + right_indexer[i] = bri[i] if bdiff <= fdiff else fri[i] + else: + right_indexer[i] = bri[i] if bri[i] != -1 else fri[i] + left_indexer[i] = bli[i] + + return left_indexer, right_indexer diff --git a/pandas/_libs/join_func_helper.pxi.in b/pandas/_libs/join_func_helper.pxi.in deleted file mode 100644 index b7f604d2fc951..0000000000000 --- a/pandas/_libs/join_func_helper.pxi.in +++ /dev/null @@ -1,405 +0,0 @@ -# cython: boundscheck=False, wraparound=False -""" -Template for each `dtype` helper function for hashtable - -WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in -""" - -#---------------------------------------------------------------------- -# asof_join_by -#---------------------------------------------------------------------- - -from hashtable cimport PyObjectHashTable, UInt64HashTable, Int64HashTable - -{{py: - -# table_type, by_dtype -by_dtypes = [('PyObjectHashTable', 'object'), ('Int64HashTable', 'int64_t'), - ('UInt64HashTable', 'uint64_t')] - -# on_dtype -on_dtypes = ['uint8_t', 'uint16_t', 'uint32_t', 'uint64_t', - 'int8_t', 'int16_t', 'int32_t', 'int64_t', - 'float', 'double'] - -}} - - -{{for table_type, by_dtype in by_dtypes}} -{{for on_dtype in on_dtypes}} - - -def asof_join_backward_{{on_dtype}}_by_{{by_dtype}}( - ndarray[{{on_dtype}}] left_values, - ndarray[{{on_dtype}}] right_values, - ndarray[{{by_dtype}}] left_by_values, - ndarray[{{by_dtype}}] right_by_values, - bint allow_exact_matches=1, - tolerance=None): - - cdef: - Py_ssize_t left_pos, right_pos, left_size, right_size, found_right_pos - ndarray[int64_t] left_indexer, right_indexer - bint has_tolerance = 0 - {{on_dtype}} tolerance_ = 0 - {{on_dtype}} diff = 0 - {{table_type}} hash_table - {{by_dtype}} by_value - - # if we are using tolerance, set our objects - if tolerance is not None: - has_tolerance = 1 - tolerance_ = tolerance - - left_size = len(left_values) - right_size = len(right_values) - - left_indexer = np.empty(left_size, dtype=np.int64) - right_indexer = np.empty(left_size, dtype=np.int64) - - hash_table = {{table_type}}(right_size) - - right_pos = 0 - for left_pos in range(left_size): - # restart right_pos if it went negative in a previous iteration - if right_pos < 0: - right_pos = 0 - - # find last position in right whose value is less than left's - if allow_exact_matches: - while (right_pos < right_size and - right_values[right_pos] <= left_values[left_pos]): - hash_table.set_item(right_by_values[right_pos], right_pos) - right_pos += 1 - else: - while (right_pos < right_size and - right_values[right_pos] < left_values[left_pos]): - hash_table.set_item(right_by_values[right_pos], right_pos) - right_pos += 1 - right_pos -= 1 - - # save positions as the desired index - by_value = left_by_values[left_pos] - found_right_pos = (hash_table.get_item(by_value) - if by_value in hash_table else -1) - left_indexer[left_pos] = left_pos - right_indexer[left_pos] = found_right_pos - - # if needed, verify that tolerance is met - if has_tolerance and found_right_pos != -1: - diff = left_values[left_pos] - right_values[found_right_pos] - if diff > tolerance_: - right_indexer[left_pos] = -1 - - return left_indexer, right_indexer - - -def asof_join_forward_{{on_dtype}}_by_{{by_dtype}}( - ndarray[{{on_dtype}}] left_values, - ndarray[{{on_dtype}}] right_values, - ndarray[{{by_dtype}}] left_by_values, - ndarray[{{by_dtype}}] right_by_values, - bint allow_exact_matches=1, - tolerance=None): - - cdef: - Py_ssize_t left_pos, right_pos, left_size, right_size, found_right_pos - ndarray[int64_t] left_indexer, right_indexer - bint has_tolerance = 0 - {{on_dtype}} tolerance_ = 0 - {{on_dtype}} diff = 0 - {{table_type}} hash_table - {{by_dtype}} by_value - - # if we are using tolerance, set our objects - if tolerance is not None: - has_tolerance = 1 - tolerance_ = tolerance - - left_size = len(left_values) - right_size = len(right_values) - - left_indexer = np.empty(left_size, dtype=np.int64) - right_indexer = np.empty(left_size, dtype=np.int64) - - hash_table = {{table_type}}(right_size) - - right_pos = right_size - 1 - for left_pos in range(left_size - 1, -1, -1): - # restart right_pos if it went over in a previous iteration - if right_pos == right_size: - right_pos = right_size - 1 - - # find first position in right whose value is greater than left's - if allow_exact_matches: - while (right_pos >= 0 and - right_values[right_pos] >= left_values[left_pos]): - hash_table.set_item(right_by_values[right_pos], right_pos) - right_pos -= 1 - else: - while (right_pos >= 0 and - right_values[right_pos] > left_values[left_pos]): - hash_table.set_item(right_by_values[right_pos], right_pos) - right_pos -= 1 - right_pos += 1 - - # save positions as the desired index - by_value = left_by_values[left_pos] - found_right_pos = (hash_table.get_item(by_value) - if by_value in hash_table else -1) - left_indexer[left_pos] = left_pos - right_indexer[left_pos] = found_right_pos - - # if needed, verify that tolerance is met - if has_tolerance and found_right_pos != -1: - diff = right_values[found_right_pos] - left_values[left_pos] - if diff > tolerance_: - right_indexer[left_pos] = -1 - - return left_indexer, right_indexer - - -def asof_join_nearest_{{on_dtype}}_by_{{by_dtype}}( - ndarray[{{on_dtype}}] left_values, - ndarray[{{on_dtype}}] right_values, - ndarray[{{by_dtype}}] left_by_values, - ndarray[{{by_dtype}}] right_by_values, - bint allow_exact_matches=1, - tolerance=None): - - cdef: - Py_ssize_t left_size, right_size, i - ndarray[int64_t] left_indexer, right_indexer, bli, bri, fli, fri - {{on_dtype}} bdiff, fdiff - - left_size = len(left_values) - right_size = len(right_values) - - left_indexer = np.empty(left_size, dtype=np.int64) - right_indexer = np.empty(left_size, dtype=np.int64) - - # search both forward and backward - bli, bri =\ - asof_join_backward_{{on_dtype}}_by_{{by_dtype}}(left_values, - right_values, - left_by_values, - right_by_values, - allow_exact_matches, - tolerance) - fli, fri =\ - asof_join_forward_{{on_dtype}}_by_{{by_dtype}}(left_values, - right_values, - left_by_values, - right_by_values, - allow_exact_matches, - tolerance) - - for i in range(len(bri)): - # choose timestamp from right with smaller difference - if bri[i] != -1 and fri[i] != -1: - bdiff = left_values[bli[i]] - right_values[bri[i]] - fdiff = right_values[fri[i]] - left_values[fli[i]] - right_indexer[i] = bri[i] if bdiff <= fdiff else fri[i] - else: - right_indexer[i] = bri[i] if bri[i] != -1 else fri[i] - left_indexer[i] = bli[i] - - return left_indexer, right_indexer - -{{endfor}} -{{endfor}} - - -# ---------------------------------------------------------------------- -# asof_join -# ---------------------------------------------------------------------- - -ctypedef fused asof_t: - uint8_t - uint16_t - uint32_t - uint64_t - int8_t - int16_t - int32_t - int64_t - float - double - - -def asof_join_backward(ndarray[asof_t] left_values, - ndarray[asof_t] right_values, - bint allow_exact_matches=1, - tolerance=None): - - cdef: - Py_ssize_t left_pos, right_pos, left_size, right_size - ndarray[int64_t] left_indexer, right_indexer - bint has_tolerance = 0 - asof_t tolerance_ = 0 - asof_t diff = 0 - - # if we are using tolerance, set our objects - if tolerance is not None: - has_tolerance = 1 - tolerance_ = tolerance - - left_size = len(left_values) - right_size = len(right_values) - - left_indexer = np.empty(left_size, dtype=np.int64) - right_indexer = np.empty(left_size, dtype=np.int64) - - right_pos = 0 - for left_pos in range(left_size): - # restart right_pos if it went negative in a previous iteration - if right_pos < 0: - right_pos = 0 - - # find last position in right whose value is less than left's - if allow_exact_matches: - while (right_pos < right_size and - right_values[right_pos] <= left_values[left_pos]): - right_pos += 1 - else: - while (right_pos < right_size and - right_values[right_pos] < left_values[left_pos]): - right_pos += 1 - right_pos -= 1 - - # save positions as the desired index - left_indexer[left_pos] = left_pos - right_indexer[left_pos] = right_pos - - # if needed, verify that tolerance is met - if has_tolerance and right_pos != -1: - diff = left_values[left_pos] - right_values[right_pos] - if diff > tolerance_: - right_indexer[left_pos] = -1 - - return left_indexer, right_indexer - - -asof_join_backward_uint8_t = asof_join_backward["uint8_t"] -asof_join_backward_uint16_t = asof_join_backward["uint16_t"] -asof_join_backward_uint32_t = asof_join_backward["uint32_t"] -asof_join_backward_uint64_t = asof_join_backward["uint64_t"] -asof_join_backward_int8_t = asof_join_backward["int8_t"] -asof_join_backward_int16_t = asof_join_backward["int16_t"] -asof_join_backward_int32_t = asof_join_backward["int32_t"] -asof_join_backward_int64_t = asof_join_backward["int64_t"] -asof_join_backward_float = asof_join_backward["float"] -asof_join_backward_double = asof_join_backward["double"] - - -def asof_join_forward(ndarray[asof_t] left_values, - ndarray[asof_t] right_values, - bint allow_exact_matches=1, - tolerance=None): - - cdef: - Py_ssize_t left_pos, right_pos, left_size, right_size - ndarray[int64_t] left_indexer, right_indexer - bint has_tolerance = 0 - asof_t tolerance_ = 0 - asof_t diff = 0 - - # if we are using tolerance, set our objects - if tolerance is not None: - has_tolerance = 1 - tolerance_ = tolerance - - left_size = len(left_values) - right_size = len(right_values) - - left_indexer = np.empty(left_size, dtype=np.int64) - right_indexer = np.empty(left_size, dtype=np.int64) - - right_pos = right_size - 1 - for left_pos in range(left_size - 1, -1, -1): - # restart right_pos if it went over in a previous iteration - if right_pos == right_size: - right_pos = right_size - 1 - - # find first position in right whose value is greater than left's - if allow_exact_matches: - while (right_pos >= 0 and - right_values[right_pos] >= left_values[left_pos]): - right_pos -= 1 - else: - while (right_pos >= 0 and - right_values[right_pos] > left_values[left_pos]): - right_pos -= 1 - right_pos += 1 - - # save positions as the desired index - left_indexer[left_pos] = left_pos - right_indexer[left_pos] = (right_pos - if right_pos != right_size else -1) - - # if needed, verify that tolerance is met - if has_tolerance and right_pos != right_size: - diff = right_values[right_pos] - left_values[left_pos] - if diff > tolerance_: - right_indexer[left_pos] = -1 - - return left_indexer, right_indexer - - -asof_join_forward_uint8_t = asof_join_forward["uint8_t"] -asof_join_forward_uint16_t = asof_join_forward["uint16_t"] -asof_join_forward_uint32_t = asof_join_forward["uint32_t"] -asof_join_forward_uint64_t = asof_join_forward["uint64_t"] -asof_join_forward_int8_t = asof_join_forward["int8_t"] -asof_join_forward_int16_t = asof_join_forward["int16_t"] -asof_join_forward_int32_t = asof_join_forward["int32_t"] -asof_join_forward_int64_t = asof_join_forward["int64_t"] -asof_join_forward_float = asof_join_forward["float"] -asof_join_forward_double = asof_join_forward["double"] - - -def asof_join_nearest(ndarray[asof_t] left_values, - ndarray[asof_t] right_values, - bint allow_exact_matches=1, - tolerance=None): - - cdef: - Py_ssize_t left_size, right_size, i - ndarray[int64_t] left_indexer, right_indexer, bli, bri, fli, fri - asof_t bdiff, fdiff - - left_size = len(left_values) - right_size = len(right_values) - - left_indexer = np.empty(left_size, dtype=np.int64) - right_indexer = np.empty(left_size, dtype=np.int64) - - # search both forward and backward - bli, bri = asof_join_backward(left_values, right_values, - allow_exact_matches, tolerance) - fli, fri = asof_join_forward(left_values, right_values, - allow_exact_matches, tolerance) - - for i in range(len(bri)): - # choose timestamp from right with smaller difference - if bri[i] != -1 and fri[i] != -1: - bdiff = left_values[bli[i]] - right_values[bri[i]] - fdiff = right_values[fri[i]] - left_values[fli[i]] - right_indexer[i] = bri[i] if bdiff <= fdiff else fri[i] - else: - right_indexer[i] = bri[i] if bri[i] != -1 else fri[i] - left_indexer[i] = bli[i] - - return left_indexer, right_indexer - - -asof_join_nearest_uint8_t = asof_join_nearest["uint8_t"] -asof_join_nearest_uint16_t = asof_join_nearest["uint16_t"] -asof_join_nearest_uint32_t = asof_join_nearest["uint32_t"] -asof_join_nearest_uint64_t = asof_join_nearest["uint64_t"] -asof_join_nearest_int8_t = asof_join_nearest["int8_t"] -asof_join_nearest_int16_t = asof_join_nearest["int16_t"] -asof_join_nearest_int32_t = asof_join_nearest["int32_t"] -asof_join_nearest_int64_t = asof_join_nearest["int64_t"] -asof_join_nearest_float = asof_join_nearest["float"] -asof_join_nearest_double = asof_join_nearest["double"] diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index ed9466795f97f..5d4a0c718499a 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -34,8 +34,7 @@ is_datetimelike, ensure_int64, ensure_float64, - ensure_object, - _get_dtype) + ensure_object) from pandas.core.dtypes.missing import na_value_for_dtype, isnull from pandas.core.internals import (items_overlap_with_suffix, concatenate_block_managers) @@ -1190,14 +1189,13 @@ def get_result(self): return result -def _asof_function(direction, on_type): - name = 'asof_join_{dir}_{on}'.format(dir=direction, on=on_type) +def _asof_function(direction): + name = 'asof_join_{dir}'.format(dir=direction) return getattr(libjoin, name, None) -def _asof_by_function(direction, on_type, by_type): - name = 'asof_join_{dir}_{on}_by_{by}'.format( - dir=direction, on=on_type, by=by_type) +def _asof_by_function(direction): + name = 'asof_join_{dir}_on_X_by_Y'.format(dir=direction) return getattr(libjoin, name, None) @@ -1207,29 +1205,6 @@ def _asof_by_function(direction, on_type, by_type): 'object': ensure_object, } -_cython_types = { - 'uint8': 'uint8_t', - 'uint32': 'uint32_t', - 'uint16': 'uint16_t', - 'uint64': 'uint64_t', - 'int8': 'int8_t', - 'int32': 'int32_t', - 'int16': 'int16_t', - 'int64': 'int64_t', - 'float16': 'error', - 'float32': 'float', - 'float64': 'double', -} - - -def _get_cython_type(dtype): - """ Given a dtype, return a C name like 'int64_t' or 'double' """ - type_name = _get_dtype(dtype).name - ctype = _cython_types.get(type_name, 'object') - if ctype == 'error': - raise MergeError('unsupported type: {type}'.format(type=type_name)) - return ctype - def _get_cython_type_upcast(dtype): """ Upcast a dtype to 'int64_t', 'double', or 'object' """ @@ -1438,8 +1413,7 @@ def flip(xs): right_by_values = by_type_caster(right_by_values) # choose appropriate function by type - on_type = _get_cython_type(left_values.dtype) - func = _asof_by_function(self.direction, on_type, by_type) + func = _asof_by_function(self.direction) return func(left_values, right_values, left_by_values, @@ -1448,8 +1422,7 @@ def flip(xs): tolerance) else: # choose appropriate function by type - on_type = _get_cython_type(left_values.dtype) - func = _asof_function(self.direction, on_type) + func = _asof_function(self.direction) return func(left_values, right_values, self.allow_exact_matches, diff --git a/setup.py b/setup.py index adffddc61cbac..cb52db98905d3 100755 --- a/setup.py +++ b/setup.py @@ -76,7 +76,6 @@ def is_platform_windows(): '_libs/algos_take_helper.pxi.in', '_libs/algos_rank_helper.pxi.in'], 'groupby': ['_libs/groupby_helper.pxi.in'], - 'join': ['_libs/join_func_helper.pxi.in'], 'hashtable': ['_libs/hashtable_class_helper.pxi.in', '_libs/hashtable_func_helper.pxi.in'], 'index': ['_libs/index_class_helper.pxi.in'], @@ -531,8 +530,7 @@ def srcpath(name=None, suffix='.pyx', subdir='src'): 'pyxfile': '_libs/interval', 'depends': _pxi_dep['interval']}, '_libs.join': { - 'pyxfile': '_libs/join', - 'depends': _pxi_dep['join']}, + 'pyxfile': '_libs/join'}, '_libs.lib': { 'pyxfile': '_libs/lib', 'include': common_include + ts_include,
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/23214
2018-10-17T23:05:36Z
2018-10-18T16:47:53Z
2018-10-18T16:47:53Z
2018-10-19T12:21:56Z
TST/CLN: Parameterize test in sparse/test_indexing
diff --git a/pandas/tests/sparse/test_indexing.py b/pandas/tests/sparse/test_indexing.py index 7c7e450c966bf..1ecb1f4e8de58 100644 --- a/pandas/tests/sparse/test_indexing.py +++ b/pandas/tests/sparse/test_indexing.py @@ -424,38 +424,35 @@ def test_reindex_nearest(self): expected = pd.Series([0, np.nan, np.nan, 2], target).to_sparse() tm.assert_sp_series_equal(expected, actual) - def tests_indexing_with_sparse(self): - # GH 13985 - - for kind in ['integer', 'block']: - for fill in [True, False, np.nan]: - arr = pd.SparseArray([1, 2, 3], kind=kind) - indexer = pd.SparseArray([True, False, True], fill_value=fill, - dtype=bool) - - tm.assert_sp_array_equal(pd.SparseArray([1, 3], kind=kind), - arr[indexer],) - - s = pd.SparseSeries(arr, index=['a', 'b', 'c'], - dtype=np.float64) - - exp = pd.SparseSeries( - [1, 3], index=['a', 'c'], - dtype=SparseDtype(np.float64, s.fill_value), - kind=kind - ) - tm.assert_sp_series_equal(s[indexer], exp) - tm.assert_sp_series_equal(s.loc[indexer], exp) - tm.assert_sp_series_equal(s.iloc[indexer], exp) - - indexer = pd.SparseSeries(indexer, index=['a', 'b', 'c']) - tm.assert_sp_series_equal(s[indexer], exp) - tm.assert_sp_series_equal(s.loc[indexer], exp) - - msg = ("iLocation based boolean indexing cannot use an " - "indexable as a mask") - with tm.assert_raises_regex(ValueError, msg): - s.iloc[indexer] + @pytest.mark.parametrize("kind", ["integer", "block"]) + @pytest.mark.parametrize("fill", [True, False, np.nan]) + def tests_indexing_with_sparse(self, kind, fill): + # see gh-13985 + arr = pd.SparseArray([1, 2, 3], kind=kind) + indexer = pd.SparseArray([True, False, True], + fill_value=fill, + dtype=bool) + + expected = arr[indexer] + result = pd.SparseArray([1, 3], kind=kind) + tm.assert_sp_array_equal(result, expected) + + s = pd.SparseSeries(arr, index=["a", "b", "c"], dtype=np.float64) + expected = pd.SparseSeries([1, 3], index=["a", "c"], kind=kind, + dtype=SparseDtype(np.float64, s.fill_value)) + + tm.assert_sp_series_equal(s[indexer], expected) + tm.assert_sp_series_equal(s.loc[indexer], expected) + tm.assert_sp_series_equal(s.iloc[indexer], expected) + + indexer = pd.SparseSeries(indexer, index=["a", "b", "c"]) + tm.assert_sp_series_equal(s[indexer], expected) + tm.assert_sp_series_equal(s.loc[indexer], expected) + + msg = ("iLocation based boolean indexing cannot " + "use an indexable as a mask") + with tm.assert_raises_regex(ValueError, msg): + s.iloc[indexer] class TestSparseSeriesMultiIndexing(TestSparseSeriesIndexing):
Title is self-explanatory.
https://api.github.com/repos/pandas-dev/pandas/pulls/23213
2018-10-17T22:26:39Z
2018-10-18T11:39:42Z
2018-10-18T11:39:42Z
2018-10-18T16:10:40Z
CLN: Address some TODO comments
diff --git a/pandas/core/common.py b/pandas/core/common.py index 8bbaabe8c08af..f6e40faa79740 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -68,17 +68,6 @@ def consensus_name_attr(objs): return name -# TODO: only used once in frame.py; belongs elsewhere? -def get_info_slice(obj, indexer): - """Slice the info axis of `obj` with `indexer`.""" - if not hasattr(obj, '_info_axis_number'): - msg = 'object of type {typ!r} has no info axis' - raise TypeError(msg.format(typ=type(obj).__name__)) - slices = [slice(None)] * obj.ndim - slices[obj._info_axis_number] = indexer - return tuple(slices) - - def maybe_box(indexer, values, obj, key): # if we have multiples coming back, box em @@ -432,21 +421,6 @@ def random_state(state=None): "RandomState, or None") -# TODO: only used once in indexes.api; belongs elsewhere? -def get_distinct_objs(objs): - """ - Return a list with distinct elements of "objs" (different ids). - Preserves order. - """ - ids = set() - res = [] - for obj in objs: - if not id(obj) in ids: - ids.add(id(obj)) - res.append(obj) - return res - - def _pipe(obj, func, *args, **kwargs): """ Apply a function ``func`` to object ``obj`` either by passing obj as the diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 8f3873b4299a5..e8acb37ad3b58 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3157,6 +3157,14 @@ def select_dtypes(self, include=None, exclude=None): 4 True 1.0 5 False 2.0 """ + def _get_info_slice(obj, indexer): + """Slice the info axis of `obj` with `indexer`.""" + if not hasattr(obj, '_info_axis_number'): + msg = 'object of type {typ!r} has no info axis' + raise TypeError(msg.format(typ=type(obj).__name__)) + slices = [slice(None)] * obj.ndim + slices[obj._info_axis_number] = indexer + return tuple(slices) if not is_list_like(include): include = (include,) if include is not None else () @@ -3205,7 +3213,7 @@ def is_dtype_instance_mapper(idx, dtype): exclude_these.iloc[idx] = not any(map(f, exclude)) dtype_indexer = include_these & exclude_these - return self.loc[com.get_info_slice(self, dtype_indexer)] + return self.loc[_get_info_slice(self, dtype_indexer)] def _box_item_values(self, key, values): items = self.columns[self.columns.get_loc(key)] diff --git a/pandas/core/generic.py b/pandas/core/generic.py index ba050bfc8db77..38688a7e60566 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4069,16 +4069,6 @@ def _reindex_with_indexers(self, reindexers, fill_value=None, copy=False, return self._constructor(new_data).__finalize__(self) - # TODO: unused; remove? - def _reindex_axis(self, new_index, fill_method, axis, copy): - new_data = self._data.reindex_axis(new_index, axis=axis, - method=fill_method, copy=copy) - - if new_data is self._data and not copy: - return self - else: - return self._constructor(new_data).__finalize__(self) - def filter(self, items=None, like=None, regex=None, axis=None): """ Subset rows or columns of dataframe according to labels in diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index e50a4b099a8e1..6e0c5e1bc2fe0 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -53,9 +53,23 @@ def _get_objs_combined_axis(objs, intersect=False, axis=0, sort=True): return _get_combined_index(obs_idxes, intersect=intersect, sort=sort) +def _get_distinct_objs(objs): + """ + Return a list with distinct elements of "objs" (different ids). + Preserves order. + """ + ids = set() + res = [] + for obj in objs: + if not id(obj) in ids: + ids.add(id(obj)) + res.append(obj) + return res + + def _get_combined_index(indexes, intersect=False, sort=False): # TODO: handle index names! - indexes = com.get_distinct_objs(indexes) + indexes = _get_distinct_objs(indexes) if len(indexes) == 0: index = Index([]) elif len(indexes) == 1: diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 56b6dc7051d9f..8c94ac2ea8256 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -511,16 +511,13 @@ def _maybe_cast_slice_bound(self, label, side, kind): return label - def _get_string_slice(self, key, use_lhs=True, use_rhs=True): - freq = getattr(self, 'freqstr', - getattr(self, 'inferred_freq', None)) + def _get_string_slice(self, key): if is_integer(key) or is_float(key) or key is NaT: self._invalid_indexer('slice', key) - loc = self._partial_td_slice(key, freq, use_lhs=use_lhs, - use_rhs=use_rhs) + loc = self._partial_td_slice(key) return loc - def _partial_td_slice(self, key, freq, use_lhs=True, use_rhs=True): + def _partial_td_slice(self, key): # given a key, try to figure out a location for a partial slice if not isinstance(key, compat.string_types): @@ -528,43 +525,6 @@ def _partial_td_slice(self, key, freq, use_lhs=True, use_rhs=True): raise NotImplementedError - # TODO(wesm): dead code - # parsed = _coerce_scalar_to_timedelta_type(key, box=True) - - # is_monotonic = self.is_monotonic - - # # figure out the resolution of the passed td - # # and round to it - - # # t1 = parsed.round(reso) - - # t2 = t1 + to_offset(parsed.resolution) - Timedelta(1, 'ns') - - # stamps = self.asi8 - - # if is_monotonic: - - # # we are out of range - # if (len(stamps) and ((use_lhs and t1.value < stamps[0] and - # t2.value < stamps[0]) or - # ((use_rhs and t1.value > stamps[-1] and - # t2.value > stamps[-1])))): - # raise KeyError - - # # a monotonic (sorted) series can be sliced - # left = (stamps.searchsorted(t1.value, side='left') - # if use_lhs else None) - # right = (stamps.searchsorted(t2.value, side='right') - # if use_rhs else None) - - # return slice(left, right) - - # lhs_mask = (stamps >= t1.value) if use_lhs else True - # rhs_mask = (stamps <= t2.value) if use_rhs else True - - # # try to find a the dates - # return (lhs_mask & rhs_mask).nonzero()[0] - @Substitution(klass='TimedeltaIndex') @Appender(_shared_docs['searchsorted']) def searchsorted(self, value, side='left', sorter=None): diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 214fcb097f736..6fb1184f48b69 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2812,9 +2812,7 @@ def _astype(self, dtype, mgr=None, **kwargs): def _can_hold_element(self, element): tipo = maybe_infer_dtype_type(element) if tipo is not None: - # TODO: this still uses asarray, instead of dtype.type - element = np.array(element) - return element.dtype == _NS_DTYPE or element.dtype == np.int64 + return tipo == _NS_DTYPE or tipo == np.int64 return (is_integer(element) or isinstance(element, datetime) or isna(element)) diff --git a/pandas/tests/frame/test_mutate_columns.py b/pandas/tests/frame/test_mutate_columns.py index 51ffe2966b4e5..102cc52aa46cb 100644 --- a/pandas/tests/frame/test_mutate_columns.py +++ b/pandas/tests/frame/test_mutate_columns.py @@ -233,7 +233,7 @@ def test_pop(self): self.frame['foo'] = 'bar' self.frame.pop('foo') assert 'foo' not in self.frame - # TODO assert self.frame.columns.name == 'baz' + assert self.frame.columns.name == 'baz' # gh-10912: inplace ops cause caching issue a = DataFrame([[1, 2, 3], [4, 5, 6]], columns=[
- [x] closes #23098 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` I am technically moving some public (non top level) helper functions and making them private, but I don't think it warrants a depreciation.
https://api.github.com/repos/pandas-dev/pandas/pulls/23208
2018-10-17T18:34:36Z
2018-10-19T13:02:29Z
2018-10-19T13:02:29Z
2018-10-19T16:52:49Z
TST: bare-bones fixture for timedelta array tests
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index bfce5fb1462d9..a13eb8dec51d1 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -34,7 +34,7 @@ def datetime_index(request): A fixture to provide DatetimeIndex objects with different frequencies. Most DatetimeArray behavior is already tested in DatetimeIndex tests, - so here we just test that the DatetimeIndex behavior matches + so here we just test that the DatetimeArray behavior matches the DatetimeIndex behavior. """ freqstr = request.param @@ -45,6 +45,18 @@ def datetime_index(request): return pi +@pytest.fixture +def timedelta_index(request): + """ + A fixture to provide TimedeltaIndex objects with different frequencies. + Most TimedeltaArray behavior is already tested in TimedeltaIndex tests, + so here we just test that the TimedeltaArray behavior matches + the TimedeltaIndex behavior. + """ + # TODO: flesh this out + return pd.TimedeltaIndex(['1 Day', '3 Hours', 'NaT']) + + class TestDatetimeArray(object): def test_from_dti(self, tz_naive_fixture): @@ -122,6 +134,34 @@ def test_astype_object(self): assert asobj.dtype == 'O' assert list(asobj) == list(tdi) + def test_to_pytimedelta(self, timedelta_index): + tdi = timedelta_index + arr = TimedeltaArrayMixin(tdi) + + expected = tdi.to_pytimedelta() + result = arr.to_pytimedelta() + + tm.assert_numpy_array_equal(result, expected) + + def test_total_seconds(self, timedelta_index): + tdi = timedelta_index + arr = TimedeltaArrayMixin(tdi) + + expected = tdi.total_seconds() + result = arr.total_seconds() + + tm.assert_numpy_array_equal(result, expected.values) + + @pytest.mark.parametrize('propname', pd.TimedeltaIndex._field_ops) + def test_int_properties(self, timedelta_index, propname): + tdi = timedelta_index + arr = TimedeltaArrayMixin(tdi) + + result = getattr(arr, propname) + expected = np.array(getattr(tdi, propname), dtype=result.dtype) + + tm.assert_numpy_array_equal(result, expected) + class TestPeriodArray(object):
Broken off from #23140. The fixture needs to be fleshed out, but for now I just want to get it in place, since already other PRs need it. - [ ] closes #xxxx - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/23207
2018-10-17T16:29:47Z
2018-10-19T13:00:47Z
2018-10-19T13:00:47Z
2018-10-23T03:28:02Z
validate min/max axis
diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py index d42be56963569..a4232ca2ebf78 100644 --- a/pandas/compat/numpy/function.py +++ b/pandas/compat/numpy/function.py @@ -360,3 +360,24 @@ def validate_resampler_func(method, args, kwargs): "{func}() instead".format(func=method))) else: raise TypeError("too many arguments passed in") + + +def validate_minmax_axis(axis): + """ + Ensure that the axis argument passed to min, max, argmin, or argmax is + zero or None, as otherwise it will be incorrectly ignored. + + Parameters + ---------- + axis : int or None + + Raises + ------ + ValueError + """ + ndim = 1 # hard-coded for Index + if axis is None: + return + if axis >= ndim or (axis < 0 and ndim + axis < 0): + raise ValueError("`axis` must be fewer than the number of " + "dimensions ({ndim})".format(ndim=ndim)) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 8e919ba3599fc..d9152c50309eb 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -431,6 +431,7 @@ def min(self, axis=None, *args, **kwargs): numpy.ndarray.min """ nv.validate_min(args, kwargs) + nv.validate_minmax_axis(axis) try: i8 = self.asi8 @@ -459,6 +460,7 @@ def argmin(self, axis=None, *args, **kwargs): numpy.ndarray.argmin """ nv.validate_argmin(args, kwargs) + nv.validate_minmax_axis(axis) i8 = self.asi8 if self.hasnans: @@ -479,6 +481,7 @@ def max(self, axis=None, *args, **kwargs): numpy.ndarray.max """ nv.validate_max(args, kwargs) + nv.validate_minmax_axis(axis) try: i8 = self.asi8 @@ -507,6 +510,7 @@ def argmax(self, axis=None, *args, **kwargs): numpy.ndarray.argmax """ nv.validate_argmax(args, kwargs) + nv.validate_minmax_axis(axis) i8 = self.asi8 if self.hasnans: diff --git a/pandas/tests/indexes/datetimelike.py b/pandas/tests/indexes/datetimelike.py index e32e18ea0ec4a..7af8b259fa137 100644 --- a/pandas/tests/indexes/datetimelike.py +++ b/pandas/tests/indexes/datetimelike.py @@ -8,6 +8,18 @@ class DatetimeLike(Base): + def test_argmax_axis_invalid(self): + # GH#23081 + rng = self.create_index() + with pytest.raises(ValueError): + rng.argmax(axis=1) + with pytest.raises(ValueError): + rng.argmin(axis=2) + with pytest.raises(ValueError): + rng.min(axis=-2) + with pytest.raises(ValueError): + rng.max(axis=-3) + def test_can_hold_identifiers(self): idx = self.create_index() key = idx[0]
Broken off from #23140. - [x] closes #23081 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/23206
2018-10-17T16:18:25Z
2018-10-18T11:27:18Z
2018-10-18T11:27:18Z
2018-10-23T03:28:19Z
implement TimedeltaArray asm8, to_timedelta64
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index ac90483513af5..b0b1397086e02 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -707,6 +707,22 @@ def tz_localize(self, tz, ambiguous='raise', errors='raise'): # ---------------------------------------------------------------- # Conversion Methods - Vectorized analogues of Timestamp methods + def to_datetime64(self): + """ + Return numpy datetime64[ns] representation of self. For timezone-aware + cases, the returned array represents UTC timestamps. + + Returns + ------- + ndarray[datetime64[ns]] + """ + return self.asi8.view('M8[ns]') + + @property + def asm8(self): + """Vectorized analogue of Timestamp.asm8""" + return self.to_datetime64() + def to_pydatetime(self): """ Return Datetime Array/Index as object ndarray of datetime.datetime diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 4904a90ab7b2b..eac2d0a23c798 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -355,6 +355,31 @@ def to_pytimedelta(self): """ return tslibs.ints_to_pytimedelta(self.asi8) + def to_timedelta64(self): + """ + Return numpy array with timedelta64[ns] dtype + + Returns + ------- + ndarray[timedelta64[ns]] + + Notes + ----- + This returns a view on self, not a copy. + + See also + -------- + Timedelta.to_timedelta64 + """ + return self.asi8.view('m8[ns]') + + @property + def asm8(self): + """ + Vectorized analogue of Timedelta.asm8 + """ + return self.to_timedelta64() + days = _field_accessor("days", "days", " Number of days for each element. ") seconds = _field_accessor("seconds", "seconds", diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index d0099aed00285..eeb173dfa9bb4 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -106,6 +106,30 @@ def test_to_period(self, datetime_index, freqstr): # an EA-specific tm.assert_ function tm.assert_index_equal(pd.Index(result), pd.Index(expected)) + def test_asm8(self, datetime_index): + dti = datetime_index + arr = DatetimeArrayMixin(dti) + + expected = np.array([x.asm8 for x in dti], dtype='M8[ns]') + + result = dti.asm8 + tm.assert_numpy_array_equal(result, expected) + + result = arr.asm8 + tm.assert_numpy_array_equal(result, expected) + + def test_to_datetime64(self, datetime_index): + dti = datetime_index + arr = DatetimeArrayMixin(dti) + + expected = np.array([x.asm8 for x in dti], dtype='M8[ns]') + + result = dti.to_datetime64() + tm.assert_numpy_array_equal(result, expected) + + result = arr.to_datetime64() + tm.assert_numpy_array_equal(result, expected) + @pytest.mark.parametrize('propname', pd.DatetimeIndex._bool_ops) def test_bool_properties(self, datetime_index, propname): # in this case _bool_ops is just `is_leap_year` @@ -148,6 +172,30 @@ def test_astype_object(self): assert asobj.dtype == 'O' assert list(asobj) == list(tdi) + def test_asm8(self): + tdi = pd.TimedeltaIndex(['1 Hour', '3 Hours']) + arr = TimedeltaArrayMixin(tdi) + + expected = np.array([3600, 10800], dtype='m8[ns]') * 1e9 + + result = tdi.asm8 + tm.assert_numpy_array_equal(result, expected) + + result = arr.asm8 + tm.assert_numpy_array_equal(result, expected) + + def test_to_timedelta64(self): + tdi = pd.TimedeltaIndex(['1 Hour', '3 Hours']) + arr = TimedeltaArrayMixin(tdi) + + expected = np.array([3600, 10800], dtype='m8[ns]') * 1e9 + + result = tdi.to_timedelta64() + tm.assert_numpy_array_equal(result, expected) + + result = arr.to_timedelta64() + tm.assert_numpy_array_equal(result, expected) + def test_to_pytimedelta(self, timedelta_index): tdi = timedelta_index arr = TimedeltaArrayMixin(tdi)
For compat with Timedelta scalar - [x] closes #22632 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/23205
2018-10-17T15:59:52Z
2018-10-23T02:55:07Z
2018-10-23T02:55:07Z
2018-10-23T09:06:41Z